@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleGsonProducesGsonAnnotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException { Class generatedType = schemaRule.generateAndCompile("/json/examples/torrent.json", "com.example", config("annotationStyle", "gson", "propertyWordDelimiters", "_", "sourceType", "json")) .loadClass("com.example.Torrent"); assertThat(schemaRule.getGenerateDir(), not(containsText("org.codehaus.jackson"))); assertThat(schemaRule.getGenerateDir(), not(containsText("com.fasterxml.jackson"))); assertThat(schemaRule.getGenerateDir(), containsText("com.google.gson")); assertThat(schemaRule.getGenerateDir(), containsText("@SerializedName")); Method getter = generatedType.getMethod("getBuild"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(nullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue())); }
@Test @SuppressWarnings({"rawtypes", "unchecked"}) public void annotationStyleMoshi1ProducesMoshi1Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException { Class generatedType = schemaRule.generateAndCompile("/json/examples/torrent.json", "com.example", config("annotationStyle", "moshi1", "propertyWordDelimiters", "_", "sourceType", "json")) .loadClass("com.example.Torrent"); assertThat(schemaRule.getGenerateDir(), not(containsText("org.codehaus.jackson"))); assertThat(schemaRule.getGenerateDir(), not(containsText("com.fasterxml.jackson"))); assertThat(schemaRule.getGenerateDir(), not(containsText("com.google.gson"))); assertThat(schemaRule.getGenerateDir(), not(containsText("@SerializedName"))); assertThat(schemaRule.getGenerateDir(), containsText("com.squareup.moshi")); assertThat(schemaRule.getGenerateDir(), containsText("@Json")); Method getter = generatedType.getMethod("getBuild"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(nullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleJackson2ProducesJackson2Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { Class generatedType = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson2")) .loadClass("com.example.PrimitiveProperties"); assertThat(schemaRule.getGenerateDir(), not(containsText("org.codehaus.jackson"))); assertThat(schemaRule.getGenerateDir(), containsText("com.fasterxml.jackson")); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleJackson1ProducesJackson1Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { Class generatedType = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson1")) .loadClass("com.example.PrimitiveProperties"); assertThat(schemaRule.getGenerateDir(), not(containsText("com.fasterxml.jackson"))); assertThat(schemaRule.getGenerateDir(), containsText("org.codehaus.jackson")); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(org.codehaus.jackson.annotate.JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(org.codehaus.jackson.map.annotate.JsonSerialize.class), is(notNullValue())); assertThat(getter.getAnnotation(org.codehaus.jackson.annotate.JsonProperty.class), is(notNullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void customAnnotatorCanBeAppliedAlongsideCoreAnnotator() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("customAnnotator", DeprecatingAnnotator.class.getName())); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue())); }
public ResourceInformation build(Class<?> resourceClass, boolean allowNonResourceBaseClass) { List<ResourceField> resourceFields = getResourceFields(resourceClass); String resourceType = getResourceType(resourceClass, allowNonResourceBaseClass); Optional<JsonPropertyOrder> propertyOrder = ClassUtils.getAnnotation(resourceClass, JsonPropertyOrder.class); if (propertyOrder.isPresent()) { JsonPropertyOrder propertyOrderAnnotation = propertyOrder.get(); Collections.sort(resourceFields, new FieldOrderedComparator(propertyOrderAnnotation.value(), propertyOrderAnnotation.alphabetic())); } DefaultResourceInstanceBuilder<?> instanceBuilder = new DefaultResourceInstanceBuilder(resourceClass); Class<?> superclass = resourceClass.getSuperclass(); String superResourceType = superclass != Object.class && context.accept(superclass) ? context.getResourceType(superclass) : null; ResourceInformation information = new ResourceInformation(context.getTypeParser(), resourceClass, resourceType, superResourceType, instanceBuilder, resourceFields); if (!allowNonResourceBaseClass && information.getIdField() == null) { throw new ResourceIdNotFoundException(resourceClass.getCanonicalName()); } return information; }
protected List<Element> orderedFields() { TypeElement typeElement = (TypeElement) typeUtils.asElement(beanType); final List<Element> orderedProperties = new ArrayList<>(); final List<Element> fields = typeElement.getEnclosedElements().stream().filter(e -> ElementKind.FIELD .equals(e.getKind()) && !e.getModifiers() .contains(Modifier.STATIC)).collect(Collectors.toList()); Optional.ofNullable(typeUtils.asElement(beanType).getAnnotation(JsonPropertyOrder.class)) .ifPresent(jsonPropertyOrder -> { final List<String> orderedFieldsNames = Arrays.asList(jsonPropertyOrder.value()); orderedProperties.addAll(fields.stream() .filter(f -> orderedFieldsNames.contains(f.getSimpleName().toString())) .collect(Collectors.toList())); fields.removeAll(orderedProperties); if (jsonPropertyOrder.alphabetic()) { fields.sort(Comparator.comparing(f -> f.getSimpleName().toString())); } fields.addAll(0, orderedProperties); }); return fields; }
@SuppressWarnings({"unchecked", "rawtypes"}) public ResourceInformation build(Class<?> resourceClass) { List<AnnotatedResourceField> resourceFields = getResourceFields(resourceClass); String resourceType = getResourceType(resourceClass); Optional<JsonPropertyOrder> propertyOrder = ClassUtils.getAnnotation(resourceClass, JsonPropertyOrder.class); if (propertyOrder.isPresent()) { JsonPropertyOrder propertyOrderAnnotation = propertyOrder.get(); Collections.sort(resourceFields, new FieldOrderedComparator(propertyOrderAnnotation.value(), propertyOrderAnnotation.alphabetic())); } DefaultResourceInstanceBuilder<?> instanceBuilder = new DefaultResourceInstanceBuilder(resourceClass); Class<?> superclass = resourceClass.getSuperclass(); String superResourceType = superclass != Object.class && context.accept(superclass) ? context.getResourceType(superclass) : null; return new ResourceInformation(context.getTypeParser(), resourceClass, resourceType, superResourceType, instanceBuilder, (List) resourceFields); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleJackson2ProducesJackson2Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { File generatedOutputDirectory = generate("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson2")); assertThat(generatedOutputDirectory, not(containsText("org.codehaus.jackson"))); assertThat(generatedOutputDirectory, containsText("com.fasterxml.jackson")); ClassLoader resultsClassLoader = compile(generatedOutputDirectory); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleJackson1ProducesJackson1Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { File generatedOutputDirectory = generate("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson1")); assertThat(generatedOutputDirectory, not(containsText("com.fasterxml.jackson"))); assertThat(generatedOutputDirectory, containsText("org.codehaus.jackson")); ClassLoader resultsClassLoader = compile(generatedOutputDirectory); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(org.codehaus.jackson.annotate.JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(org.codehaus.jackson.map.annotate.JsonSerialize.class), is(notNullValue())); assertThat(getter.getAnnotation(org.codehaus.jackson.annotate.JsonProperty.class), is(notNullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void customAnnotatorCanBeAppliedAlongsideCoreAnnotator() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("customAnnotator", DeprecatingAnnotator.class.getName())); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue())); }
@Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { JAnnotationArrayMember annotationValue = clazz.annotate(JsonPropertyOrder.class).paramArray("value"); for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) { annotationValue.param(properties.next()); } }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void defaultAnnotationStyeIsJackson2() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example"); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleJacksonProducesJackson2Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson")); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); }
@Test public void onGetAnnotationShouldReturnParentAnnotation() { // WHEN Optional<JsonPropertyOrder> result = ClassUtils.getAnnotation(ChildClass.class, JsonPropertyOrder.class); // THEN assertThat(result.get()).isInstanceOf(JsonPropertyOrder.class); }
@Override public void processPropertyOrderRule(TypeSpec.Builder typeSpec, TypeModel typeModel) { List<String> fieldOrder = typeModel.getFieldOrder(); AnnotationSpec.Builder propertyOrderBuilder = AnnotationSpec.builder(JsonPropertyOrder.class); for (String field : fieldOrder) { propertyOrderBuilder.addMember("value", "$S", field); } typeSpec.addAnnotation(propertyOrderBuilder.build()); }
private void toCSV(Collection<?> data, String outputFileName) throws IOException{ CsvMapper mapper = new CsvMapper(); String[] header = BinaryLabeledContributionInterchange.class.getAnnotation(JsonPropertyOrder.class).value(); try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFileName)))) { out.write(mapper.writeValueAsString(header)); for(Object a:data){ out.write(mapper.writerWithSchemaFor(a.getClass()).writeValueAsString(a)); } } }
@Override public void serializeContents(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { JsonPropertyOrder order = value.getClass().getAnnotation(JsonPropertyOrder.class); String[] propOrder = (order == null) ? null : order.value(); if (propOrder == null) { throw new IllegalStateException("Bean must declare JsonPropertyOrder!"); } if (propOrder.length == 0) { return; } int i = 0; try { do { Field field = value.getClass().getDeclaredField(propOrder[i]); ReflectionUtils.makeAccessible(field); Object elem = field.get(value); if (elem == null) { provider.defaultSerializeNull(jgen); } else { Class<?> cc = elem.getClass(); JsonSerializer<Object> serializer = provider.findValueSerializer(cc, null); serializer.serialize(elem, jgen, provider); } ++i; } while (i < propOrder.length); } catch (Exception e) { // [JACKSON-55] Need to add reference information wrapAndThrow(provider, e, value, i); } }
private List<String> annotationFields(Class<T> instanceClazz) { if (instanceClazz.isAnnotationPresent(JsonPropertyOrder.class)) { return Arrays.asList(instanceClazz.getAnnotation(JsonPropertyOrder.class).value()); } throw new CatnapException("Missing CatnapOrder or JsonPropertyOrder annotation"); }
private boolean alphabetizeOrphans(Class<T> instanceClazz) { if (instanceClazz.isAnnotationPresent(JsonPropertyOrder.class)) { return instanceClazz.getAnnotation(JsonPropertyOrder.class).alphabetic(); } throw new CatnapException("Missing CatnapOrder or JsonPropertyOrder annotation"); }
private <T> SortMethod sortMethod(Class<T> instanceClazz) { if (instanceClazz != null) { //Jackson Support if (instanceClazz.isAnnotationPresent(JsonPropertyOrder.class)) { String[] value = instanceClazz.getAnnotation(JsonPropertyOrder.class).value(); return (value != null && value.length > 0) ? SortMethod.ANNOTATION : SortMethod.ALPHABETICAL; } } return SortMethod.FIELD_DECLARATION; }
public String[] findSerializationPropertyOrder(AnnotatedClass paramAnnotatedClass) { JsonPropertyOrder localJsonPropertyOrder = (JsonPropertyOrder)paramAnnotatedClass.getAnnotation(JsonPropertyOrder.class); if (localJsonPropertyOrder == null) return null; return localJsonPropertyOrder.value(); }
public Boolean findSerializationSortAlphabetically(AnnotatedClass paramAnnotatedClass) { JsonPropertyOrder localJsonPropertyOrder = (JsonPropertyOrder)paramAnnotatedClass.getAnnotation(JsonPropertyOrder.class); if (localJsonPropertyOrder == null) return null; return Boolean.valueOf(localJsonPropertyOrder.alphabetic()); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void defaultAnnotationStyeIsJackson2() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json", "com.example"); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleJacksonProducesJackson2Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson")); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleNoneProducesNoAnnotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "none")); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue())); assertThat(generatedType.getAnnotation(JsonSerialize.class), is(nullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue())); }
@JsonProperty("Name") @JsonPropertyOrder() public String getName() { return this.name; }
/** * <p>processBean</p> * * @param logger a {@link com.google.gwt.core.ext.TreeLogger} object. * @param typeOracle a {@link com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle} object. * @param configuration a {@link com.github.nmorel.gwtjackson.rebind.RebindConfiguration} object. * @param beanType a {@link com.google.gwt.core.ext.typeinfo.JClassType} object. * @return a {@link com.github.nmorel.gwtjackson.rebind.bean.BeanInfo} object. * @throws com.google.gwt.core.ext.UnableToCompleteException if any. */ public static BeanInfo processBean( TreeLogger logger, JacksonTypeOracle typeOracle, RebindConfiguration configuration, JClassType beanType ) throws UnableToCompleteException { BeanInfoBuilder builder = new BeanInfoBuilder(); builder.setType( beanType ); if ( null != beanType.isGenericType() ) { builder.setParameterizedTypes( Arrays.<JClassType>asList( beanType.isGenericType().getTypeParameters() ) ); } determineInstanceCreator( configuration, typeOracle, logger, beanType, builder ); Optional<JsonAutoDetect> jsonAutoDetect = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, beanType, JsonAutoDetect .class ); if ( jsonAutoDetect.isPresent() ) { builder.setCreatorVisibility( jsonAutoDetect.get().creatorVisibility() ); builder.setFieldVisibility( jsonAutoDetect.get().fieldVisibility() ); builder.setGetterVisibility( jsonAutoDetect.get().getterVisibility() ); builder.setIsGetterVisibility( jsonAutoDetect.get().isGetterVisibility() ); builder.setSetterVisibility( jsonAutoDetect.get().setterVisibility() ); } Optional<JsonIgnoreProperties> jsonIgnoreProperties = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, beanType, JsonIgnoreProperties.class ); if ( jsonIgnoreProperties.isPresent() ) { builder.setIgnoredFields( new LinkedHashSet<String>( Arrays.asList( jsonIgnoreProperties.get().value() ) ) ); builder.setIgnoreUnknown( jsonIgnoreProperties.get().ignoreUnknown() ); } Optional<JsonPropertyOrder> jsonPropertyOrder = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, beanType, JsonPropertyOrder.class ); builder.setPropertyOrderAlphabetic( jsonPropertyOrder.isPresent() && jsonPropertyOrder.get().alphabetic() ); if ( jsonPropertyOrder.isPresent() && jsonPropertyOrder.get().value().length > 0 ) { builder.setPropertyOrderList( Arrays.asList( jsonPropertyOrder.get().value() ) ); } else if ( !builder.getCreatorParameters().isEmpty() ) { List<String> propertyOrderList = new ArrayList<String>( builder.getCreatorParameters().keySet() ); builder.setPropertyOrderList( propertyOrderList ); if ( builder.isPropertyOrderAlphabetic() ) { Collections.sort( propertyOrderList ); } } Optional<JsonInclude> jsonInclude = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, beanType, JsonInclude.class ); if ( jsonInclude.isPresent() ) { builder.setInclude( Optional.of( jsonInclude.get().value() ) ); } builder.setIdentityInfo( processIdentity( logger, typeOracle, configuration, beanType ) ); builder.setTypeInfo( processType( logger, typeOracle, configuration, beanType ) ); return builder.build(); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void annotationStyleNoneProducesNoAnnotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "none")); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue())); assertThat(generatedType.getAnnotation(JsonSerialize.class), is(nullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue())); }