Search in sources :

Example 1 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project druid by druid-io.

the class JsonConfigurator method configurate.

public <T> T configurate(Properties props, String propertyPrefix, Class<T> clazz) throws ProvisionException {
    verifyClazzIsConfigurable(jsonMapper, clazz);
    // Make it end with a period so we only include properties with sub-object thingies.
    final String propertyBase = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + ".";
    Map<String, Object> jsonMap = Maps.newHashMap();
    for (String prop : props.stringPropertyNames()) {
        if (prop.startsWith(propertyBase)) {
            final String propValue = props.getProperty(prop);
            Object value;
            try {
                // If it's a String Jackson wants it to be quoted, so check if it's not an object or array and quote.
                String modifiedPropValue = propValue;
                if (!(modifiedPropValue.startsWith("[") || modifiedPropValue.startsWith("{"))) {
                    modifiedPropValue = jsonMapper.writeValueAsString(propValue);
                }
                value = jsonMapper.readValue(modifiedPropValue, Object.class);
            } catch (IOException e) {
                log.info(e, "Unable to parse [%s]=[%s] as a json object, using as is.", prop, propValue);
                value = propValue;
            }
            jsonMap.put(prop.substring(propertyBase.length()), value);
        }
    }
    final T config;
    try {
        config = jsonMapper.convertValue(jsonMap, clazz);
    } catch (IllegalArgumentException e) {
        throw new ProvisionException(String.format("Problem parsing object at prefix[%s]: %s.", propertyPrefix, e.getMessage()), e);
    }
    final Set<ConstraintViolation<T>> violations = validator.validate(config);
    if (!violations.isEmpty()) {
        List<String> messages = Lists.newArrayList();
        for (ConstraintViolation<T> violation : violations) {
            String path = "";
            try {
                Class<?> beanClazz = violation.getRootBeanClass();
                final Iterator<Path.Node> iter = violation.getPropertyPath().iterator();
                while (iter.hasNext()) {
                    Path.Node next = iter.next();
                    if (next.getKind() == ElementKind.PROPERTY) {
                        final String fieldName = next.getName();
                        final Field theField = beanClazz.getDeclaredField(fieldName);
                        if (theField.getAnnotation(JacksonInject.class) != null) {
                            path = String.format(" -- Injected field[%s] not bound!?", fieldName);
                            break;
                        }
                        JsonProperty annotation = theField.getAnnotation(JsonProperty.class);
                        final boolean noAnnotationValue = annotation == null || Strings.isNullOrEmpty(annotation.value());
                        final String pathPart = noAnnotationValue ? fieldName : annotation.value();
                        if (path.isEmpty()) {
                            path += pathPart;
                        } else {
                            path += "." + pathPart;
                        }
                    }
                }
            } catch (NoSuchFieldException e) {
                throw Throwables.propagate(e);
            }
            messages.add(String.format("%s - %s", path, violation.getMessage()));
        }
        throw new ProvisionException(Iterables.transform(messages, new Function<String, Message>() {

            @Override
            public Message apply(String input) {
                return new Message(String.format("%s%s", propertyBase, input));
            }
        }));
    }
    log.info("Loaded class[%s] from props[%s] as [%s]", clazz, propertyBase, config);
    return config;
}
Also used : Path(javax.validation.Path) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Message(com.google.inject.spi.Message) IOException(java.io.IOException) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField) Field(java.lang.reflect.Field) Function(com.google.common.base.Function) ProvisionException(com.google.inject.ProvisionException) JacksonInject(com.fasterxml.jackson.annotation.JacksonInject) ConstraintViolation(javax.validation.ConstraintViolation)

Example 2 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project pinot by linkedin.

the class SwaggerResource method schemaForType.

