target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void nameWithDot() { assertEquals("FunImpl", Names.typeName("lib.Fun", "Impl")); }
public static String typeName(String... name) { if (name.length == 1 && isBlank(name[0])) { return "Root"; } List<String> values = new ArrayList<>(); int i = 0; for (String s : name) { String value = buildPart(i, s, NameFixer.CAMEL_UPPER); values.add(value); i++; } return Joiner.on("").join(values); }
Names { public static String typeName(String... name) { if (name.length == 1 && isBlank(name[0])) { return "Root"; } List<String> values = new ArrayList<>(); int i = 0; for (String s : name) { String value = buildPart(i, s, NameFixer.CAMEL_UPPER); values.add(value); i++; } return Joiner.on("").join(values); } }
Names { public static String typeName(String... name) { if (name.length == 1 && isBlank(name[0])) { return "Root"; } List<String> values = new ArrayList<>(); int i = 0; for (String s : name) { String value = buildPart(i, s, NameFixer.CAMEL_UPPER); values.add(value); i++; } return Joiner.on("").join(values); } private Names(); }
Names { public static String typeName(String... name) { if (name.length == 1 && isBlank(name[0])) { return "Root"; } List<String> values = new ArrayList<>(); int i = 0; for (String s : name) { String value = buildPart(i, s, NameFixer.CAMEL_UPPER); values.add(value); i++; } return Joiner.on("").join(values); } private Names(); static String typeName(String... name); static String methodName(String... name); static String variableName(String... name); static String constantName(String value); static String enumName(String value); static String javaTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); }
Names { public static String typeName(String... name) { if (name.length == 1 && isBlank(name[0])) { return "Root"; } List<String> values = new ArrayList<>(); int i = 0; for (String s : name) { String value = buildPart(i, s, NameFixer.CAMEL_UPPER); values.add(value); i++; } return Joiner.on("").join(values); } private Names(); static String typeName(String... name); static String methodName(String... name); static String variableName(String... name); static String constantName(String value); static String enumName(String value); static String javaTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); }
@Test public void scalarType() throws Exception { PojoToRamlImpl pojoToRaml = new PojoToRamlImpl(FieldClassParser.factory(), AdjusterFactory.NULL_FACTORY); Result types = pojoToRaml.classToRaml(String.class); Api api = createApi(types); List<TypeDeclaration> buildTypes = api.types(); assertEquals(0, buildTypes.size()); Emitter emitter = new Emitter(); emitter.emit(api); }
@Override public Result classToRaml(final Class<?> clazz) { RamlType type = RamlTypeFactory.forType(clazz, classParserFactory.createParser(clazz), adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return new Result(null, Collections.<String, TypeDeclarationBuilder>emptyMap()); } Map<String, TypeDeclarationBuilder> dependentTypes = new HashMap<>(); TypeDeclarationBuilder builder = handleSingleType(clazz, dependentTypes); dependentTypes.remove(builder.id()); return new Result(builder, dependentTypes); }
PojoToRamlImpl implements PojoToRaml { @Override public Result classToRaml(final Class<?> clazz) { RamlType type = RamlTypeFactory.forType(clazz, classParserFactory.createParser(clazz), adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return new Result(null, Collections.<String, TypeDeclarationBuilder>emptyMap()); } Map<String, TypeDeclarationBuilder> dependentTypes = new HashMap<>(); TypeDeclarationBuilder builder = handleSingleType(clazz, dependentTypes); dependentTypes.remove(builder.id()); return new Result(builder, dependentTypes); } }
PojoToRamlImpl implements PojoToRaml { @Override public Result classToRaml(final Class<?> clazz) { RamlType type = RamlTypeFactory.forType(clazz, classParserFactory.createParser(clazz), adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return new Result(null, Collections.<String, TypeDeclarationBuilder>emptyMap()); } Map<String, TypeDeclarationBuilder> dependentTypes = new HashMap<>(); TypeDeclarationBuilder builder = handleSingleType(clazz, dependentTypes); dependentTypes.remove(builder.id()); return new Result(builder, dependentTypes); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); }
PojoToRamlImpl implements PojoToRaml { @Override public Result classToRaml(final Class<?> clazz) { RamlType type = RamlTypeFactory.forType(clazz, classParserFactory.createParser(clazz), adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return new Result(null, Collections.<String, TypeDeclarationBuilder>emptyMap()); } Map<String, TypeDeclarationBuilder> dependentTypes = new HashMap<>(); TypeDeclarationBuilder builder = handleSingleType(clazz, dependentTypes); dependentTypes.remove(builder.id()); return new Result(builder, dependentTypes); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); @Override Result classToRaml(final Class<?> clazz); @Override TypeBuilder name(Class<?> clazz); @Override TypeBuilder name(Type type); }
PojoToRamlImpl implements PojoToRaml { @Override public Result classToRaml(final Class<?> clazz) { RamlType type = RamlTypeFactory.forType(clazz, classParserFactory.createParser(clazz), adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return new Result(null, Collections.<String, TypeDeclarationBuilder>emptyMap()); } Map<String, TypeDeclarationBuilder> dependentTypes = new HashMap<>(); TypeDeclarationBuilder builder = handleSingleType(clazz, dependentTypes); dependentTypes.remove(builder.id()); return new Result(builder, dependentTypes); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); @Override Result classToRaml(final Class<?> clazz); @Override TypeBuilder name(Class<?> clazz); @Override TypeBuilder name(Type type); }
@Test public void className() { RenamePlugin plugin = new RenamePlugin(Arrays.asList("One", "OneImplementation")); ClassName cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.INTERFACE); assertEquals("fun.com.One", cn.toString()); cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.IMPLEMENTATION); assertEquals("fun.com.OneImplementation", cn.toString()); }
@Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } RenamePlugin(List<String> arguments); }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } RenamePlugin(List<String> arguments); @Override ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } RenamePlugin(List<String> arguments); @Override ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); }
@Test public void classNameWithDefaultImpl() { RenamePlugin plugin = new RenamePlugin(Arrays.asList("One")); ClassName cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.INTERFACE); assertEquals("fun.com.One", cn.toString()); cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.IMPLEMENTATION); assertEquals("fun.com.OneImpl", cn.toString()); }
@Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } RenamePlugin(List<String> arguments); }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } RenamePlugin(List<String> arguments); @Override ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); }
RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } RenamePlugin(List<String> arguments); @Override ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); }
@Test public void boxOnNotRequired() { when(integerDeclaration.required()).thenReturn(false); BoxWhenNotRequired boxWhenNotRequired = new BoxWhenNotRequired(null); TypeName tn = boxWhenNotRequired.typeName(null, integerDeclaration, TypeName.INT); assertEquals(TypeName.INT.box(), tn); }
@Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } BoxWhenNotRequired(List<String> arguments); }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } BoxWhenNotRequired(List<String> arguments); @Override TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion); }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } BoxWhenNotRequired(List<String> arguments); @Override TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion); }
@Test public void noBoxOnRequired() { when(integerDeclaration.required()).thenReturn(true); BoxWhenNotRequired boxWhenNotRequired = new BoxWhenNotRequired(null); TypeName tn = boxWhenNotRequired.typeName(null, integerDeclaration, TypeName.INT); assertEquals(TypeName.INT, tn); }
@Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } BoxWhenNotRequired(List<String> arguments); }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } BoxWhenNotRequired(List<String> arguments); @Override TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion); }
BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } BoxWhenNotRequired(List<String> arguments); @Override TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion); }
@Test public void className() { JaxbUnionExtension jaxb = new JaxbUnionExtension(); ClassName typeName = ClassName.bestGuess("foo.Union"); TypeName calculatedTypeName = jaxb.className(null, null, typeName, null); assertSame(typeName, calculatedTypeName); }
@Override public ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return currentSuggestion; }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return currentSuggestion; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return currentSuggestion; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return currentSuggestion; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return currentSuggestion; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
@Test public void classCreated() { JaxbUnionExtension jaxb = new JaxbUnionExtension(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder("my.BuiltClass"); TypeSpec.Builder builder = jaxb.classCreated(null, unionTypeDeclaration, classBuilder, EventType.INTERFACE); TypeSpec buildClass = builder.build(); TypeSpecAssert.assertThat(buildClass) .hasName("my.BuiltClass"); AnnotationSpecAssert.assertThat(buildClass.annotations.get(0)).hasType(ClassName.get(XmlRootElement.class)); assertEquals("null", builder.build().annotations.get(0).members.get("name").get(0).toString()); assertEquals("\"##default\"", builder.build().annotations.get(0).members.get("namespace").get(0).toString()); }
@Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
@Test public void implementationClassCreated() { JaxbUnionExtension jaxb = new JaxbUnionExtension(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder("my.BuiltClass"); TypeSpec.Builder builder = jaxb.classCreated(null, unionTypeDeclaration, classBuilder, EventType.IMPLEMENTATION); TypeSpec buildClass = builder.build(); TypeSpecAssert.assertThat(buildClass) .hasName("my.BuiltClass"); AnnotationSpecAssert.assertThat(buildClass.annotations.get(0)).hasType(ClassName.get(XmlAccessorType.class)); assertEquals("javax.xml.bind.annotation.XmlAccessType.FIELD", builder.build().annotations.get(0).members.get("value").get(0).toString()); AnnotationSpecAssert.assertThat(buildClass.annotations.get(1)).hasType(ClassName.get(XmlRootElement.class)); assertEquals("null", builder.build().annotations.get(1).members.get("name").get(0).toString()); assertEquals("\"##default\"", builder.build().annotations.get(1).members.get("namespace").get(0).toString()); }
@Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
@Test public void anyFieldCreated() { }
@Override public FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { AnnotationSpec.Builder elementsAnnotation = AnnotationSpec.builder(XmlElements.class); for (TypeDeclaration typeDeclaration : union.of()) { TypeName unionPossibility = context.unionClass(typeDeclaration).getJavaName(EventType.IMPLEMENTATION); elementsAnnotation.addMember("value", "$L", AnnotationSpec .builder(XmlElement.class) .addMember("name", "$S", typeDeclaration.name()) .addMember("type", "$T.class", unionPossibility ) .build()); } anyType.addAnnotation(elementsAnnotation.build()); return anyType; }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { AnnotationSpec.Builder elementsAnnotation = AnnotationSpec.builder(XmlElements.class); for (TypeDeclaration typeDeclaration : union.of()) { TypeName unionPossibility = context.unionClass(typeDeclaration).getJavaName(EventType.IMPLEMENTATION); elementsAnnotation.addMember("value", "$L", AnnotationSpec .builder(XmlElement.class) .addMember("name", "$S", typeDeclaration.name()) .addMember("type", "$T.class", unionPossibility ) .build()); } anyType.addAnnotation(elementsAnnotation.build()); return anyType; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { AnnotationSpec.Builder elementsAnnotation = AnnotationSpec.builder(XmlElements.class); for (TypeDeclaration typeDeclaration : union.of()) { TypeName unionPossibility = context.unionClass(typeDeclaration).getJavaName(EventType.IMPLEMENTATION); elementsAnnotation.addMember("value", "$L", AnnotationSpec .builder(XmlElement.class) .addMember("name", "$S", typeDeclaration.name()) .addMember("type", "$T.class", unionPossibility ) .build()); } anyType.addAnnotation(elementsAnnotation.build()); return anyType; } }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { AnnotationSpec.Builder elementsAnnotation = AnnotationSpec.builder(XmlElements.class); for (TypeDeclaration typeDeclaration : union.of()) { TypeName unionPossibility = context.unionClass(typeDeclaration).getJavaName(EventType.IMPLEMENTATION); elementsAnnotation.addMember("value", "$L", AnnotationSpec .builder(XmlElement.class) .addMember("name", "$S", typeDeclaration.name()) .addMember("type", "$T.class", unionPossibility ) .build()); } anyType.addAnnotation(elementsAnnotation.build()); return anyType; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { AnnotationSpec.Builder elementsAnnotation = AnnotationSpec.builder(XmlElements.class); for (TypeDeclaration typeDeclaration : union.of()) { TypeName unionPossibility = context.unionClass(typeDeclaration).getJavaName(EventType.IMPLEMENTATION); elementsAnnotation.addMember("value", "$L", AnnotationSpec .builder(XmlElement.class) .addMember("name", "$S", typeDeclaration.name()) .addMember("type", "$T.class", unionPossibility ) .build()); } anyType.addAnnotation(elementsAnnotation.build()); return anyType; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }
@Test public void forInteger() throws Exception { setupNumberFacets(); Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Integer.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, number, builder, EventType.IMPLEMENTATION); assertForIntegerNumber(builder); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forBigInt() throws Exception { setupNumberFacets(); Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(BigInteger.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, number, builder, EventType.IMPLEMENTATION); assertForIntegerNumber(builder); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void name() throws Exception { PojoToRamlImpl pojoToRaml = new PojoToRamlImpl(FieldClassParser.factory(), AdjusterFactory.NULL_FACTORY); TypeBuilder builder = pojoToRaml.name(Fun.class.getMethod("stringMethod").getGenericReturnType()); ObjectNode node = builder.buildNode(); assertEquals("type: array", node.getChildren().get(0).toString()); }
@Override public TypeBuilder name(Class<?> clazz) { RamlAdjuster adjuster = this.adjusterFactory.createAdjuster(clazz); ClassParser parser = classParserFactory.createParser(clazz); RamlType type = RamlTypeFactory.forType(clazz, parser, adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return type.getRamlSyntax(); } final String simpleName = adjuster.adjustTypeName(clazz, clazz.getSimpleName()); return TypeBuilder.type(simpleName); }
PojoToRamlImpl implements PojoToRaml { @Override public TypeBuilder name(Class<?> clazz) { RamlAdjuster adjuster = this.adjusterFactory.createAdjuster(clazz); ClassParser parser = classParserFactory.createParser(clazz); RamlType type = RamlTypeFactory.forType(clazz, parser, adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return type.getRamlSyntax(); } final String simpleName = adjuster.adjustTypeName(clazz, clazz.getSimpleName()); return TypeBuilder.type(simpleName); } }
PojoToRamlImpl implements PojoToRaml { @Override public TypeBuilder name(Class<?> clazz) { RamlAdjuster adjuster = this.adjusterFactory.createAdjuster(clazz); ClassParser parser = classParserFactory.createParser(clazz); RamlType type = RamlTypeFactory.forType(clazz, parser, adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return type.getRamlSyntax(); } final String simpleName = adjuster.adjustTypeName(clazz, clazz.getSimpleName()); return TypeBuilder.type(simpleName); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); }
PojoToRamlImpl implements PojoToRaml { @Override public TypeBuilder name(Class<?> clazz) { RamlAdjuster adjuster = this.adjusterFactory.createAdjuster(clazz); ClassParser parser = classParserFactory.createParser(clazz); RamlType type = RamlTypeFactory.forType(clazz, parser, adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return type.getRamlSyntax(); } final String simpleName = adjuster.adjustTypeName(clazz, clazz.getSimpleName()); return TypeBuilder.type(simpleName); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); @Override Result classToRaml(final Class<?> clazz); @Override TypeBuilder name(Class<?> clazz); @Override TypeBuilder name(Type type); }
PojoToRamlImpl implements PojoToRaml { @Override public TypeBuilder name(Class<?> clazz) { RamlAdjuster adjuster = this.adjusterFactory.createAdjuster(clazz); ClassParser parser = classParserFactory.createParser(clazz); RamlType type = RamlTypeFactory.forType(clazz, parser, adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return type.getRamlSyntax(); } final String simpleName = adjuster.adjustTypeName(clazz, clazz.getSimpleName()); return TypeBuilder.type(simpleName); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); @Override Result classToRaml(final Class<?> clazz); @Override TypeBuilder name(Class<?> clazz); @Override TypeBuilder name(Type type); }
@Test public void forObject() throws Exception { Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, object, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forUnion() throws Exception { Jsr303Extension ext = new Jsr303Extension(); TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(ClassName.get("xx.bb", "Foo")); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC); ext.anyFieldCreated(unionPluginContext, union, typeBuilder, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Override public FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { FacetValidation.addFacetsForBuilt(new AnnotationAdder() { @Override public TypeName typeName() { return anyType.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { anyType.addAnnotation(spec); } }); return anyType; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { FacetValidation.addFacetsForBuilt(new AnnotationAdder() { @Override public TypeName typeName() { return anyType.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { anyType.addAnnotation(spec); } }); return anyType; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { FacetValidation.addFacetsForBuilt(new AnnotationAdder() { @Override public TypeName typeName() { return anyType.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { anyType.addAnnotation(spec); } }); return anyType; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { FacetValidation.addFacetsForBuilt(new AnnotationAdder() { @Override public TypeName typeName() { return anyType.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { anyType.addAnnotation(spec); } }); return anyType; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { FacetValidation.addFacetsForBuilt(new AnnotationAdder() { @Override public TypeName typeName() { return anyType.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { anyType.addAnnotation(spec); } }); return anyType; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forDouble() throws Exception { setupNumberFacets(); Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, object, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forArrays() throws Exception { when(array.minItems()).thenReturn(3); when(array.maxItems()).thenReturn(5); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Size.class.getName(), builder.build().annotations.get(0).type.toString()); assertEquals("3", builder.build().annotations.get(0).members.get("min").get(0).toString()); assertEquals("5", builder.build().annotations.get(0).members.get("max").get(0).toString()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forArraysOfStrings() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(0, builder.build().annotations.size()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forArraysOfObject() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); when(array.items()).thenReturn(object); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forArraysOfUnion() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); when(array.items()).thenReturn(union); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forArraysMaxOnly() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(5); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Size.class.getName(), builder.build().annotations.get(0).type.toString()); assertEquals(1, builder.build().annotations.get(0).members.size()); assertEquals("5", builder.build().annotations.get(0).members.get("max").get(0).toString()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void forArraysNotNull() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); when(array.required()).thenReturn(true); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(NotNull.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }
@Test public void javaClassReferenceWithString() { when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), eq(ParameterizedTypeName.get(List.class, String.class)))).thenReturn(ParameterizedTypeName.get(List.class, String.class)); when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), eq(ClassName.get(String.class)))).thenReturn(ClassName.get(String.class)); when(itemType.name()).thenReturn("string"); when(itemType.type()).thenReturn("string"); ArrayTypeHandler handler = new ArrayTypeHandler("string[]", arrayTypeDeclaration); TypeName tn = handler.javaClassReference(context, EventType.INTERFACE); assertEquals("java.util.List<java.lang.String>", tn.toString()); }
@Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }
@Test public void forScalars() throws Exception { RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("one").getGenericType(), null, null).orNull(); assertEquals("string", type.getRamlSyntax().id()); }
public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
@Test public void javaClassReferenceWithListOfSomething() { when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), eq(ParameterizedTypeName.get(List.class, String.class)))).thenReturn(ParameterizedTypeName.get(ClassName.get(List.class), ClassName.bestGuess("foo.Something"))); when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), (TypeName) any())).thenReturn(ParameterizedTypeName.get(ClassName.get(List.class), ClassName.bestGuess("foo.Something"))); when(itemType.name()).thenReturn("Something"); when(itemType.type()).thenReturn("object"); ArrayTypeHandler handler = new ArrayTypeHandler("Something[]", arrayTypeDeclaration); TypeName tn = handler.javaClassReference(context, EventType.INTERFACE); assertEquals("java.util.List<foo.Something>", tn.toString()); }
@Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }
@Test public void javaClassReferenceWithSomethingAsList() { when(arrayTypeHandlerPlugin.className(any(ArrayPluginContext.class), any(ArrayTypeDeclaration.class), (ClassName) eq(null), eq(EventType.INTERFACE))).thenReturn(ClassName.get("foo", "Something")); when(itemType.name()).thenReturn("Something"); when(itemType.type()).thenReturn("object"); ArrayTypeHandler handler = new ArrayTypeHandler("Something", arrayTypeDeclaration); TypeName tn = handler.javaClassReference(context, EventType.INTERFACE); assertEquals("foo.Something", tn.toString()); }
@Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }
ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }
@Test public void fromTypes() throws Exception { when(api.types()).thenReturn(Arrays.asList(t1, t2, t3)); TypeDeclaration typeDeclaration = TypeFetchers.fromTypes().fetchType(api, "t1"); assertSame(t1, typeDeclaration); }
public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }
@Test(expected = GenerationException.class) public void fromTypesFail() throws Exception { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeFetchers.fromTypes().fetchType(api, "nosuchtype"); }
public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); }
TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }
@Test public void fromLibraries() throws Exception { when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeDeclaration typeDeclaration1 = TypeFetchers.fromLibraries().fetchType(api, "t1"); TypeDeclaration typeDeclaration2 = TypeFetchers.fromLibraries().fetchType(api, "t2"); TypeDeclaration typeDeclaration3 = TypeFetchers.fromLibraries().fetchType(api, "t3"); assertSame(typeDeclaration1, t1); assertSame(typeDeclaration2, t2); assertSame(typeDeclaration3, t3); }
public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }
@Test public void fromAnywhere() throws Exception { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeDeclaration typeDeclaration1 = TypeFetchers.fromAnywhere().fetchType(api, "t1"); TypeDeclaration typeDeclaration2 = TypeFetchers.fromAnywhere().fetchType(api, "t2"); TypeDeclaration typeDeclaration3 = TypeFetchers.fromAnywhere().fetchType(api, "t3"); TypeDeclaration typeDeclaration4 = TypeFetchers.fromAnywhere().fetchType(api, "t4"); TypeDeclaration typeDeclaration5 = TypeFetchers.fromAnywhere().fetchType(api, "t5"); TypeDeclaration typeDeclaration6 = TypeFetchers.fromAnywhere().fetchType(api, "t6"); assertSame(typeDeclaration1, t1); assertSame(typeDeclaration2, t2); assertSame(typeDeclaration3, t3); assertSame(typeDeclaration4, t4); assertSame(typeDeclaration5, t5); assertSame(typeDeclaration6, t6); }
public static TypeFetcher fromAnywhere() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(FluentIterable.from(api.types()).append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; }
TypeFetchers { public static TypeFetcher fromAnywhere() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(FluentIterable.from(api.types()).append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromAnywhere() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(FluentIterable.from(api.types()).append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromAnywhere() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(FluentIterable.from(api.types()).append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); }
TypeFetchers { public static TypeFetcher fromAnywhere() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(FluentIterable.from(api.types()).append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }
@Test(expected = GenerationException.class) public void failFromLibraries() throws Exception { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeFetchers.fromLibraries().fetchType(api, "t4"); }
public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); }
TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }
@Test public void inTypes() { when(api.types()).thenReturn(Arrays.asList(t1, t2, t3)); Iterable<TypeDeclaration> it = TypeFinders.inTypes().findTypes(api); assertThat(it, contains(equalTo(t1), equalTo(t2), equalTo(t3))); }
public static TypeFinder inTypes() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return api.types(); } }; }
TypeFinders { public static TypeFinder inTypes() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return api.types(); } }; } }
TypeFinders { public static TypeFinder inTypes() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return api.types(); } }; } }
TypeFinders { public static TypeFinder inTypes() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return api.types(); } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }
TypeFinders { public static TypeFinder inTypes() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return api.types(); } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }
@Test public void inLibraries() { when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); Iterable<TypeDeclaration> it = TypeFinders.inLibraries().findTypes(api); System.err.println(it); assertThat(it, containsInAnyOrder(equalTo(t1), equalTo(t2), equalTo(t3))); }
public static TypeFinder inLibraries() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { List<TypeDeclaration> foundTypes = new ArrayList<>(); Utils.goThroughLibraries(foundTypes, new HashSet<String>(), api.uses()); return foundTypes; } }; }
TypeFinders { public static TypeFinder inLibraries() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { List<TypeDeclaration> foundTypes = new ArrayList<>(); Utils.goThroughLibraries(foundTypes, new HashSet<String>(), api.uses()); return foundTypes; } }; } }
TypeFinders { public static TypeFinder inLibraries() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { List<TypeDeclaration> foundTypes = new ArrayList<>(); Utils.goThroughLibraries(foundTypes, new HashSet<String>(), api.uses()); return foundTypes; } }; } }
TypeFinders { public static TypeFinder inLibraries() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { List<TypeDeclaration> foundTypes = new ArrayList<>(); Utils.goThroughLibraries(foundTypes, new HashSet<String>(), api.uses()); return foundTypes; } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }
TypeFinders { public static TypeFinder inLibraries() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { List<TypeDeclaration> foundTypes = new ArrayList<>(); Utils.goThroughLibraries(foundTypes, new HashSet<String>(), api.uses()); return foundTypes; } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }
@Test public void everyWhere() { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); Iterable<TypeDeclaration> it = TypeFinders.everyWhere().findTypes(api); System.err.println(it); assertThat(it, containsInAnyOrder(equalTo(t1), equalTo(t2), equalTo(t3), equalTo(t4), equalTo(t5), equalTo(t6))); }
public static TypeFinder everyWhere() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return FluentIterable.from(api.types()) .append(resourceTypes(api.resources())) .append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())); } }; }
TypeFinders { public static TypeFinder everyWhere() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return FluentIterable.from(api.types()) .append(resourceTypes(api.resources())) .append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())); } }; } }
TypeFinders { public static TypeFinder everyWhere() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return FluentIterable.from(api.types()) .append(resourceTypes(api.resources())) .append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())); } }; } }
TypeFinders { public static TypeFinder everyWhere() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return FluentIterable.from(api.types()) .append(resourceTypes(api.resources())) .append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())); } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }
TypeFinders { public static TypeFinder everyWhere() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return FluentIterable.from(api.types()) .append(resourceTypes(api.resources())) .append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())); } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }
@Test public void forComposed() throws Exception { when(adjusterFactory.createAdjuster(SubFun.class)).thenReturn(adjuster); when(adjuster.adjustTypeName(SubFun.class, "SubFun")).thenReturn("foo"); RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("sub").getGenericType(), classParser, adjusterFactory).orNull(); assertTrue(type instanceof ComposedRamlType); assertEquals("foo", type.getRamlSyntax().id()); }
public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
@Test public void simple() throws Exception { Foo foo = (Foo) Proxy.newProxyInstance(AugmenterTest.class.getClassLoader(), new Class[] {Foo.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.getName(); } }); Boo b = Augmenter.augment(Boo.class, foo); Assert.assertEquals("HandledBibi", b.getBibi()); Assert.assertEquals("getName", b.getName()); Assert.assertEquals("toString", b.toString()); }
public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } static T augment(Class<T> augmentedInterface, final Object delegate); }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } static T augment(Class<T> augmentedInterface, final Object delegate); }
@Test public void factory() throws Exception { SubFoo subFoo = (SubFoo) Proxy.newProxyInstance(AugmenterTest.class.getClassLoader(), new Class[] {SubFoo.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.getName(); } }); AugmentedNode b = Augmenter.augment(AugmentedNode.class, subFoo); Assert.assertEquals("toString", b.toString()); }
public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } static T augment(Class<T> augmentedInterface, final Object delegate); }
Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } static T augment(Class<T> augmentedInterface, final Object delegate); }
@Test public void response() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withResources( resource("/foo") .withMethods(MethodBuilder.method("get") .withResponses(ResponseBuilder.response(200) .withBodies(BodyBuilder.body("application/json").ofType(TypeBuilder.type("integer"))) ) ) ) .buildModel(); assertEquals("application/json", api.resources().get(0).methods().get(0).responses().get(0).body().get(0).name()); assertEquals("integer", api.resources().get(0).methods().get(0).responses().get(0).body().get(0).type()); }
static public ResponseBuilder response(int code) { return new ResponseBuilder(code); }
ResponseBuilder extends KeyValueNodeBuilder<ResponseBuilder> implements NodeBuilder, AnnotableBuilder<ResponseBuilder> { static public ResponseBuilder response(int code) { return new ResponseBuilder(code); } }
ResponseBuilder extends KeyValueNodeBuilder<ResponseBuilder> implements NodeBuilder, AnnotableBuilder<ResponseBuilder> { static public ResponseBuilder response(int code) { return new ResponseBuilder(code); } private ResponseBuilder(int code); }
ResponseBuilder extends KeyValueNodeBuilder<ResponseBuilder> implements NodeBuilder, AnnotableBuilder<ResponseBuilder> { static public ResponseBuilder response(int code) { return new ResponseBuilder(code); } private ResponseBuilder(int code); static ResponseBuilder response(int code); ResponseBuilder withBodies(BodyBuilder... builder); @Override ResponseBuilder withAnnotations(AnnotationBuilder... builders); @Override KeyValueNode buildNode(); ResponseBuilder description(String description); }
ResponseBuilder extends KeyValueNodeBuilder<ResponseBuilder> implements NodeBuilder, AnnotableBuilder<ResponseBuilder> { static public ResponseBuilder response(int code) { return new ResponseBuilder(code); } private ResponseBuilder(int code); static ResponseBuilder response(int code); ResponseBuilder withBodies(BodyBuilder... builder); @Override ResponseBuilder withAnnotations(AnnotationBuilder... builders); @Override KeyValueNode buildNode(); ResponseBuilder description(String description); }
@Test public void resourceBuilder() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withResources( resource("/foo") .description("happy") ) .buildModel(); assertEquals("/foo", api.resources().get(0).displayName().value()); assertEquals("/foo", api.resources().get(0).resourcePath()); assertEquals("/foo", api.resources().get(0).relativeUri().value()); assertEquals("happy", api.resources().get(0).description().value()); }
private ResourceBuilder(String name) { super(name); }
ResourceBuilder extends KeyValueNodeBuilder<ResourceBuilder> implements NodeBuilder { private ResourceBuilder(String name) { super(name); } }
ResourceBuilder extends KeyValueNodeBuilder<ResourceBuilder> implements NodeBuilder { private ResourceBuilder(String name) { super(name); } private ResourceBuilder(String name); }
ResourceBuilder extends KeyValueNodeBuilder<ResourceBuilder> implements NodeBuilder { private ResourceBuilder(String name) { super(name); } private ResourceBuilder(String name); static ResourceBuilder resource(String name); @Override KeyValueNode buildNode(); ResourceBuilder displayName(String displayName); ResourceBuilder description(String comment); ResourceBuilder relativeUri(String relativeUri); ResourceBuilder withResources(ResourceBuilder... resourceBuilders); ResourceBuilder withMethods(MethodBuilder... methodBuilders); }
ResourceBuilder extends KeyValueNodeBuilder<ResourceBuilder> implements NodeBuilder { private ResourceBuilder(String name) { super(name); } private ResourceBuilder(String name); static ResourceBuilder resource(String name); @Override KeyValueNode buildNode(); ResourceBuilder displayName(String displayName); ResourceBuilder description(String comment); ResourceBuilder relativeUri(String relativeUri); ResourceBuilder withResources(ResourceBuilder... resourceBuilders); ResourceBuilder withMethods(MethodBuilder... methodBuilders); }
@Test public void simpleType() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withTypes( TypeDeclarationBuilder.typeDeclaration("Mom") .ofType(TypeBuilder.type("boolean"))) .buildModel(); assertEquals("Mom", api.types().get(0).name()); assertEquals("boolean", api.types().get(0).type()); }
static public TypeBuilder type(String type) { return new TypeBuilder(type); }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } private TypeBuilder(String type); TypeBuilder(String[] types); TypeBuilder(TypeBuilder builder); }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } private TypeBuilder(String type); TypeBuilder(String[] types); TypeBuilder(TypeBuilder builder); String id(); static TypeBuilder type(String type); static TypeBuilder arrayOf(TypeBuilder builder); static TypeBuilder type(); static TypeBuilder type(String... types); @Override TypeBuilder withAnnotations(AnnotationBuilder... builders); TypeBuilder withProperty(TypePropertyBuilder... properties); TypeBuilder withExamples(ExamplesBuilder... properties); TypeBuilder withExample(ExamplesBuilder example); TypeBuilder withFacets(FacetBuilder... facetBuilders); TypeBuilder description(String description); TypeBuilder enumValues(String... enumValues); TypeBuilder enumValues(long... enumValues); TypeBuilder enumValues(boolean... enumValues); @Override ObjectNode buildNode(); }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } private TypeBuilder(String type); TypeBuilder(String[] types); TypeBuilder(TypeBuilder builder); String id(); static TypeBuilder type(String type); static TypeBuilder arrayOf(TypeBuilder builder); static TypeBuilder type(); static TypeBuilder type(String... types); @Override TypeBuilder withAnnotations(AnnotationBuilder... builders); TypeBuilder withProperty(TypePropertyBuilder... properties); TypeBuilder withExamples(ExamplesBuilder... properties); TypeBuilder withExample(ExamplesBuilder example); TypeBuilder withFacets(FacetBuilder... facetBuilders); TypeBuilder description(String description); TypeBuilder enumValues(String... enumValues); TypeBuilder enumValues(long... enumValues); TypeBuilder enumValues(boolean... enumValues); @Override ObjectNode buildNode(); public String[] types; }
@Test public void unionType() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withTypes( TypeDeclarationBuilder.typeDeclaration("Mom") .ofType(TypeBuilder.type("string | integer") ) ) .buildModel(); assertEquals("Mom", api.types().get(0).name()); assertEquals("string | integer", api.types().get(0).type()); assertEquals("string | integer", ((UnionTypeDeclaration)api.types().get(0)).of().get(0).name()); assertEquals("string | integer", ((UnionTypeDeclaration)api.types().get(0)).of().get(1).name()); }
static public TypeBuilder type(String type) { return new TypeBuilder(type); }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } private TypeBuilder(String type); TypeBuilder(String[] types); TypeBuilder(TypeBuilder builder); }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } private TypeBuilder(String type); TypeBuilder(String[] types); TypeBuilder(TypeBuilder builder); String id(); static TypeBuilder type(String type); static TypeBuilder arrayOf(TypeBuilder builder); static TypeBuilder type(); static TypeBuilder type(String... types); @Override TypeBuilder withAnnotations(AnnotationBuilder... builders); TypeBuilder withProperty(TypePropertyBuilder... properties); TypeBuilder withExamples(ExamplesBuilder... properties); TypeBuilder withExample(ExamplesBuilder example); TypeBuilder withFacets(FacetBuilder... facetBuilders); TypeBuilder description(String description); TypeBuilder enumValues(String... enumValues); TypeBuilder enumValues(long... enumValues); TypeBuilder enumValues(boolean... enumValues); @Override ObjectNode buildNode(); }
TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } private TypeBuilder(String type); TypeBuilder(String[] types); TypeBuilder(TypeBuilder builder); String id(); static TypeBuilder type(String type); static TypeBuilder arrayOf(TypeBuilder builder); static TypeBuilder type(); static TypeBuilder type(String... types); @Override TypeBuilder withAnnotations(AnnotationBuilder... builders); TypeBuilder withProperty(TypePropertyBuilder... properties); TypeBuilder withExamples(ExamplesBuilder... properties); TypeBuilder withExample(ExamplesBuilder example); TypeBuilder withFacets(FacetBuilder... facetBuilders); TypeBuilder description(String description); TypeBuilder enumValues(String... enumValues); TypeBuilder enumValues(long... enumValues); TypeBuilder enumValues(boolean... enumValues); @Override ObjectNode buildNode(); public String[] types; }
@Test public void emit() throws Exception { when(api.getNode()).thenReturn(node); when(node.getChildren()).thenReturn(Arrays.asList(child1, child2)); Emitter emitter = new Emitter(list) { @Override protected YamlEmitter createEmitter(Writer w) { assertSame(w, writer); return yamlEmitter; } }; emitter.emit(api, writer); verify(list).handle(eq(child1), any(YamlEmitter.class) ); verify(list).handle(eq(child2), any(YamlEmitter.class) ); }
public void emit(Api api) throws IOException { emit(api, new OutputStreamWriter(System.out)); }
Emitter { public void emit(Api api) throws IOException { emit(api, new OutputStreamWriter(System.out)); } }
Emitter { public void emit(Api api) throws IOException { emit(api, new OutputStreamWriter(System.out)); } Emitter(HandlerList list); Emitter(); }
Emitter { public void emit(Api api) throws IOException { emit(api, new OutputStreamWriter(System.out)); } Emitter(HandlerList list); Emitter(); void emit(Api api); void emit(Api api, Writer w); }
Emitter { public void emit(Api api) throws IOException { emit(api, new OutputStreamWriter(System.out)); } Emitter(HandlerList list); Emitter(); void emit(Api api); void emit(Api api, Writer w); }
@Test public void handles() throws Exception { when(nodeHandler1.handles(node)).thenReturn(true); HandlerList list = new HandlerList(Arrays.<NodeHandler<? extends Node>>asList(nodeHandler1, nodeHandler2)); assertTrue(list.handles(node)); verify(nodeHandler2, never()).handles(any(Node.class)); }
@Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); @Override boolean handles(final Node node); @Override boolean handleSafely(final Node node, YamlEmitter emitter); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); @Override boolean handles(final Node node); @Override boolean handleSafely(final Node node, YamlEmitter emitter); }
@Test public void handlesNone() throws Exception { when(nodeHandler1.handles(node)).thenReturn(false); when(nodeHandler2.handles(node)).thenReturn(false); HandlerList list = new HandlerList(Arrays.<NodeHandler<? extends Node>>asList(nodeHandler1, nodeHandler2)); assertFalse(list.handles(node)); }
@Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); @Override boolean handles(final Node node); @Override boolean handleSafely(final Node node, YamlEmitter emitter); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); @Override boolean handles(final Node node); @Override boolean handleSafely(final Node node, YamlEmitter emitter); }
@Test public void actuallyHandleSafely() throws Exception { when(nodeHandler1.handles(node)).thenReturn(false); when(nodeHandler2.handles(node)).thenReturn(true); when(nodeHandler2.handle(node, emitter)).thenReturn(true); HandlerList list = new HandlerList(Arrays.<NodeHandler<? extends Node>>asList(nodeHandler1, nodeHandler2)); assertTrue(list.handle(node, emitter)); verify(nodeHandler1, never()).handle(any(Node.class), any(YamlEmitter.class)); verify(nodeHandler2).handle(node, emitter); }
@Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); @Override boolean handles(final Node node); @Override boolean handleSafely(final Node node, YamlEmitter emitter); }
HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); @Override boolean handles(final Node node); @Override boolean handleSafely(final Node node, YamlEmitter emitter); }
@Test public void forCollectionsOfScalars() throws Exception { RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("listOfStrings").getGenericType(), null, null).orNull(); assertTrue(type instanceof CollectionRamlType); assertEquals("array", type.getRamlSyntax().id()); }
public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
@Test public void handles() throws Exception { ReferenceNodeHandler handler = new ReferenceNodeHandler(); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
@Override public boolean handles(Node node) { return node instanceof ReferenceNode; }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handles(Node node) { return node instanceof ReferenceNode; } }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handles(Node node) { return node instanceof ReferenceNode; } }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handles(Node node) { return node instanceof ReferenceNode; } @Override boolean handles(Node node); @Override boolean handleSafely(ReferenceNode node, YamlEmitter emitter); }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handles(Node node) { return node instanceof ReferenceNode; } @Override boolean handles(Node node); @Override boolean handleSafely(ReferenceNode node, YamlEmitter emitter); }
@Test public void handleSafely() throws Exception { when(goodNode.getRefName()).thenReturn("ref.value"); ReferenceNodeHandler rnh = new ReferenceNodeHandler(); rnh.handleSafely(goodNode, emitter); verify(emitter).writeObjectValue("ref.value"); }
@Override public boolean handleSafely(ReferenceNode node, YamlEmitter emitter) throws IOException { emitter.writeObjectValue(node.getRefName()); return true; }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handleSafely(ReferenceNode node, YamlEmitter emitter) throws IOException { emitter.writeObjectValue(node.getRefName()); return true; } }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handleSafely(ReferenceNode node, YamlEmitter emitter) throws IOException { emitter.writeObjectValue(node.getRefName()); return true; } }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handleSafely(ReferenceNode node, YamlEmitter emitter) throws IOException { emitter.writeObjectValue(node.getRefName()); return true; } @Override boolean handles(Node node); @Override boolean handleSafely(ReferenceNode node, YamlEmitter emitter); }
ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handleSafely(ReferenceNode node, YamlEmitter emitter) throws IOException { emitter.writeObjectValue(node.getRefName()); return true; } @Override boolean handles(Node node); @Override boolean handleSafely(ReferenceNode node, YamlEmitter emitter); }
@Test public void handles() throws Exception { TypeDeclarationNodeHandler tdnh = new TypeDeclarationNodeHandler(list); assertFalse(tdnh.handles(badNode)); assertTrue(tdnh.handles(goodNode)); }
@Override public boolean handles(Node node) { return node instanceof TypeDeclarationNode; }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handles(Node node) { return node instanceof TypeDeclarationNode; } }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handles(Node node) { return node instanceof TypeDeclarationNode; } TypeDeclarationNodeHandler(HandlerList handlerList); }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handles(Node node) { return node instanceof TypeDeclarationNode; } TypeDeclarationNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter); }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handles(Node node) { return node instanceof TypeDeclarationNode; } TypeDeclarationNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter); }
@Test public void handleSafely() throws Exception { when(goodNode.getChildren()).thenReturn(Collections.<Node>singletonList(keyValueNode)); TypeDeclarationNodeHandler handler = new TypeDeclarationNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(list).handle(keyValueNode, emitter); }
@Override public boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { handlerList.handle(child, emitter); } return true; }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { handlerList.handle(child, emitter); } return true; } }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { handlerList.handle(child, emitter); } return true; } TypeDeclarationNodeHandler(HandlerList handlerList); }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { handlerList.handle(child, emitter); } return true; } TypeDeclarationNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter); }
TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { handlerList.handle(child, emitter); } return true; } TypeDeclarationNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter); }
@Test public void handles() throws Exception { ArrayNodeHandler handler = new ArrayNodeHandler(list); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
@Override public boolean handles(Node node) { return node instanceof ArrayNode; }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handles(Node node) { return node instanceof ArrayNode; } }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handles(Node node) { return node instanceof ArrayNode; } ArrayNodeHandler(HandlerList handlerList); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handles(Node node) { return node instanceof ArrayNode; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handles(Node node) { return node instanceof ArrayNode; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
@Test public void handleSafelyEmpty() throws Exception { ArrayNodeHandler handler = new ArrayNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(emitter).writeSyntaxElement("["); verify(emitter).writeSyntaxElement("]"); verifyNoMoreInteractions(emitter); }
@Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
@Test public void handleSafelyTwoScalarElements() throws Exception { when(goodNode.getChildren()).thenReturn(Arrays.<Node>asList(scalar1, scalar2)); ArrayNodeHandler handler = new ArrayNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(emitter).writeSyntaxElement("["); verify(emitter).writeSyntaxElement(","); verify(emitter).writeSyntaxElement("]"); verify(list).handle(scalar1, emitter); verify(list).handle(scalar2, emitter); verifyNoMoreInteractions(emitter, list); }
@Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
@Test public void handleSafelyTwoNonScalarElements() throws Exception { when(goodNode.getChildren()).thenReturn(Arrays.asList(object1, object2)); when(emitter.indent()).thenReturn(subEmitter); when(subEmitter.bulletListArray()).thenReturn(bullet); ArrayNodeHandler handler = new ArrayNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(emitter).indent(); verify(subEmitter, times(2)).bulletListArray(); verify(subEmitter, times(2)).writeSyntaxElement("\n"); verify(subEmitter, times(2)).writeSyntaxElement("- "); verify(subEmitter, times(2)).writeIndent(); verify(list).handle(object1, bullet); verify(list).handle(object2, bullet); verifyNoMoreInteractions(emitter, subEmitter, list); }
@Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }
@Test public void handles() throws Exception { KeyValueNodeHandler handler = new KeyValueNodeHandler(list); assertFalse(handler.handles(notKeyNode)); assertTrue(handler.handles(keyNode)); }
@Override public boolean handles(Node node) { return node instanceof KeyValueNode; }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handles(Node node) { return node instanceof KeyValueNode; } }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handles(Node node) { return node instanceof KeyValueNode; } KeyValueNodeHandler(HandlerList handlerList); }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handles(Node node) { return node instanceof KeyValueNode; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handles(Node node) { return node instanceof KeyValueNode; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }
@Test public void handleSafelyScalar() throws Exception { when(keyNode.getValue()).thenReturn(simpleNode); when(keyNode.getKey()).thenReturn(new StringNodeImpl("hello")); KeyValueNodeHandler handler = new KeyValueNodeHandler(list); assertTrue(handler.handleSafely(keyNode, emitter)); verify(emitter).writeTag("hello"); verify(list).handle(simpleNode, emitter); }
@Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } KeyValueNodeHandler(HandlerList handlerList); }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }
@Test public void forCollectionsOfScalarsFromArray() throws Exception { when(adjusterFactory.createAdjuster(Fun.class)).thenReturn(RamlAdjuster.NULL_ADJUSTER); RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("arrayOfInts").getGenericType(), null, adjusterFactory).orNull(); assertTrue(type instanceof CollectionRamlType); assertEquals("array", type.getRamlSyntax().id()); }
public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
@Test public void handleSafelyObject() throws Exception { when(keyNode.getValue()).thenReturn(objectNode); when(emitter.indent()).thenReturn(subEmitter); when(keyNode.getKey()).thenReturn(new StringNodeImpl("hello")); KeyValueNodeHandler handler = new KeyValueNodeHandler(list); assertTrue(handler.handleSafely(keyNode, emitter)); verify(emitter).writeTag("hello"); verify(list).handle(objectNode, subEmitter); }
@Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } KeyValueNodeHandler(HandlerList handlerList); }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }
KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }
@Test public void fallsThrough() throws Exception { when(subNodeHandler.handle(node, emitter)).thenReturn(false); SubclassedNodeHandler<ObjectNode> on = new SubclassedNodeHandler<ObjectNode>(ObjectNode.class, subNodeHandler) { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { nodeVerifier.handleSafely(node, emitter); return true; } }; assertTrue(on.handle(node, emitter)); verify(subNodeHandler).handle(node, emitter); verify(nodeVerifier).handleSafely(node, emitter); }
@Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } SubclassedNodeHandler(Class<?> superClass, HandlerList subclassHandlerList); }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } SubclassedNodeHandler(Class<?> superClass, HandlerList subclassHandlerList); @Override boolean handles(Node node); @Override boolean handle(Node node, YamlEmitter emitter); }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } SubclassedNodeHandler(Class<?> superClass, HandlerList subclassHandlerList); @Override boolean handles(Node node); @Override boolean handle(Node node, YamlEmitter emitter); }
@Test public void sublistHandles() throws Exception { when(subNodeHandler.handle(node, emitter)).thenReturn(true); SubclassedNodeHandler<ObjectNode> on = new SubclassedNodeHandler<ObjectNode>(ObjectNode.class, subNodeHandler) { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { nodeVerifier.handleSafely(node, emitter); return true; } }; assertTrue(on.handle(node, emitter)); verify(subNodeHandler).handle(node, emitter); verify(nodeVerifier, never()).handleSafely(node, emitter); }
@Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } SubclassedNodeHandler(Class<?> superClass, HandlerList subclassHandlerList); }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } SubclassedNodeHandler(Class<?> superClass, HandlerList subclassHandlerList); @Override boolean handles(Node node); @Override boolean handle(Node node, YamlEmitter emitter); }
SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } SubclassedNodeHandler(Class<?> superClass, HandlerList subclassHandlerList); @Override boolean handles(Node node); @Override boolean handle(Node node, YamlEmitter emitter); }
@Test public void handles() throws Exception { TypeExpressionNodeHandler handler = new TypeExpressionNodeHandler(list); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
@Override public boolean handles(Node node) { return node instanceof TypeExpressionNode; }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handles(Node node) { return node instanceof TypeExpressionNode; } }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handles(Node node) { return node instanceof TypeExpressionNode; } TypeExpressionNodeHandler(HandlerList handlerList); }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handles(Node node) { return node instanceof TypeExpressionNode; } TypeExpressionNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter); }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handles(Node node) { return node instanceof TypeExpressionNode; } TypeExpressionNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter); }
@Test public void handleSafely() throws Exception { when(goodNode.getTypeExpressionText()).thenReturn("JustReference"); TypeExpressionNodeHandler handler = new TypeExpressionNodeHandler(list); handler.handle(goodNode, emitter); verify(emitter).writeObjectValue("JustReference"); }
@Override public boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter) throws IOException { List<LibraryRefNode> descs = node.findDescendantsWith(LibraryRefNode.class); if ( descs.size() != 0 && descs.get(0) != null ) { emitter.writeObjectValue(descs.get(0).getRefName() + "." +node.getTypeExpressionText()); } else { emitter.writeObjectValue(node.getTypeExpressionText()); } return true; }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter) throws IOException { List<LibraryRefNode> descs = node.findDescendantsWith(LibraryRefNode.class); if ( descs.size() != 0 && descs.get(0) != null ) { emitter.writeObjectValue(descs.get(0).getRefName() + "." +node.getTypeExpressionText()); } else { emitter.writeObjectValue(node.getTypeExpressionText()); } return true; } }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter) throws IOException { List<LibraryRefNode> descs = node.findDescendantsWith(LibraryRefNode.class); if ( descs.size() != 0 && descs.get(0) != null ) { emitter.writeObjectValue(descs.get(0).getRefName() + "." +node.getTypeExpressionText()); } else { emitter.writeObjectValue(node.getTypeExpressionText()); } return true; } TypeExpressionNodeHandler(HandlerList handlerList); }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter) throws IOException { List<LibraryRefNode> descs = node.findDescendantsWith(LibraryRefNode.class); if ( descs.size() != 0 && descs.get(0) != null ) { emitter.writeObjectValue(descs.get(0).getRefName() + "." +node.getTypeExpressionText()); } else { emitter.writeObjectValue(node.getTypeExpressionText()); } return true; } TypeExpressionNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter); }
TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter) throws IOException { List<LibraryRefNode> descs = node.findDescendantsWith(LibraryRefNode.class); if ( descs.size() != 0 && descs.get(0) != null ) { emitter.writeObjectValue(descs.get(0).getRefName() + "." +node.getTypeExpressionText()); } else { emitter.writeObjectValue(node.getTypeExpressionText()); } return true; } TypeExpressionNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter); }
@Test public void handleSafely() throws Exception { when(objectNode.getChildren()).thenReturn(Collections.<Node>singletonList(child)); ObjectNodeHandler on = new ObjectNodeHandler(list); on.handleSafely(objectNode, emitter); verify(list).handle(child, emitter); }
@Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } ObjectNodeHandler(HandlerList handlerList); }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } ObjectNodeHandler(HandlerList handlerList); @Override boolean handleSafely(ObjectNode node, YamlEmitter emitter); }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } ObjectNodeHandler(HandlerList handlerList); @Override boolean handleSafely(ObjectNode node, YamlEmitter emitter); }
@Test public void handleSafelyScalar() throws Exception { when(objectNode.getChildren()).thenReturn(Collections.<Node>singletonList(scalarNode)); ObjectNodeHandler on = new ObjectNodeHandler(list); on.handleSafely(objectNode, emitter); verify(emitter).writeObjectValue("foo"); }
@Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } ObjectNodeHandler(HandlerList handlerList); }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } ObjectNodeHandler(HandlerList handlerList); @Override boolean handleSafely(ObjectNode node, YamlEmitter emitter); }
ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } ObjectNodeHandler(HandlerList handlerList); @Override boolean handleSafely(ObjectNode node, YamlEmitter emitter); }
@Test public void handles() throws Exception { NullNodeHandler handler = new NullNodeHandler(); assertFalse(handler.handles(notNullNode)); assertTrue(handler.handles(nullNode)); }
@Override public boolean handles(Node node) { return node instanceof NullNode; }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handles(Node node) { return node instanceof NullNode; } }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handles(Node node) { return node instanceof NullNode; } NullNodeHandler(); }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handles(Node node) { return node instanceof NullNode; } NullNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(NullNode node, YamlEmitter emitter); }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handles(Node node) { return node instanceof NullNode; } NullNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(NullNode node, YamlEmitter emitter); }
@Test public void handleSafely() throws Exception { NullNodeHandler nul = new NullNodeHandler(); nul.handleSafely(nullNode, emitter); verifyNoMoreInteractions(emitter); }
@Override public boolean handleSafely(NullNode node, YamlEmitter emitter) throws IOException { return true; }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handleSafely(NullNode node, YamlEmitter emitter) throws IOException { return true; } }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handleSafely(NullNode node, YamlEmitter emitter) throws IOException { return true; } NullNodeHandler(); }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handleSafely(NullNode node, YamlEmitter emitter) throws IOException { return true; } NullNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(NullNode node, YamlEmitter emitter); }
NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handleSafely(NullNode node, YamlEmitter emitter) throws IOException { return true; } NullNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(NullNode node, YamlEmitter emitter); }
@Test public void handles() throws Exception { SimpleTypeNodeHandler handler = new SimpleTypeNodeHandler(); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
@Override public boolean handles(Node node) { return node instanceof SimpleTypeNode; }
SimpleTypeNodeHandler extends NodeHandler<SimpleTypeNode<?>> { @Override public boolean handles(Node node) { return node instanceof SimpleTypeNode; } }
SimpleTypeNodeHandler extends NodeHandler<SimpleTypeNode<?>> { @Override public boolean handles(Node node) { return node instanceof SimpleTypeNode; } SimpleTypeNodeHandler(); }
SimpleTypeNodeHandler extends NodeHandler<SimpleTypeNode<?>> { @Override public boolean handles(Node node) { return node instanceof SimpleTypeNode; } SimpleTypeNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(SimpleTypeNode<?> node, YamlEmitter emitter); }
SimpleTypeNodeHandler extends NodeHandler<SimpleTypeNode<?>> { @Override public boolean handles(Node node) { return node instanceof SimpleTypeNode; } SimpleTypeNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(SimpleTypeNode<?> node, YamlEmitter emitter); }
@Test public void forListOfComposed() throws Exception { when(adjusterFactory.createAdjuster(SubFun.class)).thenReturn(RamlAdjuster.NULL_ADJUSTER); when(adjuster.adjustTypeName(SubFun.class, "SubFun")).thenReturn("foo"); RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("listOfSubs").getGenericType(), classParser, adjusterFactory).orNull(); assertTrue(type instanceof CollectionRamlType); assertEquals("array", type.getRamlSyntax().id()); }
public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); }
@Test public void deserializeGeneric() throws Exception { ArrayList<ContentValues> highlightsReturn = Highlight.deserializeToContentValues(serialized1,pagId,0); ArrayList<ContentValues> highlightsGiven = new ArrayList<>(); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, pagId.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID,2); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME,"highlight3"); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, 0); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, "dcdcdc "); highlightsGiven.add(contentValues); contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, pagId.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID,4); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME,"highlight1"); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, 0); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, "cdcdc "); highlightsGiven.add(contentValues); assertEquals(highlightsGiven.size(), highlightsReturn.size()); }
@NonNull public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId) { Matcher matcher = HIGHLIGHT_PATTERN.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<ContentValues> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_BOOK_ID, bookId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, highlight.pageInfo.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID, highlight.id); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME, highlight.className); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, highlight.containerElementId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, highlight.text); highlights.add(contentValues); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId) { Matcher matcher = HIGHLIGHT_PATTERN.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<ContentValues> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_BOOK_ID, bookId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, highlight.pageInfo.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID, highlight.id); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME, highlight.className); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, highlight.containerElementId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, highlight.text); highlights.add(contentValues); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId) { Matcher matcher = HIGHLIGHT_PATTERN.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<ContentValues> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_BOOK_ID, bookId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, highlight.pageInfo.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID, highlight.id); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME, highlight.className); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, highlight.containerElementId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, highlight.text); highlights.add(contentValues); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId) { Matcher matcher = HIGHLIGHT_PATTERN.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<ContentValues> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_BOOK_ID, bookId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, highlight.pageInfo.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID, highlight.id); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME, highlight.className); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, highlight.containerElementId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, highlight.text); highlights.add(contentValues); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); @ColorInt static int getHighlightColor(@NonNull String className); @ColorInt static int getDarkHighlightColor(@NonNull String className); @NonNull static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId); @NonNull static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId); @Override int compareTo(@NonNull Highlight highlight); boolean hasNote(); Date getDateTime(); }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId) { Matcher matcher = HIGHLIGHT_PATTERN.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<ContentValues> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_BOOK_ID, bookId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, highlight.pageInfo.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID, highlight.id); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME, highlight.className); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, highlight.containerElementId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, highlight.text); highlights.add(contentValues); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); @ColorInt static int getHighlightColor(@NonNull String className); @ColorInt static int getDarkHighlightColor(@NonNull String className); @NonNull static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId); @NonNull static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId); @Override int compareTo(@NonNull Highlight highlight); boolean hasNote(); Date getDateTime(); static boolean sortByDate; public String text; public int id; public String className; public int containerElementId; public String noteText; }
@Test public void deserialize() throws Exception { ArrayList<Highlight> highlightsRerurn = Highlight.deserialize(serialized1,pagId,0); ArrayList<Highlight> highlightsGiven = new ArrayList<>(); highlightsGiven.add(new Highlight("dcdcdc ", 2, "highlight3", 0, pagId, "note",0)); highlightsGiven.add(new Highlight("cdcdc ", 4, "highlight1", 0, pagId, "note",0)); assertEquals(highlightsRerurn.size(), highlightsRerurn.size()); for (int i = 0; i < highlightsRerurn.size(); i++) { Highlight expectedHighlight = highlightsGiven.get(i); Highlight HighlightActual = highlightsGiven.get(i); assertEquals(expectedHighlight.containerElementId, HighlightActual.containerElementId); assertEquals(expectedHighlight.id, HighlightActual.id); assertEquals(expectedHighlight.className, HighlightActual.className); assertEquals(expectedHighlight.text, HighlightActual.text); } }
@NonNull public static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId) { final Pattern pattern = Pattern.compile("^type:(\\w+)(?:\\|(\\d+)\\$(\\d+)\\$(\\d+)\\$(\\w+)\\$(\\d*)\\$([^|]+))+$"); Matcher matcher = pattern.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<Highlight> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); highlights.add(highlight); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId) { final Pattern pattern = Pattern.compile("^type:(\\w+)(?:\\|(\\d+)\\$(\\d+)\\$(\\d+)\\$(\\w+)\\$(\\d*)\\$([^|]+))+$"); Matcher matcher = pattern.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<Highlight> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); highlights.add(highlight); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId) { final Pattern pattern = Pattern.compile("^type:(\\w+)(?:\\|(\\d+)\\$(\\d+)\\$(\\d+)\\$(\\w+)\\$(\\d*)\\$([^|]+))+$"); Matcher matcher = pattern.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<Highlight> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); highlights.add(highlight); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId) { final Pattern pattern = Pattern.compile("^type:(\\w+)(?:\\|(\\d+)\\$(\\d+)\\$(\\d+)\\$(\\w+)\\$(\\d*)\\$([^|]+))+$"); Matcher matcher = pattern.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<Highlight> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); highlights.add(highlight); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); @ColorInt static int getHighlightColor(@NonNull String className); @ColorInt static int getDarkHighlightColor(@NonNull String className); @NonNull static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId); @NonNull static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId); @Override int compareTo(@NonNull Highlight highlight); boolean hasNote(); Date getDateTime(); }
Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId) { final Pattern pattern = Pattern.compile("^type:(\\w+)(?:\\|(\\d+)\\$(\\d+)\\$(\\d+)\\$(\\w+)\\$(\\d*)\\$([^|]+))+$"); Matcher matcher = pattern.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<Highlight> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); highlights.add(highlight); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); @ColorInt static int getHighlightColor(@NonNull String className); @ColorInt static int getDarkHighlightColor(@NonNull String className); @NonNull static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId); @NonNull static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId); @Override int compareTo(@NonNull Highlight highlight); boolean hasNote(); Date getDateTime(); static boolean sortByDate; public String text; public int id; public String className; public int containerElementId; public String noteText; }
@Test public void handleTatweela() throws Exception { assertEquals(ArabicUtilities.handleTatweela("بـــــــــــــــــــسم"), "بسم"); assertEquals(ArabicUtilities.handleTatweela("هـ"), "هـ"); }
public static String handleTatweela(@NonNull String s) { Matcher matcher4 = TATWEELA_PATTERN.matcher(s); StringBuffer sb2 = new StringBuffer(); while (matcher4.find()) { matcher4.appendReplacement(sb2, "$1$3"); } matcher4.appendTail(sb2); return sb2.toString(); }
ArabicUtilities { public static String handleTatweela(@NonNull String s) { Matcher matcher4 = TATWEELA_PATTERN.matcher(s); StringBuffer sb2 = new StringBuffer(); while (matcher4.find()) { matcher4.appendReplacement(sb2, "$1$3"); } matcher4.appendTail(sb2); return sb2.toString(); } }
ArabicUtilities { public static String handleTatweela(@NonNull String s) { Matcher matcher4 = TATWEELA_PATTERN.matcher(s); StringBuffer sb2 = new StringBuffer(); while (matcher4.find()) { matcher4.appendReplacement(sb2, "$1$3"); } matcher4.appendTail(sb2); return sb2.toString(); } }
ArabicUtilities { public static String handleTatweela(@NonNull String s) { Matcher matcher4 = TATWEELA_PATTERN.matcher(s); StringBuffer sb2 = new StringBuffer(); while (matcher4.find()) { matcher4.appendReplacement(sb2, "$1$3"); } matcher4.appendTail(sb2); return sb2.toString(); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); }
ArabicUtilities { public static String handleTatweela(@NonNull String s) { Matcher matcher4 = TATWEELA_PATTERN.matcher(s); StringBuffer sb2 = new StringBuffer(); while (matcher4.find()) { matcher4.appendReplacement(sb2, "$1$3"); } matcher4.appendTail(sb2); return sb2.toString(); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }
@Test public void cleanTextForSearchingIndexing() throws Exception { assertEquals(ArabicUtilities.cleanTextForSearchingIndexing(testCase), "هذا المستدرك ثم بعد ان جمعت فتاوي ورسائل مفتي الديار السعوديه ورئيس قضائها والشئون الاسلاميه سماحه الشيخ محمد بن ابراهيم ال الشيخ بامر جلاله الملك فيصل بن عبد العزيز ال سعود رحمه الله وطبعت في مطبعه الحكومه بمكه المكرمه عام تسعه وتسعين وثلاثمائه والف بامره في ثلاثه عشر مجلدا وانتشرت وانتفع الناس بها فكرت في البحث عن شيء ما لشيخ الاسلام احمد ابن تيميه قدس الله روحه فتذكرت اني حين سافرت الي بغداد للبحث عن فتاوي شيخ الاسلام عثرت علي مجلد من الدرر المضيه من الفتاوي المصريه وعدد مجلداتها سته فيما ذكره ابن القيم رحمه الله ويقول العليمي سبعه وتبين ان الخمسه الباقيه مفقوده رايت بعد ذلك ان ارجع الي مختصر هذه الفتاوي الذي اختصره بدر الدين محمد بن علي بن محمد البعلي الحنبلي المتوفي سنه او هـ وطبع في مطبعه انصار السنه بمصر في عام هـ لاجمع منها ما ليس في الجزء الاول الذي ادخلته في مجموع الفتاوي السابق فوجدت فيه فتاوي كثيره ليست في المجموع الاول بلغ عددها سبعا وخمسين ومائتي مساله قليل منها موجود في المجموع السابق لكن في هذا مع زياده ولها فهرس عام في مجلد مخطوط ذكرها ابن القيم في النونيه بقوله وكذاك اجوبه له مصريه في ست اسفار كتبن سمان ويقول العليمي انها سبع مجلدات الدر المنضد جـ "); }
public static String cleanTextForSearchingIndexing(String s) { return cleanTextForSearchingQuery(cleanHtml(s)); }
ArabicUtilities { public static String cleanTextForSearchingIndexing(String s) { return cleanTextForSearchingQuery(cleanHtml(s)); } }
ArabicUtilities { public static String cleanTextForSearchingIndexing(String s) { return cleanTextForSearchingQuery(cleanHtml(s)); } }
ArabicUtilities { public static String cleanTextForSearchingIndexing(String s) { return cleanTextForSearchingQuery(cleanHtml(s)); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); }
ArabicUtilities { public static String cleanTextForSearchingIndexing(String s) { return cleanTextForSearchingQuery(cleanHtml(s)); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }
@Test public void cleanHtml() throws Exception { assertEquals(ArabicUtilities.cleanHtml(testCase), "هذا المستدرك\nثم بعد أن جمعت فتاوى ورسائل مفتي الديار السعودية ورئيس قضائها والشئون الإسلامية سماحة الشيخ محمد بن إبراهيم آل الشيخ بأمر جلالة الملك فيصل بن عبد العزيز آل سعود رحمه الله وطبعت في مطبعة الحكومة بمكة المكرمة عام تسعة وتسعين وثلاثمائة وألف بأمره في ثلاثة عشر مجلدا وانتشرت، وانتفع الناس بها (?) فكرت في البحث عن شيء «ما» لشيخ الإسلام أحمد ابن تيمية (قدس الله روحه) ، فتذكرت أني حين سافرت إلى بغداد للبحث عن فتاوى شيخ الإسلام عثرت على مجلد من «الدرر المضية من الفتاوى المصرية» وعدد مجلداتها ستة فيما ذكره ابن القيم رحمه الله ويقول العليمي سبعة (?) ، وتبين أن الخمسة الباقية مفقودة رأيت بعد ذلك أن أرجع إلى مختصر هذه الفتاوى الذي اختصره بدر الدين محمد بن علي بن محمد البعلي الحنبلي المتوفى سنة 777 أو 778هـ وطبع في مطبعة أنصار السنة بمصر في عام 1368هـ لأجمع منها ما ليس في الجزء الأول الذي أدخلته في مجموع الفتاوى السابق، فوجدت فيه فتاوى كثيرة ليست في المجموع الأول، بلغ عددها سبعا وخمسين ومائتي مسألة قليل منها موجود في المجموع السابق لكن في هذا مع زيادة.\n\nولها فهرس عام في مجلد مخطوط.\nذكرها ابن القيم في النونية بقوله:\nوكذاك أجوبة له مصرية ... في ست أسفار كتبن سمان\nويقول العليمي: إنها سبع مجلدات (الدر المنضد جـ2/478)"); }
@NonNull public static String cleanHtml(String htmlText) { Document doc = Jsoup.parse(htmlText); Elements footnotes = doc.select("a[title].comment"); StringBuilder htmlTextBuilder = new StringBuilder(htmlText); for (Element footnote : footnotes) { htmlTextBuilder.append("\n").append(footnote.attr("title")); } String encodedHtml = REMOVE_HTML_TAGS.matcher(htmlTextBuilder.toString()).replaceAll(""); return encodedHtml; }
ArabicUtilities { @NonNull public static String cleanHtml(String htmlText) { Document doc = Jsoup.parse(htmlText); Elements footnotes = doc.select("a[title].comment"); StringBuilder htmlTextBuilder = new StringBuilder(htmlText); for (Element footnote : footnotes) { htmlTextBuilder.append("\n").append(footnote.attr("title")); } String encodedHtml = REMOVE_HTML_TAGS.matcher(htmlTextBuilder.toString()).replaceAll(""); return encodedHtml; } }
ArabicUtilities { @NonNull public static String cleanHtml(String htmlText) { Document doc = Jsoup.parse(htmlText); Elements footnotes = doc.select("a[title].comment"); StringBuilder htmlTextBuilder = new StringBuilder(htmlText); for (Element footnote : footnotes) { htmlTextBuilder.append("\n").append(footnote.attr("title")); } String encodedHtml = REMOVE_HTML_TAGS.matcher(htmlTextBuilder.toString()).replaceAll(""); return encodedHtml; } }
ArabicUtilities { @NonNull public static String cleanHtml(String htmlText) { Document doc = Jsoup.parse(htmlText); Elements footnotes = doc.select("a[title].comment"); StringBuilder htmlTextBuilder = new StringBuilder(htmlText); for (Element footnote : footnotes) { htmlTextBuilder.append("\n").append(footnote.attr("title")); } String encodedHtml = REMOVE_HTML_TAGS.matcher(htmlTextBuilder.toString()).replaceAll(""); return encodedHtml; } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); }
ArabicUtilities { @NonNull public static String cleanHtml(String htmlText) { Document doc = Jsoup.parse(htmlText); Elements footnotes = doc.select("a[title].comment"); StringBuilder htmlTextBuilder = new StringBuilder(htmlText); for (Element footnote : footnotes) { htmlTextBuilder.append("\n").append(footnote.attr("title")); } String encodedHtml = REMOVE_HTML_TAGS.matcher(htmlTextBuilder.toString()).replaceAll(""); return encodedHtml; } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }
@Test public void cleanTashkeel() throws Exception { String testStringWithTashkeel = "فَكَمْ نَدْ رَأَيْنَا مِنْ رِجَالٍ وَدَوْلَةٍ ... فَبَادُوا جَمِيعًا مُسْرِعِينَ وَزَالُوا"; String testStringWithTashkeel2 = "خِلَافٌ يَصِحُّ تَخْرِيجُهُ عَلَى هَذِهِ الْقَاعِدَةِ لِأَنَّ قَوْلَهُ حَرَامٌ مُطْلَقٌ دَالٌّ عَلَى مُطْلَقِ التَّحْرِيمِ الدَّائِرِ بَيْنَ الرُّتَبِ الْمُخْتَلِفَةِ فَأَمْكَنَ حَمْلُهُ عَلَى أَعْلَاهَا أَوْ عَلَى أَدْنَاهَا وَيَلْحَقُ بِمَسْأَلَةِ الْحَرَامِ مَا مَعَهَا فِي مَذْهَبِ مَالِكٍ مِنْ الْأَلْفَاظِ نَحْوُ أَلْبَتَّةَ وَالْبَائِنِ وَحَبْلُك عَلَى غَارِبِك هَلْ يُحْمَلُ عَلَى أَعْلَى الرُّتَبِ وَهُوَ الثَّلَاثُ أَمْ لَا وَمِنْهَا مَسْأَلَةُ التَّيَمُّمِ فِي قَوْله تَعَالَى {فَتَيَمَّمُوا صَعِيدًا} [النساء: 43] فَقَوْلُهُ صَعِيدًا مَدْلُولُهُ أَمْرٌ كُلِّيٌّ يُمْكِنُ حَمْلُهُ عَلَى أَدْنَى الرُّتَبِ وَهُوَ مُطْلَقُ مَا يُسَمَّى صَعِيدًا تُرَابًا كَانَ أَوْ غَيْرَهُ مِنْ جِنْسِ الْأَرْضِ وَهُوَ مَذْهَبُ مَالِكٍ - رَحِمَهُ اللَّهُ - أَوْ أَعْلَى رُتَبِ الصَّعِيدِ وَهُوَ التُّرَابُ وَهُوَ مَذْهَبُ الشَّافِعِيِّ فَهَذِهِ الْمَسْأَلَةُ أَيْضًا حَسَنَةُ التَّخْرِيجِ عَلَى هَذِهِ الْقَاعِدَةِ مِنْ غَيْرِ مُعَارِضٍ مِنْ جِهَةِ اللَّفْظِ وَلَا الْمَعْنَى. " + "وَمِنْهَا قَوْلُهُ - عَلَيْهِ السَّلَامُ - «إذَا سَمِعْتُمْ الْمُؤَذِّنَ يُؤَذِّنُ فَقُولُوا مِثْلَ مَا يَقُولُ» وَالْمِثْلِيَّةُ فِي لِسَانِ الْعَرَبِ تَصْدُقُ بَيْنَ الشَّيْئَيْنِ بِأَيِّ وَصْفٍ كَانَ مِنْ غَيْرِ شُمُولٍ فَإِذَا قُلْت: زَيْدٌ مِثْلُ الْأَسَدِ كَفَى فِي ذَلِكَ الشُّجَاعَةُ دُونَ بَقِيَّةِ الْأَوْصَافِ وَكَذَلِكَ زَيْدٌ مِثْلُ عَمْرٍو يَصْدُقُ ذَلِكَ حَقِيقَةً بِمُشَارَكَتِهِمَا فِي صِفَةٍ وَاحِدَةٍ فَالْمِثْلُ الْمَذْكُورُ فِي الْأَذَانِ إنْ حُمِلَ عَلَى أَعْلَى الرُّتَبِ قَالَ: مِثْلَ مَا يَقُولُ إلَى آخِرِ الْأَذَانِ أَوْ عَلَى أَدْنَى الرُّتَبِ فَفِي التَّشَهُّدِ خَاصَّةً وَهُوَ مَشْهُورُ مَذْهَبِ مَالِكٍ فَهَذِهِ سِتُّ مَسَائِلَ تُنَبِّهُك عَلَى صِحَّةِ التَّخْرِيجِ عَلَى هَذِهِ الْقَاعِدَةِ وَالْمَسَائِلُ السَّابِقَةُ تُنَبِّهُك عَلَى التَّخْرِيجِ الْفَاسِدِ عَلَيْهَا لِأَنَّ الْأَوَّلَ مِنْ بَابِ الْأَجْزَاءِ وَهَذِهِ مِنْ بَابِ الْجُزْئِيَّاتِ فَقَدْ ظَهَرَ لَك الْفَرْقُ بَيْنَهُمَا وَالصَّحِيحُ مِنْ الْفَاسِدِ."; String testStringWithoutTashkeel = "فكم ند رأينا من رجال ودولة ... فبادوا جميعا مسرعين وزالوا"; String testStringWithoutTashkeel2 = "خلاف يصح تخريجه على هذه القاعدة لأن قوله حرام مطلق دال على مطلق التحريم الدائر بين الرتب المختلفة فأمكن حمله على أعلاها أو على أدناها ويلحق بمسألة الحرام ما معها في مذهب مالك من الألفاظ نحو ألبتة والبائن وحبلك على غاربك هل يحمل على أعلى الرتب وهو الثلاث أم لا ومنها مسألة التيمم في قوله تعالى {فتيمموا صعيدا} [النساء: 43] فقوله صعيدا مدلوله أمر كلي يمكن حمله على أدنى الرتب وهو مطلق ما يسمى صعيدا ترابا كان أو غيره من جنس الأرض وهو مذهب مالك - رحمه الله - أو أعلى رتب الصعيد وهو التراب وهو مذهب الشافعي فهذه المسألة أيضا حسنة التخريج على هذه القاعدة من غير معارض من جهة اللفظ ولا المعنى. " + "ومنها قوله - عليه السلام - «إذا سمعتم المؤذن يؤذن فقولوا مثل ما يقول» والمثلية في لسان العرب تصدق بين الشيئين بأي وصف كان من غير شمول فإذا قلت: زيد مثل الأسد كفى في ذلك الشجاعة دون بقية الأوصاف وكذلك زيد مثل عمرو يصدق ذلك حقيقة بمشاركتهما في صفة واحدة فالمثل المذكور في الأذان إن حمل على أعلى الرتب قال: مثل ما يقول إلى آخر الأذان أو على أدنى الرتب ففي التشهد خاصة وهو مشهور مذهب مالك فهذه ست مسائل تنبهك على صحة التخريج على هذه القاعدة والمسائل السابقة تنبهك على التخريج الفاسد عليها لأن الأول من باب الأجزاء وهذه من باب الجزئيات فقد ظهر لك الفرق بينهما والصحيح من الفاسد."; assertEquals(testStringWithoutTashkeel, ArabicUtilities.cleanTashkeel(testStringWithTashkeel)); assertEquals(testStringWithoutTashkeel2, ArabicUtilities.cleanTashkeel(testStringWithTashkeel2)); }
public static String cleanTashkeel(@NonNull String s) { Matcher matcher = CLEANING_TASHKEEL.matcher(s); return matcher.replaceAll(""); }
ArabicUtilities { public static String cleanTashkeel(@NonNull String s) { Matcher matcher = CLEANING_TASHKEEL.matcher(s); return matcher.replaceAll(""); } }
ArabicUtilities { public static String cleanTashkeel(@NonNull String s) { Matcher matcher = CLEANING_TASHKEEL.matcher(s); return matcher.replaceAll(""); } }
ArabicUtilities { public static String cleanTashkeel(@NonNull String s) { Matcher matcher = CLEANING_TASHKEEL.matcher(s); return matcher.replaceAll(""); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); }
ArabicUtilities { public static String cleanTashkeel(@NonNull String s) { Matcher matcher = CLEANING_TASHKEEL.matcher(s); return matcher.replaceAll(""); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }
@Test public void cleanTextForSearchingWthStingBuilder() throws Exception { }
@NonNull public static String cleanTextForSearchingWthStingBuilder(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if ((c < HAMZAH || c > YEH) & !Character.isSpace(c)) { sb.deleteCharAt(i); i--; } else if (Character.isSpace(c)) { sb.setCharAt(i, ' '); } else { switch (c) { case ALEF_MADDA: case ALEF_HAMZA_ABOVE: case ALEF_HAMZA_BELOW: sb.setCharAt(i, ALEF); break; case DOTLESS_YEH: sb.setCharAt(i, YEH); break; case TEH_MARBUTA: sb.setCharAt(i, HEH); break; default: break; } } } return sb.toString(); }
ArabicUtilities { @NonNull public static String cleanTextForSearchingWthStingBuilder(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if ((c < HAMZAH || c > YEH) & !Character.isSpace(c)) { sb.deleteCharAt(i); i--; } else if (Character.isSpace(c)) { sb.setCharAt(i, ' '); } else { switch (c) { case ALEF_MADDA: case ALEF_HAMZA_ABOVE: case ALEF_HAMZA_BELOW: sb.setCharAt(i, ALEF); break; case DOTLESS_YEH: sb.setCharAt(i, YEH); break; case TEH_MARBUTA: sb.setCharAt(i, HEH); break; default: break; } } } return sb.toString(); } }
ArabicUtilities { @NonNull public static String cleanTextForSearchingWthStingBuilder(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if ((c < HAMZAH || c > YEH) & !Character.isSpace(c)) { sb.deleteCharAt(i); i--; } else if (Character.isSpace(c)) { sb.setCharAt(i, ' '); } else { switch (c) { case ALEF_MADDA: case ALEF_HAMZA_ABOVE: case ALEF_HAMZA_BELOW: sb.setCharAt(i, ALEF); break; case DOTLESS_YEH: sb.setCharAt(i, YEH); break; case TEH_MARBUTA: sb.setCharAt(i, HEH); break; default: break; } } } return sb.toString(); } }
ArabicUtilities { @NonNull public static String cleanTextForSearchingWthStingBuilder(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if ((c < HAMZAH || c > YEH) & !Character.isSpace(c)) { sb.deleteCharAt(i); i--; } else if (Character.isSpace(c)) { sb.setCharAt(i, ' '); } else { switch (c) { case ALEF_MADDA: case ALEF_HAMZA_ABOVE: case ALEF_HAMZA_BELOW: sb.setCharAt(i, ALEF); break; case DOTLESS_YEH: sb.setCharAt(i, YEH); break; case TEH_MARBUTA: sb.setCharAt(i, HEH); break; default: break; } } } return sb.toString(); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); }
ArabicUtilities { @NonNull public static String cleanTextForSearchingWthStingBuilder(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if ((c < HAMZAH || c > YEH) & !Character.isSpace(c)) { sb.deleteCharAt(i); i--; } else if (Character.isSpace(c)) { sb.setCharAt(i, ' '); } else { switch (c) { case ALEF_MADDA: case ALEF_HAMZA_ABOVE: case ALEF_HAMZA_BELOW: sb.setCharAt(i, ALEF); break; case DOTLESS_YEH: sb.setCharAt(i, YEH); break; case TEH_MARBUTA: sb.setCharAt(i, HEH); break; default: break; } } } return sb.toString(); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }
@Test public void startsWithDefiniteArticle() throws Exception { assertEquals(ArabicUtilities.startsWithDefiniteArticle("البخاري"), true); assertEquals(ArabicUtilities.startsWithDefiniteArticle("اللبن"), true); assertEquals(ArabicUtilities.startsWithDefiniteArticle("اللحم"), true); }
public static boolean startsWithDefiniteArticle(@NonNull String string) { return string.startsWith("ال"); }
ArabicUtilities { public static boolean startsWithDefiniteArticle(@NonNull String string) { return string.startsWith("ال"); } }
ArabicUtilities { public static boolean startsWithDefiniteArticle(@NonNull String string) { return string.startsWith("ال"); } }
ArabicUtilities { public static boolean startsWithDefiniteArticle(@NonNull String string) { return string.startsWith("ال"); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); }
ArabicUtilities { public static boolean startsWithDefiniteArticle(@NonNull String string) { return string.startsWith("ال"); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }
@Test public void testFromFile() throws IOException { ConfigHelper helper = ConfigHelper.fromFile("src/test/resources/base-config.properties"); Assert.assertEquals("Base Property 1", helper.getRaw("prop1")); Assert.assertEquals("Base Property 2", helper.getRaw("prop2")); }
public static ConfigHelper fromFile(String file) throws IOException { return new ConfigHelper(file); }
ConfigHelper { public static ConfigHelper fromFile(String file) throws IOException { return new ConfigHelper(file); } }
ConfigHelper { public static ConfigHelper fromFile(String file) throws IOException { return new ConfigHelper(file); } ConfigHelper(); ConfigHelper(Properties properties); @Inject ConfigHelper(List<ConfigHelper> configuration); private ConfigHelper(String configFilename); private ConfigHelper(File configFile); private ConfigHelper(InputStream input, String resourceName); }
ConfigHelper { public static ConfigHelper fromFile(String file) throws IOException { return new ConfigHelper(file); } ConfigHelper(); ConfigHelper(Properties properties); @Inject ConfigHelper(List<ConfigHelper> configuration); private ConfigHelper(String configFilename); private ConfigHelper(File configFile); private ConfigHelper(InputStream input, String resourceName); static ConfigHelper fromClasspathResource(String resourceName); static ConfigHelper fromSystemProperty(String property); static ConfigHelper fromFile(String file); static ConfigHelper fromFile(File file); static ConfigHelper fromStream(InputStream input); void add(String propertyName, MappedConfiguration<String, Object> configuration); void add(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void addIfExists(String propertyName, MappedConfiguration<String, Object> configuration); void addIfExists(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void override(String propertyName, MappedConfiguration<String, Object> configuration); void override(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void overrideIfExists(String propertyName, MappedConfiguration<String, Object> configuration); void overrideIfExists(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); Set<String> getPropertyNames(); Set<String> getReferenced(); Class<?> getPropertyType(String propertyName); String getRaw(String propertyName); void copyFrom(ConfigHelper source); }
ConfigHelper { public static ConfigHelper fromFile(String file) throws IOException { return new ConfigHelper(file); } ConfigHelper(); ConfigHelper(Properties properties); @Inject ConfigHelper(List<ConfigHelper> configuration); private ConfigHelper(String configFilename); private ConfigHelper(File configFile); private ConfigHelper(InputStream input, String resourceName); static ConfigHelper fromClasspathResource(String resourceName); static ConfigHelper fromSystemProperty(String property); static ConfigHelper fromFile(String file); static ConfigHelper fromFile(File file); static ConfigHelper fromStream(InputStream input); void add(String propertyName, MappedConfiguration<String, Object> configuration); void add(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void addIfExists(String propertyName, MappedConfiguration<String, Object> configuration); void addIfExists(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void override(String propertyName, MappedConfiguration<String, Object> configuration); void override(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void overrideIfExists(String propertyName, MappedConfiguration<String, Object> configuration); void overrideIfExists(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); Set<String> getPropertyNames(); Set<String> getReferenced(); Class<?> getPropertyType(String propertyName); String getRaw(String propertyName); void copyFrom(ConfigHelper source); static final String EXTEND; static final String PREFIX; }
@Test public void shouldSkipValidationOfUnreferencedProperties() { Properties properties = new Properties(); properties.put("property", "false"); ConfigHelper configHelper = new ConfigHelper(properties); PropertyTypeValidator validator = new PropertyTypeValidator(null, null); validator.validate(configHelper); }
@Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); @Override void validate(ConfigHelper configHelper); }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); @Override void validate(ConfigHelper configHelper); }
@Test public void shouldSkipValidationOfPropertiesWithDefaultType() { Properties properties = new Properties(); properties.put("property", "false"); MappedConfiguration<String, Object> configuration = Mockito.mock(MappedConfiguration.class); ConfigHelper configHelper = new ConfigHelper(properties); configHelper.add("property", configuration); Mockito.inOrder(configuration) .verify(configuration, Mockito.calls(1)) .add("property", "false"); PropertyTypeValidator validator = new PropertyTypeValidator(null, null); validator.validate(configHelper); }
@Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); @Override void validate(ConfigHelper configHelper); }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); @Override void validate(ConfigHelper configHelper); }
@Test public void shouldUseTypeCoercerWithValueFromSymbolSourceToValidatePropertyType() { Properties properties = new Properties(); properties.put("property", "${symbol}"); MappedConfiguration<String, Object> configuration = Mockito.mock(MappedConfiguration.class); TypeCoercer typeCoercer = Mockito.mock(TypeCoercer.class); SymbolSource symbolSource = Mockito.mock(SymbolSource.class); Mockito.when(symbolSource.expandSymbols("${symbol}")).thenReturn("true"); ConfigHelper configHelper = new ConfigHelper(properties); configHelper.add(Boolean.class, "property", configuration); Mockito.inOrder(configuration) .verify(configuration, Mockito.calls(1)) .add("property", "${symbol}"); PropertyTypeValidator validator = new PropertyTypeValidator(typeCoercer, symbolSource); validator.validate(configHelper); Mockito.inOrder(typeCoercer) .verify(typeCoercer, Mockito.calls(1)) .coerce("true", Boolean.class); }
@Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); @Override void validate(ConfigHelper configHelper); }
PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); @Override void validate(ConfigHelper configHelper); }
@Test public void testGetClassNameForTable() throws Exception { Assert.assertEquals("ManagedSuperClassJoined", provider.getClassNameForTable(getTable("MANAGEDSUPERCLASSJOINED"))); Assert.assertEquals("SubEntityJoined1", provider.getClassNameForTable(getTable("SUB_ENTITY_JOINED_1"))); Assert.assertEquals("SubEntityJoined2", provider.getClassNameForTable(getTable("SUBENTITY_JOINED_2"))); Assert.assertEquals("ManagedSuperClassSingleTable", provider.getClassNameForTable(getTable("MANAGED_SUPERCLASS_SINGLE_TABLE"))); Assert.assertEquals("SubEntityTablePerClass1", provider.getClassNameForTable(getTable("SUBENTITYTABLEPERCLASS1"))); Assert.assertEquals("SubEntityTablePerClass2", provider.getClassNameForTable(getTable("SUBENTITY_TABLE_PER_CLASS_2"))); }
@Override public String getClassNameForTable(Table table) { ManagedType managedType = managedTypesByTableName.get(table.getName().toUpperCase()); return managedType != null ? managedType.getJavaType().getSimpleName() : fallbackNameProvider.getClassNameForTable(table); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getClassNameForTable(Table table) { ManagedType managedType = managedTypesByTableName.get(table.getName().toUpperCase()); return managedType != null ? managedType.getJavaType().getSimpleName() : fallbackNameProvider.getClassNameForTable(table); } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getClassNameForTable(Table table) { ManagedType managedType = managedTypesByTableName.get(table.getName().toUpperCase()); return managedType != null ? managedType.getJavaType().getSimpleName() : fallbackNameProvider.getClassNameForTable(table); } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getClassNameForTable(Table table) { ManagedType managedType = managedTypesByTableName.get(table.getName().toUpperCase()); return managedType != null ? managedType.getJavaType().getSimpleName() : fallbackNameProvider.getClassNameForTable(table); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getClassNameForTable(Table table) { ManagedType managedType = managedTypesByTableName.get(table.getName().toUpperCase()); return managedType != null ? managedType.getJavaType().getSimpleName() : fallbackNameProvider.getClassNameForTable(table); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void testBuilder_ClassPrivate() { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Could not instantiate RedG instance"); AbstractRedG redG = new RedGBuilder<>(PrivateRedG.class).build(); }
public T build() { final T inst = instance; instance = null; return inst; }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); }
@Test public void testBuilder_DefaultConstructor() throws Exception { try { AbstractRedG redG = new RedGBuilder<>().build(); } catch (RuntimeException e) { assertEquals("Could not load default RedG class", e.getMessage()); } final ClassLoader classLoader = this.getClass().getClassLoader(); final Method defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); defineClassMethod.setAccessible(true); byte[] classDef = java.util.Base64.getDecoder().decode(this.redGClassData); defineClassMethod.invoke(classLoader, "com.btc.redg.generated.RedG", classDef, 0, classDef.length); try { AbstractRedG redG = new RedGBuilder<>().build(); } catch (RuntimeException e) { assertEquals("Could not instantiate RedG instance", e.getMessage()); } }
public T build() { final T inst = instance; instance = null; return inst; }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); }
@Test public void testGetDummy_reuseCachedObject() throws Exception { AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); TestRedGEntity1 entity1 = factory.getDummy(redG, TestRedGEntity1.class); assertNotNull(entity1); TestRedGEntity1 entity2 = factory.getDummy(redG, TestRedGEntity1.class); assertNotNull(entity1); assertEquals(entity1, entity2); }
@Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
@Test public void testGetDummy_transitiveDependencies() throws Exception { AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); TestRedGEntity2 entity2 = factory.getDummy(redG, TestRedGEntity2.class); assertNotNull(entity2); assertTrue(redG.findSingleEntity(TestRedGEntity1.class, e -> true) != null); assertTrue(redG.findSingleEntity(TestRedGEntity2.class, e -> true) != null); }
@Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
@Test public void testGetDummy_NoFittingConstructor() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Could not find a fitting constructor"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity4.class); }
@Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
@Test public void testGetDummy_NoFittingConstructor2() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Could not find a fitting constructor"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity6.class); }
@Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
@Test public void testGetDummy_NoFittingConstructor3() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Could not find a fitting constructor"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity7.class); }
@Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
@Test public void testGetDummy_InstantiationFails() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Instantiation of the dummy failed"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity5.class); }
@Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }
@Test public void testInsertDataIntoDatabase() throws Exception { Connection connection = getConnection("-idid"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); List<MockEntity1> gObjects = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity1()).collect(Collectors.toList()); RedGDatabaseUtil.insertDataIntoDatabase(gObjects, connection); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM TEST"); rs.next(); assertEquals(20, rs.getInt(1)); }
public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
@Test public void testInsertDataIntoDatabase2() throws Exception { Connection connection = getConnection("-idid2"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); List<MockEntity3> gObjects = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity3()).collect(Collectors.toList()); RedGDatabaseUtil.insertDataIntoDatabase(gObjects, connection); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM TEST"); rs.next(); assertEquals(20, rs.getInt(1)); }
public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
@Test public void testGetDataTypeByName() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setTableTypeMappings(Arrays.asList( new TableTypeMapping(".+", Collections.singletonList(new ColumnTypeMapping("ACTIVE", "java.lang.Boolean"))), new TableTypeMapping("JOIN_TABLE", Collections.singletonList(new ColumnTypeMapping(".*_ID", "java.math.BigDecimal"))) )); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals(dataTypeProvider.getDataTypeByName("FOO", "ACTIVE"), "java.lang.Boolean"); Assert.assertEquals(dataTypeProvider.getDataTypeByName("BAR", "ACTIVE"), "java.lang.Boolean"); Assert.assertEquals(dataTypeProvider.getDataTypeByName("BAR", "INACTIVE"), null); Assert.assertEquals(dataTypeProvider.getDataTypeByName("JOIN_TABLE", "FOO_ID"), "java.math.BigDecimal"); Assert.assertEquals(dataTypeProvider.getDataTypeByName("JOIN_TABLE", "BAR"), null); }
String getDataTypeByName(String tableName, String columnName) { if (typeMappings.getTableTypeMappings() == null) { return null; } return typeMappings.getTableTypeMappings().stream() .filter(tableTypeMapping -> tableName.matches(tableTypeMapping.getTableName())) .flatMap(tableTypeMapping -> tableTypeMapping.getColumnTypeMappings().stream()) .filter(columnTypeMapping -> columnName.matches(columnTypeMapping.getColumnName())) .findFirst() .map(ColumnTypeMapping::getJavaType) .orElse(null); }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeByName(String tableName, String columnName) { if (typeMappings.getTableTypeMappings() == null) { return null; } return typeMappings.getTableTypeMappings().stream() .filter(tableTypeMapping -> tableName.matches(tableTypeMapping.getTableName())) .flatMap(tableTypeMapping -> tableTypeMapping.getColumnTypeMappings().stream()) .filter(columnTypeMapping -> columnName.matches(columnTypeMapping.getColumnName())) .findFirst() .map(ColumnTypeMapping::getJavaType) .orElse(null); } }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeByName(String tableName, String columnName) { if (typeMappings.getTableTypeMappings() == null) { return null; } return typeMappings.getTableTypeMappings().stream() .filter(tableTypeMapping -> tableName.matches(tableTypeMapping.getTableName())) .flatMap(tableTypeMapping -> tableTypeMapping.getColumnTypeMappings().stream()) .filter(columnTypeMapping -> columnName.matches(columnTypeMapping.getColumnName())) .findFirst() .map(ColumnTypeMapping::getJavaType) .orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeByName(String tableName, String columnName) { if (typeMappings.getTableTypeMappings() == null) { return null; } return typeMappings.getTableTypeMappings().stream() .filter(tableTypeMapping -> tableName.matches(tableTypeMapping.getTableName())) .flatMap(tableTypeMapping -> tableTypeMapping.getColumnTypeMappings().stream()) .filter(columnTypeMapping -> columnName.matches(columnTypeMapping.getColumnName())) .findFirst() .map(ColumnTypeMapping::getJavaType) .orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeByName(String tableName, String columnName) { if (typeMappings.getTableTypeMappings() == null) { return null; } return typeMappings.getTableTypeMappings().stream() .filter(tableTypeMapping -> tableName.matches(tableTypeMapping.getTableName())) .flatMap(tableTypeMapping -> tableTypeMapping.getColumnTypeMappings().stream()) .filter(columnTypeMapping -> columnName.matches(columnTypeMapping.getColumnName())) .findFirst() .map(ColumnTypeMapping::getJavaType) .orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
@Test public void testInsertDataIntoDatabase3() throws Exception { Connection connection = getConnection("-idid3"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); List<MockEntity4> gObjects = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity4()).collect(Collectors.toList()); RedGDatabaseUtil.insertDataIntoDatabase(gObjects, connection); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM TEST"); rs.next(); assertEquals(40, rs.getInt(1)); }
public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
@Test public void testInsertExistingDataIntoDatabase() throws Exception { Connection connection = getConnection("-iedid"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); stmt.execute("INSERT INTO TEST VALUES ('obj1')"); RedGDatabaseUtil.insertDataIntoDatabase(Collections.singletonList(new ExistingMockEntity1()), connection); }
public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
@Test public void testInsertExistingDataIntoDatabase_NotExisting() throws Exception { this.thrown.expect(ExistingEntryMissingException.class); Connection connection = getConnection("-iedidm"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); RedGDatabaseUtil.insertDataIntoDatabase(Collections.singletonList(new ExistingMockEntity1()), connection); }
public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }
@Test public void entitiesAreSortedByDepths() throws Exception { EntitySorter entitySorter = new EntitySorter(); Entity leafEntity1 = new Entity("leafEntity1"); Entity leafEntity2 = new Entity("leafEntity2"); Entity leafEntity3 = new Entity("leafEntity3"); Entity nonLeaf1 = new Entity("nonLeaf1", leafEntity1, leafEntity2); Entity nonLeaf2 = new Entity("nonLeaf2", leafEntity1, leafEntity3); Entity nonLeaf3 = new Entity("nonLeaf3", nonLeaf1); Entity superDependentNode = new Entity("superDependentNode", leafEntity1, nonLeaf1, nonLeaf3); List<RedGEntity> sortedEntities = entitySorter.sortEntities(Arrays.asList( superDependentNode, nonLeaf3, nonLeaf2, nonLeaf1, leafEntity1, leafEntity2, leafEntity3 )); Assert.assertEquals(Arrays.asList( leafEntity1, leafEntity2, leafEntity3, nonLeaf2, nonLeaf1, nonLeaf3, superDependentNode ), sortedEntities); }
public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } static List<RedGEntity> sortEntities(List<RedGEntity> entities); }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } static List<RedGEntity> sortEntities(List<RedGEntity> entities); }
@Test public void entitiesSelfReferenceTest() throws Exception { Entity root = new Entity("root"); root.addDependency(root); Entity leaf = new Entity("leaf", root); Entity leafWithSelf = new Entity("leafWithSelf", root, leaf); leafWithSelf.addDependency(leafWithSelf); List<RedGEntity> sorted = EntitySorter.sortEntities(Arrays.asList( leaf, leafWithSelf, root)); Assert.assertEquals(Arrays.asList( root, leaf, leafWithSelf ), sorted); }
public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } static List<RedGEntity> sortEntities(List<RedGEntity> entities); }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } static List<RedGEntity> sortEntities(List<RedGEntity> entities); }
@Test public void existingEntitiesFirst() throws Exception { EntitySorter entitySorter = new EntitySorter(); Entity existingEntity1 = new ExistingEntity("existingEntity1"); Entity leafEntity1 = new Entity("leafEntity1"); Entity existingEntity2 = new ExistingEntity("existingEntity2"); Entity leafEntity2 = new Entity("leafEntity2"); leafEntity2.setDependencies(null); Entity existingEntity3 = new ExistingEntity("existingEntity3"); Entity nonLeaf1 = new Entity("nonLeaf1", leafEntity1, leafEntity2); Entity existingEntity4 = new ExistingEntity("existingEntity4"); List<RedGEntity> sortedEntities = entitySorter.sortEntities(Arrays.asList( existingEntity1, nonLeaf1, existingEntity2, leafEntity1, existingEntity3, leafEntity2, existingEntity4 )); Assert.assertEquals(Arrays.asList( existingEntity1, existingEntity2, existingEntity3, existingEntity4, leafEntity1, leafEntity2, nonLeaf1 ), sortedEntities); }
public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } static List<RedGEntity> sortEntities(List<RedGEntity> entities); }
EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } static List<RedGEntity> sortEntities(List<RedGEntity> entities); }
@Test public void testGetFullSqlName() throws Exception { final TableModel tm1 = new TableModel(); tm1.setSqlFullName("TEST.TABLE"); assertThat(wrapGetFullTableName(new DataExtractor(), tm1)).isEqualTo("TEST.TABLE"); final TableModel tm2 = new TableModel(); tm2.setSqlFullName("TEST.\"TABLE\""); assertThat(wrapGetFullTableName(new DataExtractor(), tm2)).isEqualTo("TEST.\"TABLE\""); final TableModel tm3 = new TableModel(); tm3.setSqlFullName("\"TEST\".TABLE"); assertThat(wrapGetFullTableName(new DataExtractor(), tm3)).isEqualTo("\"TEST\".TABLE"); final TableModel tm4 = new TableModel(); tm4.setSqlFullName("TEST.TABLE"); final DataExtractor de1 = new DataExtractor(); de1.setSqlSchemaName("TEST2"); assertThat(wrapGetFullTableName(de1, tm4)).isEqualTo("TEST2.TABLE"); final TableModel tm5 = new TableModel(); tm5.setSqlFullName("TEST.TABLE"); final DataExtractor de2 = new DataExtractor(); de2.setSqlSchemaName("TEST2."); assertThat(wrapGetFullTableName(de2, tm5)).isEqualTo("TEST2.TABLE"); final TableModel tm6 = new TableModel(); tm6.setSqlFullName("TEST.\"TABLE\""); final DataExtractor de3 = new DataExtractor(); de3.setSqlSchemaName("TEST2"); assertThat(wrapGetFullTableName(de3, tm6)).isEqualTo("TEST2.\"TABLE\""); final TableModel tm7 = new TableModel(); tm7.setSqlFullName("TEST.\"TABLE\""); final DataExtractor de4 = new DataExtractor(); de4.setSqlSchemaName("TEST2."); assertThat(wrapGetFullTableName(de4, tm7)).isEqualTo("TEST2.\"TABLE\""); }
public void setSqlSchemaName(String sqlSchemaName) { this.sqlSchemaName = sqlSchemaName; }
DataExtractor { public void setSqlSchemaName(String sqlSchemaName) { this.sqlSchemaName = sqlSchemaName; } }
DataExtractor { public void setSqlSchemaName(String sqlSchemaName) { this.sqlSchemaName = sqlSchemaName; } }
DataExtractor { public void setSqlSchemaName(String sqlSchemaName) { this.sqlSchemaName = sqlSchemaName; } JavaCodeRepresentationProvider getJcrProvider(); void setJcrProvider(final JavaCodeRepresentationProvider jcrProvider); Function<EntityModel, EntityInclusionMode> getEntityModeDecider(); void setEntityModeDecider(final Function<EntityModel, EntityInclusionMode> entityModeDecider); void setSqlSchemaName(String sqlSchemaName); List<EntityModel> extractAllData(final DataSource dataSource, final List<TableModel> tableModels); List<EntityModel> extractAllData(final Connection connection, final List<TableModel> tableModels); }
DataExtractor { public void setSqlSchemaName(String sqlSchemaName) { this.sqlSchemaName = sqlSchemaName; } JavaCodeRepresentationProvider getJcrProvider(); void setJcrProvider(final JavaCodeRepresentationProvider jcrProvider); Function<EntityModel, EntityInclusionMode> getEntityModeDecider(); void setEntityModeDecider(final Function<EntityModel, EntityInclusionMode> entityModeDecider); void setSqlSchemaName(String sqlSchemaName); List<EntityModel> extractAllData(final DataSource dataSource, final List<TableModel> tableModels); List<EntityModel> extractAllData(final Connection connection, final List<TableModel> tableModels); }
@Test @Ignore public void extractTableModelsFromSourceCode() throws Exception { TableModelExtractor.extractTableModelsFromSourceCode(Paths.get("D:\\redg\\redg-playground\\target\\generated-test-sources\\redg"), "com.btc.redg.generated", "G"); }
public static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException { LOG.debug("Starting table model extraction from source code..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = srcDir.resolve(packageNameAsFolders); LOG.debug("Folder with source files is {}", codeFilePath.toAbsolutePath().toString()); final List<Path> paths = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.java")) .collect(Collectors.toList()); LOG.debug("Found following java source files:\n{}", paths.stream().map(p -> p.toAbsolutePath().toString()).collect(Collectors.joining("\n"))); for (Path p : paths) { LOG.debug("Loading source file {}", p.toAbsolutePath().toString()); final String code = new String(Files.readAllBytes(p)); final Matcher m = tableModelPattern.matcher(code); if (m.find()) { LOG.debug("Found serialized table model inside of file. Extracting..."); final String encodedModel = m.group(1); final byte[] decodedModel = Base64.getDecoder().decode(encodedModel); final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decodedModel)); results.add((TableModel) ois.readObject()); LOG.debug("Table model successfully extracted and deserialized."); } } return results; }
TableModelExtractor { public static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException { LOG.debug("Starting table model extraction from source code..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = srcDir.resolve(packageNameAsFolders); LOG.debug("Folder with source files is {}", codeFilePath.toAbsolutePath().toString()); final List<Path> paths = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.java")) .collect(Collectors.toList()); LOG.debug("Found following java source files:\n{}", paths.stream().map(p -> p.toAbsolutePath().toString()).collect(Collectors.joining("\n"))); for (Path p : paths) { LOG.debug("Loading source file {}", p.toAbsolutePath().toString()); final String code = new String(Files.readAllBytes(p)); final Matcher m = tableModelPattern.matcher(code); if (m.find()) { LOG.debug("Found serialized table model inside of file. Extracting..."); final String encodedModel = m.group(1); final byte[] decodedModel = Base64.getDecoder().decode(encodedModel); final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decodedModel)); results.add((TableModel) ois.readObject()); LOG.debug("Table model successfully extracted and deserialized."); } } return results; } }
TableModelExtractor { public static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException { LOG.debug("Starting table model extraction from source code..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = srcDir.resolve(packageNameAsFolders); LOG.debug("Folder with source files is {}", codeFilePath.toAbsolutePath().toString()); final List<Path> paths = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.java")) .collect(Collectors.toList()); LOG.debug("Found following java source files:\n{}", paths.stream().map(p -> p.toAbsolutePath().toString()).collect(Collectors.joining("\n"))); for (Path p : paths) { LOG.debug("Loading source file {}", p.toAbsolutePath().toString()); final String code = new String(Files.readAllBytes(p)); final Matcher m = tableModelPattern.matcher(code); if (m.find()) { LOG.debug("Found serialized table model inside of file. Extracting..."); final String encodedModel = m.group(1); final byte[] decodedModel = Base64.getDecoder().decode(encodedModel); final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decodedModel)); results.add((TableModel) ois.readObject()); LOG.debug("Table model successfully extracted and deserialized."); } } return results; } }
TableModelExtractor { public static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException { LOG.debug("Starting table model extraction from source code..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = srcDir.resolve(packageNameAsFolders); LOG.debug("Folder with source files is {}", codeFilePath.toAbsolutePath().toString()); final List<Path> paths = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.java")) .collect(Collectors.toList()); LOG.debug("Found following java source files:\n{}", paths.stream().map(p -> p.toAbsolutePath().toString()).collect(Collectors.joining("\n"))); for (Path p : paths) { LOG.debug("Loading source file {}", p.toAbsolutePath().toString()); final String code = new String(Files.readAllBytes(p)); final Matcher m = tableModelPattern.matcher(code); if (m.find()) { LOG.debug("Found serialized table model inside of file. Extracting..."); final String encodedModel = m.group(1); final byte[] decodedModel = Base64.getDecoder().decode(encodedModel); final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decodedModel)); results.add((TableModel) ois.readObject()); LOG.debug("Table model successfully extracted and deserialized."); } } return results; } static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix); static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix); }
TableModelExtractor { public static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException { LOG.debug("Starting table model extraction from source code..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = srcDir.resolve(packageNameAsFolders); LOG.debug("Folder with source files is {}", codeFilePath.toAbsolutePath().toString()); final List<Path> paths = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.java")) .collect(Collectors.toList()); LOG.debug("Found following java source files:\n{}", paths.stream().map(p -> p.toAbsolutePath().toString()).collect(Collectors.joining("\n"))); for (Path p : paths) { LOG.debug("Loading source file {}", p.toAbsolutePath().toString()); final String code = new String(Files.readAllBytes(p)); final Matcher m = tableModelPattern.matcher(code); if (m.find()) { LOG.debug("Found serialized table model inside of file. Extracting..."); final String encodedModel = m.group(1); final byte[] decodedModel = Base64.getDecoder().decode(encodedModel); final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decodedModel)); results.add((TableModel) ois.readObject()); LOG.debug("Table model successfully extracted and deserialized."); } } return results; } static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix); static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix); }