protected boolean _useStatic(
     SerializerProvider provider, BeanProperty property, JavaType referredType) {
   // First: no serializer for `Object.class`, must be dynamic
   if (referredType.isJavaLangObject()) {
     return false;
   }
   // but if type is final, might as well fetch
   if (referredType.isFinal()) { // or should we allow annotation override? (only if requested...)
     return true;
   }
   // also: if indicated by typing, should be considered static
   if (referredType.useStaticType()) {
     return true;
   }
   // if neither, maybe explicit annotation?
   AnnotationIntrospector intr = provider.getAnnotationIntrospector();
   if ((intr != null) && (property != null)) {
     Annotated ann = property.getMember();
     if (ann != null) {
       JsonSerialize.Typing t = intr.findSerializationTyping(property.getMember());
       if (t == JsonSerialize.Typing.STATIC) {
         return true;
       }
       if (t == JsonSerialize.Typing.DYNAMIC) {
         return false;
       }
     }
   }
   // and finally, may be forced by global static typing (unlikely...)
   return provider.isEnabled(MapperFeature.USE_STATIC_TYPING);
 }
Example #2
0
  //  @Override
  public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
      throws JsonMappingException {
    /* 29-Sep-2012, tatu: Actually, we need to do much more contextual
     *    checking here since we finally know for sure the property,
     *    and it may have overrides
     */
    JsonSerializer<?> ser = null;
    JsonSerializer<?> keySer = null;

    // First: if we have a property, may have property-annotation overrides
    if (property != null) {
      AnnotatedMember m = property.getMember();
      if (m != null) {
        Object serDef;
        final AnnotationIntrospector intr = provider.getAnnotationIntrospector();
        serDef = intr.findKeySerializer(m);
        if (serDef != null) {
          keySer = provider.serializerInstance(m, serDef);
        }
        serDef = intr.findContentSerializer(m);
        if (serDef != null) {
          ser = provider.serializerInstance(m, serDef);
        }
      }
    }
    if (ser == null) {
      ser = _valueSerializer;
    }
    if (ser == null) {
      // 30-Sep-2012, tatu: One more thing -- if explicit content type is annotated,
      //   we can consider it a static case as well.
      if (_valueTypeIsStatic || hasContentTypeAnnotation(provider, property)) {
        ser = provider.findValueSerializer(_valueType, property);
      }
    } else if (ser instanceof ContextualSerializer) {
      ser = ((ContextualSerializer) ser).createContextual(provider, property);
    }
    if (keySer == null) {
      keySer = _keySerializer;
    }
    if (keySer == null) {
      keySer = provider.findKeySerializer(_keyType, property);
    } else if (keySer instanceof ContextualSerializer) {
      keySer = ((ContextualSerializer) keySer).createContextual(provider, property);
    }
    HashSet<String> ignored = this._ignoredEntries;
    AnnotationIntrospector intr = provider.getAnnotationIntrospector();
    if (intr != null && property != null) {
      String[] moreToIgnore = intr.findPropertiesToIgnore(property.getMember());
      if (moreToIgnore != null) {
        ignored = (ignored == null) ? new HashSet<String>() : new HashSet<String>(ignored);
        for (String str : moreToIgnore) {
          ignored.add(str);
        }
      }
    }
    return withResolved(property, keySer, ser, ignored);
  }
 protected JsonSchema propertySchema(BeanProperty prop) throws JsonMappingException {
   if (prop == null) {
     throw new IllegalArgumentException("Null property");
   }
   SchemaFactoryWrapper visitor = wrapperFactory.getWrapper(getProvider());
   JsonSerializer<Object> ser = getSer(prop);
   if (ser != null) {
     JavaType type = prop.getType();
     if (type == null) {
       throw new IllegalStateException("Missing type for property '" + prop.getName() + "'");
     }
     ser.acceptJsonFormatVisitor(visitor, type);
   }
   return visitor.finalSchema();
 }