private JSONObject schemaForType(Class<?> type) {
    try {
        JSONObject schema = new JSONObject();
        schema.put("type", "object");
        schema.put("title", type.getSimpleName());
        Example example = type.getAnnotation(Example.class);
        if (example != null) {
            schema.put("example", new JSONObject(example.value()));
        }
        for (Constructor<?> constructor : type.getConstructors()) {
            if (constructor.isAnnotationPresent(JsonCreator.class)) {
                JSONObject properties = new JSONObject();
                JSONArray required = new JSONArray();
                Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();
                Class<?>[] parameterTypes = constructor.getParameterTypes();
                for (int i = 0; i < parameterTypes.length; i++) {
                    Class<?> parameterType = parameterTypes[i];
                    Annotation[] annotations = parameterAnnotations[i];
                    if (annotations.length != 0) {
                        for (Annotation annotation : annotations) {
                            if (annotation instanceof JsonProperty) {
                                JsonProperty jsonPropertyAnnotation = (JsonProperty) annotation;
                                JSONObject parameter = new JSONObject();
                                properties.put(jsonPropertyAnnotation.value(), parameter);
                                if (parameterType.equals(String.class)) {
                                    parameter.put("type", "string");
                                } else if (parameterType.equals(Boolean.class) || parameterType.equals(Boolean.TYPE)) {
                                    parameter.put("type", "boolean");
                                } else if (parameterType.equals(Integer.class) || parameterType.equals(Integer.TYPE)) {
                                    parameter.put("type", "integer");
                                } else if (parameterType.equals(Long.class) || parameterType.equals(Long.TYPE)) {
                                    // Long maps to integer type in http://swagger.io/specification/#dataTypeFormat
                                    parameter.put("type", "integer");
                                } else if (parameterType.equals(Float.class) || parameterType.equals(Float.TYPE)) {
                                    parameter.put("type", "boolean");
                                } else if (parameterType.equals(Double.class) || parameterType.equals(Double.TYPE)) {
                                    parameter.put("type", "double");
                                } else if (parameterType.equals(Byte.class) || parameterType.equals(Byte.TYPE)) {
                                    // Byte maps to string type in http://swagger.io/specification/#dataTypeFormat
                                    parameter.put("type", "string");
                                } else {
                                    parameter.put("type", "string");
                                }
                                if (jsonPropertyAnnotation.required()) {
                                    required.put(jsonPropertyAnnotation.value());
                                }
                            }
                        }
                    }
                }
                if (required.length() != 0) {
                    schema.put("required", required);
                }
                schema.put("properties", properties);
                break;
            }
        }
        return schema;
    } catch (Exception e) {
        return new JSONObject();
    }
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) JSONArray(org.json.JSONArray) Annotation(java.lang.annotation.Annotation) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject)

Example 3 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project dhis2-core by dhis2.

the class Jackson2PropertyIntrospectorService method scanClass.

@Override
protected Map<String, Property> scanClass(Class<?> clazz) {
    Map<String, Property> propertyMap = Maps.newHashMap();
    Map<String, Property> hibernatePropertyMap = getPropertiesFromHibernate(clazz);
    List<String> classFieldNames = ReflectionUtils.getAllFieldNames(clazz);
    // TODO this is quite nasty, should find a better way of exposing properties at class-level
    if (AnnotationUtils.isAnnotationPresent(clazz, JacksonXmlRootElement.class)) {
        Property property = new Property();
        JacksonXmlRootElement jacksonXmlRootElement = AnnotationUtils.getAnnotation(clazz, JacksonXmlRootElement.class);
        if (!StringUtils.isEmpty(jacksonXmlRootElement.localName())) {
            property.setName(jacksonXmlRootElement.localName());
        }
        if (!StringUtils.isEmpty(jacksonXmlRootElement.namespace())) {
            property.setNamespace(jacksonXmlRootElement.namespace());
        }
        propertyMap.put("__self__", property);
    }
    List<Property> properties = collectProperties(clazz);
    for (Property property : properties) {
        Method getterMethod = property.getGetterMethod();
        JsonProperty jsonProperty = AnnotationUtils.getAnnotation(getterMethod, JsonProperty.class);
        String fieldName = getFieldName(getterMethod);
        property.setName(!StringUtils.isEmpty(jsonProperty.value()) ? jsonProperty.value() : fieldName);
        if (property.getGetterMethod() != null) {
            property.setReadable(true);
        }
        if (property.getSetterMethod() != null) {
            property.setWritable(true);
        }
        if (classFieldNames.contains(fieldName)) {
            property.setFieldName(fieldName);
        }
        if (hibernatePropertyMap.containsKey(fieldName)) {
            Property hibernateProperty = hibernatePropertyMap.get(fieldName);
            property.setPersisted(true);
            property.setWritable(true);
            property.setUnique(hibernateProperty.isUnique());
            property.setRequired(hibernateProperty.isRequired());
            property.setLength(hibernateProperty.getLength());
            property.setMax(hibernateProperty.getMax());
            property.setMin(hibernateProperty.getMin());
            property.setCollection(hibernateProperty.isCollection());
            property.setCascade(hibernateProperty.getCascade());
            property.setOwner(hibernateProperty.isOwner());
            property.setManyToMany(hibernateProperty.isManyToMany());
            property.setOneToOne(hibernateProperty.isOneToOne());
            property.setManyToOne(hibernateProperty.isManyToOne());
            property.setOwningRole(hibernateProperty.getOwningRole());
            property.setInverseRole(hibernateProperty.getInverseRole());
            property.setGetterMethod(hibernateProperty.getGetterMethod());
            property.setSetterMethod(hibernateProperty.getSetterMethod());
        }
        if (AnnotationUtils.isAnnotationPresent(property.getGetterMethod(), Description.class)) {
            Description description = AnnotationUtils.getAnnotation(property.getGetterMethod(), Description.class);
            property.setDescription(description.value());
        }
        if (AnnotationUtils.isAnnotationPresent(property.getGetterMethod(), JacksonXmlProperty.class)) {
            JacksonXmlProperty jacksonXmlProperty = AnnotationUtils.getAnnotation(getterMethod, JacksonXmlProperty.class);
            if (StringUtils.isEmpty(jacksonXmlProperty.localName())) {
                property.setName(property.getName());
            } else {
                property.setName(jacksonXmlProperty.localName());
            }
            if (!StringUtils.isEmpty(jacksonXmlProperty.namespace())) {
                property.setNamespace(jacksonXmlProperty.namespace());
            }
            property.setAttribute(jacksonXmlProperty.isAttribute());
        }
        Class<?> returnType = property.getGetterMethod().getReturnType();
        property.setKlass(Primitives.wrap(returnType));
        if (Collection.class.isAssignableFrom(returnType)) {
            property.setCollection(true);
            property.setCollectionName(property.getName());
            property.setOrdered(List.class.isAssignableFrom(returnType));
            Type type = property.getGetterMethod().getGenericReturnType();
            if (ParameterizedType.class.isInstance(type)) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                Class<?> klass = (Class<?>) parameterizedType.getActualTypeArguments()[0];
                property.setItemKlass(Primitives.wrap(klass));
                if (collectProperties(klass).isEmpty()) {
                    property.setSimple(true);
                }
                property.setIdentifiableObject(IdentifiableObject.class.isAssignableFrom(klass));
                property.setNameableObject(NameableObject.class.isAssignableFrom(klass));
                property.setEmbeddedObject(EmbeddedObject.class.isAssignableFrom(klass));
            }
        } else {
            if (collectProperties(returnType).isEmpty()) {
                property.setSimple(true);
            }
        }
        if (property.isCollection()) {
            if (AnnotationUtils.isAnnotationPresent(property.getGetterMethod(), JacksonXmlElementWrapper.class)) {
                JacksonXmlElementWrapper jacksonXmlElementWrapper = AnnotationUtils.getAnnotation(getterMethod, JacksonXmlElementWrapper.class);
                property.setCollectionWrapping(jacksonXmlElementWrapper.useWrapping());
                // TODO what if element-wrapper have different namespace?
                if (!StringUtils.isEmpty(jacksonXmlElementWrapper.localName())) {
                    property.setCollectionName(jacksonXmlElementWrapper.localName());
                }
            }
            propertyMap.put(property.getCollectionName(), property);
        } else {
            propertyMap.put(property.getName(), property);
        }
        if (Enum.class.isAssignableFrom(property.getKlass())) {
            Object[] enumConstants = property.getKlass().getEnumConstants();
            List<String> enumValues = new ArrayList<>();
            for (Object value : enumConstants) {
                enumValues.add(value.toString());
            }
            property.setConstants(enumValues);
        }
        SchemaUtils.updatePropertyTypes(property);
    }
    return propertyMap;
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Description(org.hisp.dhis.common.annotation.Description) JacksonXmlRootElement(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement) ArrayList(java.util.ArrayList) EmbeddedObject(org.hisp.dhis.common.EmbeddedObject) Method(java.lang.reflect.Method) JacksonXmlElementWrapper(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper) JacksonXmlProperty(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) NameableObject(org.hisp.dhis.common.NameableObject) ArrayList(java.util.ArrayList) List(java.util.List) EmbeddedObject(org.hisp.dhis.common.EmbeddedObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) NameableObject(org.hisp.dhis.common.NameableObject) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) JacksonXmlProperty(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty)