Example #4
0
  /**
   * Gets the value specified by the BeanProperty
   *
   * @param instance Object to get the value from
   * @param bp the property to get
   * @return the value of the property if it exists
   */
  protected final Object getBeanValue(Object instance, BeanProperty bp) {
    String propertyName = bp.getName();
    if (bp.isRead()) {
      try {
        Object value = bp.get(instance);
        if (value != null && descriptor != null) {
          SerializationDescriptor subDescriptor =
              (SerializationDescriptor) descriptor.get(propertyName);
          if (subDescriptor != null) {
            PropertyProxy subProxy = PropertyProxyRegistry.getProxyAndRegister(value);
            subProxy = (PropertyProxy) subProxy.clone();
            subProxy.setDescriptor(subDescriptor);
            subProxy.setDefaultInstance(value);
            value = subProxy;
          }
        }
        return value;
      } catch (Exception e) {
        SerializationContext context = getSerializationContext();

        // Log failed property set errors
        if (Log.isWarn() && logPropertyErrors(context)) {
          Logger log = Log.getLogger(LOG_CATEGORY);
          log.warn(
              "Failed to get property {0} on type {1}.",
              new Object[] {propertyName, getAlias(instance)}, e);
        }

        if (!ignorePropertyErrors(context)) {
          // Failed to get property '{propertyName}' on type '{className}'.
          MessageException ex = new MessageException();
          ex.setMessage(
              FAILED_PROPERTY_READ_ERROR, new Object[] {propertyName, getAlias(instance)});
          ex.setRootCause(e);
          throw ex;
        }
      }
    } else {
      SerializationContext context = getSerializationContext();
      if (!ignorePropertyErrors(context)) {
        // Property '{propertyName}' not readable from class '{alias}'.
        MessageException ex = new MessageException();
        ex.setMessage(NON_READABLE_PROPERTY_ERROR, new Object[] {propertyName, getAlias(instance)});
        throw ex;
      }
    }
    return null;
  }
 @Override
 public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
     throws JsonMappingException {
   TypeSerializer vts = _valueTypeSerializer;
   if (vts != null) {
     vts = vts.forProperty(property);
   }
   JsonSerializer<?> ser = findContentSerializer(provider, property);
   if (ser == null) {
     ser = _valueSerializer;
     if (ser == null) {
       // A few conditions needed to be able to fetch serializer here:
       if (_useStatic(provider, property, _referredType)) {
         ser = _findSerializer(provider, _referredType, property);
       }
     } else {
       ser = provider.handlePrimaryContextualization(ser, property);
     }
   }
   // Also: may want to have more refined exclusion based on referenced value
   JsonInclude.Include contentIncl = _contentInclusion;
   if (property != null) {
     JsonInclude.Value incl = property.findPropertyInclusion(provider.getConfig(), Optional.class);
     JsonInclude.Include newIncl = incl.getContentInclusion();
     if ((newIncl != contentIncl) && (newIncl != JsonInclude.Include.USE_DEFAULTS)) {
       contentIncl = newIncl;
     }
   }
   return withResolved(property, vts, ser, _unwrapper, contentIncl);
 }