Example 4 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project hono by eclipse.

the class TenantObject method setAdapterConfigurations.

/**
 * Sets the configuration information for this tenant's
 * configured adapters.
 *
 * @param configurations A list of configuration properties, one set of properties
 *                              for each configured adapter. The list's content will be
 *                              copied into a new list in order to prevent modification
 *                              of the list after this method has been invoked.
 * @throws NullPointerException if the list is {@code null}.
 * @return This tenant for command chaining.
 */
@JsonProperty(TenantConstants.FIELD_ADAPTERS)
public TenantObject setAdapterConfigurations(final List<Map<String, Object>> configurations) {
    if (configurations == null) {
        this.adapterConfigurations = null;
    } else {
        configurations.stream().forEach(map -> {
            final JsonObject config = new JsonObject(map);
            addAdapterConfiguration(config);
        });
    }
    return this;
}
Also used : JsonObject(io.vertx.core.json.JsonObject) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty)

Example 5 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project knime-core by knime.

the class SubnodeContainerExecutionResult method setWorkflowExecutionResult.

/**
 * Sets inner execution result.
 * @param workflowExecutionResult To be set, must have correct baseID.
 * @throws IllegalArgumentException If the id prefix is invalid or argument is null
 */
@JsonProperty("workflowExecResult")
public void setWorkflowExecutionResult(final WorkflowExecutionResult workflowExecutionResult) {
    m_workflowExecutionResult = CheckUtils.checkArgumentNotNull(workflowExecutionResult, "Arg must not be null");
    CheckUtils.checkArgument(new NodeID(m_baseID, 0).equals(m_workflowExecutionResult.getBaseID()), "Unexpected ID of inner wfm result, expected %s but got %s", new NodeID(m_baseID, 0), m_workflowExecutionResult.getBaseID());
    m_workflowExecutionResult = workflowExecutionResult;
}
Also used : NodeID(org.knime.core.node.workflow.NodeID) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty)

Aggregations

JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)37 Field (java.lang.reflect.Field)9 ArrayList (java.util.ArrayList)9 Annotation (java.lang.annotation.Annotation)8 NamedType (com.fasterxml.jackson.databind.jsontype.NamedType)6 Method (java.lang.reflect.Method)6 Type (java.lang.reflect.Type)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)5 HashMap (java.util.HashMap)5 JsonCreator (com.fasterxml.jackson.annotation.JsonCreator)4 JavaType (com.fasterxml.jackson.databind.JavaType)4 AnnotatedClass (com.fasterxml.jackson.databind.introspect.AnnotatedClass)4 JsonIdentityInfo (com.fasterxml.jackson.annotation.JsonIdentityInfo)3 JsonIdentityReference (com.fasterxml.jackson.annotation.JsonIdentityReference)3 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)3 PropertyMetadata (com.fasterxml.jackson.databind.PropertyMetadata)3 AnnotatedMember (com.fasterxml.jackson.databind.introspect.AnnotatedMember)3 BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)3