Example #6
0
 /**
  * Extract index string from non-nested property name. If index is found, it is stripped from bean
  * property name. If no index is found, it returns <code>null</code>.
  */
 protected String extractIndex(BeanProperty bp) {
   bp.index = null;
   String name = bp.name;
   int lastNdx = name.length() - 1;
   if (lastNdx < 0) {
     return null;
   }
   if (name.charAt(lastNdx) == ']') {
     int leftBracketNdx = name.lastIndexOf('[');
     if (leftBracketNdx != -1) {
       bp.name = name.substring(0, leftBracketNdx);
       bp.index = name.substring(leftBracketNdx + 1, lastNdx);
       return bp.index;
     }
   }
   return null;
 }
  /** Add appropriate changes to support update. */
  void handleUpdate(Object id, PersistRequestBean<T> updateRequest, CacheChangeSet changeSet) {

    queryCacheClear(changeSet);

    if (beanCache == null) {
      // query caching only
      return;
    }

    List<BeanPropertyAssocMany<?>> manyCollections = updateRequest.getUpdatedManyCollections();
    if (manyCollections != null) {
      for (BeanPropertyAssocMany<?> many : manyCollections) {
        Object details = many.getValue(updateRequest.getEntityBean());
        CachedManyIds entry = createManyIds(many, details);
        if (entry != null) {
          changeSet.addManyPut(desc, many.getName(), id, entry);
        }
      }
    }

    // check if the bean itself was updated
    if (!updateRequest.isUpdatedManysOnly()) {

      boolean updateNaturalKey = false;

      Map<String, Object> changes = new LinkedHashMap<>();
      EntityBean bean = updateRequest.getEntityBean();
      boolean[] dirtyProperties = updateRequest.getDirtyProperties();
      for (int i = 0; i < dirtyProperties.length; i++) {
        if (dirtyProperties[i]) {
          BeanProperty property = desc.propertiesIndex[i];
          if (property.isCacheDataInclude()) {
            Object val = property.getCacheDataValue(bean);
            changes.put(property.getName(), val);
            if (property.isNaturalKey()) {
              updateNaturalKey = true;
              changeSet.addNaturalKeyPut(desc, id, val);
            }
          }
        }
      }

      changeSet.addBeanUpdate(desc, id, changes, updateNaturalKey, updateRequest.getVersion());
    }
  }
 protected JsonSerializer<Object> getSer(BeanProperty prop) throws JsonMappingException {
   JsonSerializer<Object> ser = null;
   // 26-Jul-2013, tatu: This is ugly, should NOT require cast...
   if (prop instanceof BeanPropertyWriter) {
     ser = ((BeanPropertyWriter) prop).getSerializer();
   }
   if (ser == null) {
     ser = getProvider().findValueSerializer(prop.getType(), prop);
   }
   return ser;
 }
  public static String getQueryDefault(
      Class<? extends AbstractEntity> entityClass,
      Map<String, BeanProperty> map,
      AbstractDto dto,
      Integer campoOrdenacao) {

    String select = "SELECT o FROM " + entityClass.getSimpleName() + " o WHERE 0=0";

    StringBuffer where = new StringBuffer();
    for (String key : map.keySet()) {

      BeanProperty prop = map.get(key);

      if (prop.getType().equals(String.class)) {

        where.append(" AND UPPER(o." + prop.getName() + ") LIKE UPPER(:" + prop.getName() + ")");

      } else {
        where.append(" AND o." + prop.getName() + " = :" + prop.getName());
      }
    }
    if (campoOrdenacao != null) {
      where.append(" ORDER BY " + campoOrdenacao);
    }
    String query = select + where.toString();
    return query;
  }
 // !!! TODO: added late in 2.7 in `jackson-databind`: remove from 2.8
 protected JsonSerializer<?> findContentSerializer(
     SerializerProvider serializers, BeanProperty property) throws JsonMappingException {
   if (property != null) {
     AnnotatedMember m = property.getMember();
     final AnnotationIntrospector intr = serializers.getAnnotationIntrospector();
     if (m != null) {
       Object serDef = intr.findContentSerializer(m);
       if (serDef != null) {
         return serializers.serializerInstance(m, serDef);
       }
     }
   }
   return null;
 }
  public static void setParemeters(Query query, Map<String, BeanProperty> props) {

    for (String key : props.keySet()) {
      BeanProperty prop = props.get(key);
      if (prop.getType().equals(String.class)) {
        query.setParameter(prop.getName(), "%" + prop.getValue() + "%");
      } else {
        query.setParameter(prop.getName(), prop.getValue());
      }
    }
  }
    Converter<?> provide(BeanProperty property, Genson genson) {
      Type type = property.getType();
      for (Iterator<? extends ContextualFactory<?>> it = contextualFactories.iterator();
          it.hasNext(); ) {
        ContextualFactory<?> factory = it.next();
        Converter<?> object = null;
        Type factoryType = lookupGenericType(ContextualFactory.class, factory.getClass());
        factoryType = expandType(factoryType, factory.getClass());
        Type factoryParameter = typeOf(0, factoryType);

        if (type instanceof Class<?> && ((Class<?>) type).isPrimitive())
          type = wrap((Class<?>) type);

        if (match(type, factoryParameter, false)
            && (object = factory.create(property, genson)) != null) {
          return object;
        }
      }
      return null;
    }
 @Override
 public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
     throws JsonMappingException {
   /* 29-Sep-2012, tatu: Actually, we need to do much more contextual
    *    checking here since we finally know for sure the property,
    *    and it may have overrides
    */
   JsonSerializer<?> ser = null;
   // First: if we have a property, may have property-annotation overrides
   if (property != null) {
     AnnotatedMember m = property.getMember();
     if (m != null) {
       Object serDef = provider.getAnnotationIntrospector().findContentSerializer(m);
       if (serDef != null) {
         ser = provider.serializerInstance(m, serDef);
       }
     }
   }
   if (ser == null) {
     ser = _serializer;
   }
   // #124: May have a content converter
   ser = findConvertingContentSerializer(provider, property, ser);
   if (ser == null) {
     ser = provider.findValueSerializer(String.class, property);
   } else if (ser instanceof ContextualSerializer) {
     ser = ((ContextualSerializer) ser).createContextual(provider, property);
   }
   // Optimization: default serializer just writes String, so we can avoid a call:
   if (isDefaultSerializer(ser)) {
     ser = null;
   }
   // note: will never have TypeSerializer, because Strings are "natural" type
   if (ser == _serializer) {
     return this;
   }
   return new IndexedStringListSerializer(ser);
 }
 public Object findInjectableValue(
     Object valueId,
     DeserializationContext ctxt,
     BeanProperty forProperty,
     Object beanInstance) {
   if (valueId instanceof String) {
     String key = (String) valueId;
     Object ob = this._values.get(key);
     if (ob != null || this._values.containsKey(key)) {
       return ob;
     }
     throw new IllegalArgumentException(
         "No injectable id with value '"
             + key
             + "' found (for property '"
             + forProperty.getName()
             + "')");
   }
   throw new IllegalArgumentException(
       "Unrecognized inject value id type ("
           + (valueId == null ? "[null]" : valueId.getClass().getName())
           + "), expecting String");
 }
  @Override
  public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
      throws JsonMappingException {
    if (property != null) {
      JsonFormat.Value ann =
          prov.getAnnotationIntrospector().findFormat((Annotated) property.getMember());
      if (ann != null) {
        JacksonJodaDateFormat format = _format;

        Boolean useTimestamp;

        // Simple case first: serialize as numeric timestamp?
        if (ann.getShape().isNumeric()) {
          useTimestamp = Boolean.TRUE;
        } else if (ann.getShape() == JsonFormat.Shape.STRING) {
          useTimestamp = Boolean.FALSE;
        } else if (ann.getShape() == JsonFormat.Shape.ARRAY) {
          // 17-Nov-2014, tatu: also, arrays typically contain non-string representation
          useTimestamp = Boolean.TRUE;
        } else {
          useTimestamp = null;
        }
        // must not call if flag defined, to rely on defaults:
        if (useTimestamp != null) {
          format = format.withUseTimestamp(useTimestamp);
        }
        // for others, safe to call, null/empty just ignored
        format = format.withFormat(ann.getPattern().trim());
        format = format.withLocale(ann.getLocale());
        format = format.withTimeZone(ann.getTimeZone());
        if (format != _format) {
          return withFormat(format);
        }
      }
    }
    return this;
  }
Example #16
0
  /**
   * Return true if this property is write only, which means we cannot get a value for it.
   *
   * @param instance the instance
   * @param propertyName the property name
   * @return true if there is a way to write but not read the property
   */
  public boolean isWriteOnly(Object instance, String propertyName) {
    if (instance == null || propertyName == null) return false;

    BeanProperty bp = getBeanProperty(instance, propertyName);
    return bp != null && bp.isWrite() && !bp.isRead();
  }
Example #17
0
  /** {@inheritDoc} */
  public Class getType(Object instance, String propertyName) {
    if (instance == null || propertyName == null) return null;

    BeanProperty bp = getBeanProperty(instance, propertyName);
    return bp == null ? null : bp.getType();
  }
Example #18
0
  /** {@inheritDoc} */
  public void setValue(Object instance, String propertyName, Object value) {
    BeanProperty bp = getBeanProperty(instance, propertyName);

    if (bp != null) {
      if (bp.isWrite()) {
        try {
          Class desiredPropClass = bp.getType();
          TypeMarshaller marshaller = TypeMarshallingContext.getTypeMarshaller();
          value = marshaller.convert(value, desiredPropClass);
          ClassUtil.validateAssignment(instance, propertyName, value);
          bp.set(instance, value);
        } catch (Exception e) {
          SerializationContext context = getSerializationContext();

          // Log ignore failed property set errors
          if (Log.isWarn() && logPropertyErrors(context)) {
            Logger log = Log.getLogger(LOG_CATEGORY);
            log.warn(
                "Failed to set property {0} on type {1}.",
                new Object[] {propertyName, getAlias(instance)}, e);
          }

          if (!ignorePropertyErrors(context)) {
            // Failed to get property '{propertyName}' on type '{className}'.
            MessageException ex = new MessageException();
            ex.setMessage(
                FAILED_PROPERTY_WRITE_ERROR, new Object[] {propertyName, getAlias(instance)});
            ex.setRootCause(e);
            throw ex;
          }
        }
      } else {
        SerializationContext context = getSerializationContext();

        if (Log.isWarn() && logPropertyErrors(context)) {
          Logger log = Log.getLogger(LOG_CATEGORY);
          log.warn(
              "Property {0} not writable on class {1}",
              new Object[] {propertyName, getAlias(instance)});
        }

        if (!ignorePropertyErrors(context)) {
          // Property '{propertyName}' not writable on class '{alias}'.
          MessageException ex = new MessageException();
          ex.setMessage(
              NON_WRITABLE_PROPERTY_ERROR, new Object[] {propertyName, getAlias(instance)});
          throw ex;
        }
      }
    } else {
      SerializationContext context = getSerializationContext();

      if (Log.isWarn() && logPropertyErrors(context)) {
        Logger log = Log.getLogger(LOG_CATEGORY);
        log.warn(
            "Ignoring set property {0} for type {1} as a setter could not be found.",
            new Object[] {propertyName, getAlias(instance)});
      }

      if (!ignorePropertyErrors(context)) {
        // Property '{propertyName}' not found on class '{alias}'.
        MessageException ex = new MessageException();
        ex.setMessage(UNKNOWN_PROPERTY_ERROR, new Object[] {propertyName, getAlias(instance)});
        throw ex;
      }
    }
  }
 @Override
 public KeyDeserializer createContextual(DeserializationContext ctxt, BeanProperty property)
     throws JsonMappingException {
   return new ContextualDeser((property == null) ? "ROOT" : property.getName());
 }
  @Override
  public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
      throws JsonMappingException {
    JsonSerializer<?> ser = null;
    JsonSerializer<?> keySer = null;
    final AnnotationIntrospector intr = provider.getAnnotationIntrospector();
    final AnnotatedMember propertyAcc = (property == null) ? null : property.getMember();

    // First: if we have a property, may have property-annotation overrides
    if ((propertyAcc != null) && (intr != null)) {
      Object serDef = intr.findKeySerializer(propertyAcc);
      if (serDef != null) {
        keySer = provider.serializerInstance(propertyAcc, serDef);
      }
      serDef = intr.findContentSerializer(propertyAcc);
      if (serDef != null) {
        ser = provider.serializerInstance(propertyAcc, serDef);
      }
    }
    if (ser == null) {
      ser = _valueSerializer;
    }
    // [databind#124]: May have a content converter
    ser = findContextualConvertingSerializer(provider, property, ser);
    if (ser == null) {
      // 30-Sep-2012, tatu: One more thing -- if explicit content type is annotated,
      //   we can consider it a static case as well.
      // 20-Aug-2013, tatu: Need to avoid trying to access serializer for java.lang.Object tho
      if (_valueTypeIsStatic && !_valueType.isJavaLangObject()) {
        ser = provider.findValueSerializer(_valueType, property);
      }
    }
    if (keySer == null) {
      keySer = _keySerializer;
    }
    if (keySer == null) {
      keySer = provider.findKeySerializer(_keyType, property);
    } else {
      keySer = provider.handleSecondaryContextualization(keySer, property);
    }
    Set<String> ignored = _ignoredEntries;
    boolean sortKeys = false;
    if ((intr != null) && (propertyAcc != null)) {
      JsonIgnoreProperties.Value ignorals = intr.findPropertyIgnorals(propertyAcc);
      if (ignorals != null) {
        Set<String> newIgnored = ignorals.findIgnoredForSerialization();
        if ((newIgnored != null) && !newIgnored.isEmpty()) {
          ignored = (ignored == null) ? new HashSet<String>() : new HashSet<String>(ignored);
          for (String str : newIgnored) {
            ignored.add(str);
          }
        }
      }
      Boolean b = intr.findSerializationSortAlphabetically(propertyAcc);
      sortKeys = (b != null) && b.booleanValue();
    }
    JsonFormat.Value format = findFormatOverrides(provider, property, Map.class);
    if (format != null) {
      Boolean B = format.getFeature(JsonFormat.Feature.WRITE_SORTED_MAP_ENTRIES);
      if (B != null) {
        sortKeys = B.booleanValue();
      }
    }
    MapSerializer mser = withResolved(property, keySer, ser, ignored, sortKeys);

    // [databind#307]: allow filtering
    if (property != null) {
      AnnotatedMember m = property.getMember();
      if (m != null) {
        Object filterId = intr.findFilterId(m);
        if (filterId != null) {
          mser = mser.withFilterId(filterId);
        }
      }
      JsonInclude.Value inclV = property.findPropertyInclusion(provider.getConfig(), null);
      if (inclV != null) {
        JsonInclude.Include incl = inclV.getContentInclusion();

        if (incl != JsonInclude.Include.USE_DEFAULTS) {
          Object valueToSuppress;
          boolean suppressNulls;
          switch (incl) {
            case NON_DEFAULT:
              valueToSuppress = BeanUtil.getDefaultValue(_valueType);
              suppressNulls = true;
              if (valueToSuppress != null) {
                if (valueToSuppress.getClass().isArray()) {
                  valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
                }
              }
              break;
            case NON_ABSENT:
              suppressNulls = true;
              valueToSuppress = _valueType.isReferenceType() ? MARKER_FOR_EMPTY : null;
              break;
            case NON_EMPTY:
              suppressNulls = true;
              valueToSuppress = MARKER_FOR_EMPTY;
              break;
            case CUSTOM:
              valueToSuppress = provider.includeFilterInstance(null, inclV.getContentFilter());
              if (valueToSuppress == null) { // is this legal?
                suppressNulls = true;
              } else {
                suppressNulls = provider.includeFilterSuppressNulls(valueToSuppress);
              }
              break;
            case NON_NULL:
              valueToSuppress = null;
              suppressNulls = true;
              break;
            case ALWAYS: // default
            default:
              valueToSuppress = null;
              // 30-Sep-2016, tatu: Should not need to check global flags here,
              //   if inclusion forced to be ALWAYS
              suppressNulls = false;
              break;
          }
          mser = mser.withContentInclusion(valueToSuppress, suppressNulls);
        }
      }
    }
    return mser;
  }