@Override public org.jsonschema2pojo.rules.Rule<JPackage, JType> getObjectRule() { final org.jsonschema2pojo.rules.Rule<JPackage, JType> workingRule = super.getObjectRule(); return new org.jsonschema2pojo.rules.Rule<JPackage, JType>() { @Override public JType apply(String nodeName, JsonNode node, JPackage generatableType, Schema currentSchema) { JType objectType = workingRule.apply(nodeName, node, generatableType, currentSchema); if( objectType instanceof JDefinedClass ) { JDefinedClass jclass = (JDefinedClass)objectType; jclass.method(JMod.PUBLIC, jclass.owner().BOOLEAN, "brokenMethod").body(); } return objectType; } }; }
@Override public OutputStream openBinary(final JPackage pkg, String fileName) throws IOException { final ByteArrayOutputStream javaSourceStream = new ByteArrayOutputStream(); final String scalaFileName = fileName.replaceAll("\\.java$", ".scala"); return new FilterOutputStream(javaSourceStream) { @Override public void close() throws IOException { super.close(); final String javaSource = new String(javaSourceStream.toByteArray(), "utf-8"); final String scalaSource = Converter.instance210().convert(javaSource, new ConversionSettings(false)); OutputStream parentStream = ScalaZipCodeWriter.super.openBinary(pkg, scalaFileName); parentStream.write(scalaSource.getBytes("utf-8")); } }; }
@Override public Writer openSource(JPackage pkg, String fileName) throws IOException { final Writer bw = new OutputStreamWriter(openBinary(pkg, fileName), encoding); return new UnicodeEscapeWriter(bw) { private final CharsetEncoder encoder = Charset.forName(encoding).newEncoder(); @Override protected boolean requireEscaping(int ch) { // control characters if (ch < 0x20 && " \t\r\n".indexOf(ch) == -1) { return true; } // ASCII chars if (ch < 0x80) { return false; } return !encoder.canEncode((char) ch); } }; }
@Override public OutputStream openBinary(final JPackage pkg, String fileName) throws IOException { final ByteArrayOutputStream javaSourceStream = new ByteArrayOutputStream(); final String scalaFileName = fileName.replaceAll("\\.java$", ".scala"); return new FilterOutputStream(javaSourceStream) { @Override public void close() throws IOException { super.close(); final String javaSource = new String(javaSourceStream.toByteArray(), "utf-8"); final String scalaSource = Converter.instance210().convert(javaSource, new ConversionSettings(false)); OutputStream parentStream = ScalaSingleStreamCodeWriter.super.openBinary(pkg, scalaFileName); parentStream.write(scalaSource.getBytes("utf-8")); } }; }
public OutputStream openBinary(JPackage pkg, String fileName) throws IOException { final ByteArrayOutputStream javaSourceStream = new ByteArrayOutputStream(); final String javaFileName = getFile(pkg, fileName).getAbsolutePath(); final String scalaFileName = javaFileName.replaceAll("\\.java$", ".scala"); return new FilterOutputStream(javaSourceStream) { public void close() throws IOException { super.close(); final String javaSource = new String(javaSourceStream.toByteArray(), encoding); final String scalaSource = Converter.instance210().convert(javaSource, new ConversionSettings(false)); FileUtils.writeStringToFile(new File(scalaFileName), scalaSource, encoding); } }; }
@Test public void applyGeneratesDate() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "string"); TextNode formatNode = TextNode.valueOf("date-time"); objectNode.set("format", formatNode); JType mockDateType = mock(JType.class); FormatRule mockFormatRule = mock(FormatRule.class); when(mockFormatRule.apply(eq("fooBar"), eq(formatNode), Mockito.isA(JType.class), isNull(Schema.class))).thenReturn(mockDateType); when(ruleFactory.getFormatRule()).thenReturn(mockFormatRule); JType result = rule.apply("fooBar", objectNode, jpackage, null); assertThat(result, equalTo(mockDateType)); }
@Test public void applyGeneratesArray() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "array"); JClass mockArrayType = mock(JClass.class); ArrayRule mockArrayRule = mock(ArrayRule.class); when(mockArrayRule.apply("fooBar", objectNode, jpackage, null)).thenReturn(mockArrayType); when(ruleFactory.getArrayRule()).thenReturn(mockArrayRule); JType result = rule.apply("fooBar", objectNode, jpackage, null); assertThat(result, is((JType) mockArrayType)); }
@Test public void applyGeneratesCustomObject() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "object"); JDefinedClass mockObjectType = mock(JDefinedClass.class); ObjectRule mockObjectRule = mock(ObjectRule.class); when(mockObjectRule.apply("fooBar", objectNode, jpackage, null)).thenReturn(mockObjectType); when(ruleFactory.getObjectRule()).thenReturn(mockObjectRule); JType result = rule.apply("fooBar", objectNode, jpackage, null); assertThat(result, is((JType) mockObjectType)); }
@Test public void arrayWithUniqueItemsProducesSet() { JCodeModel codeModel = new JCodeModel(); JPackage jpackage = codeModel._package(getClass().getPackage().getName()); ObjectMapper mapper = new ObjectMapper(); ObjectNode itemsNode = mapper.createObjectNode(); itemsNode.put("type", "integer"); ObjectNode propertyNode = mapper.createObjectNode(); propertyNode.set("uniqueItems", BooleanNode.TRUE); propertyNode.set("items", itemsNode); JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, mock(Schema.class)); assertThat(propertyType, notNullValue()); assertThat(propertyType.erasure(), is(codeModel.ref(Set.class))); assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Integer.class.getName())); }
@Test public void arrayWithNonUniqueItemsProducesList() { JCodeModel codeModel = new JCodeModel(); JPackage jpackage = codeModel._package(getClass().getPackage().getName()); ObjectMapper mapper = new ObjectMapper(); ObjectNode itemsNode = mapper.createObjectNode(); itemsNode.put("type", "number"); ObjectNode propertyNode = mapper.createObjectNode(); propertyNode.set("uniqueItems", BooleanNode.FALSE); propertyNode.set("items", itemsNode); Schema schema = mock(Schema.class); when(schema.getId()).thenReturn(URI.create("http://example/nonUniqueArray")); when(config.isUseDoubleNumbers()).thenReturn(true); JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, schema); assertThat(propertyType, notNullValue()); assertThat(propertyType.erasure(), is(codeModel.ref(List.class))); assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Double.class.getName())); }
@Test public void arrayOfPrimitivesProducesCollectionOfWrapperTypes() { JCodeModel codeModel = new JCodeModel(); JPackage jpackage = codeModel._package(getClass().getPackage().getName()); ObjectMapper mapper = new ObjectMapper(); ObjectNode itemsNode = mapper.createObjectNode(); itemsNode.put("type", "number"); ObjectNode propertyNode = mapper.createObjectNode(); propertyNode.set("uniqueItems", BooleanNode.FALSE); propertyNode.set("items", itemsNode); Schema schema = mock(Schema.class); when(schema.getId()).thenReturn(URI.create("http://example/nonUniqueArray")); when(config.isUsePrimitives()).thenReturn(true); when(config.isUseDoubleNumbers()).thenReturn(true); JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, schema); assertThat(propertyType, notNullValue()); assertThat(propertyType.erasure(), is(codeModel.ref(List.class))); assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Double.class.getName())); }
@Test public void arrayDefaultsToNonUnique() { JCodeModel codeModel = new JCodeModel(); JPackage jpackage = codeModel._package(getClass().getPackage().getName()); ObjectMapper mapper = new ObjectMapper(); ObjectNode itemsNode = mapper.createObjectNode(); itemsNode.put("type", "boolean"); ObjectNode propertyNode = mapper.createObjectNode(); propertyNode.set("uniqueItems", BooleanNode.FALSE); propertyNode.set("items", itemsNode); Schema schema = mock(Schema.class); when(schema.getId()).thenReturn(URI.create("http://example/defaultArray")); JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, schema); assertThat(propertyType.erasure(), is(codeModel.ref(List.class))); }
@RequestMapping(value = "/generator/preview", method = RequestMethod.POST) public String preview(@RequestParam(value = "schema") String schema, @RequestParam(value = "targetpackage") String targetpackage, @RequestParam(value = "sourcetype", required = false) final String sourcetype, @RequestParam(value = "annotationstyle", required = false) final String annotationstyle, @RequestParam(value = "usedoublenumbers", required = false) final boolean usedoublenumbers, @RequestParam(value = "includeaccessors", required = false) final boolean includeaccessors, @RequestParam(value = "includeadditionalproperties", required = false) final boolean includeadditionalproperties, @RequestParam(value = "propertyworddelimiters", required = false) final String propertyworddelimiters, @RequestParam(value = "classname") String classname) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JCodeModel codegenModel = getCodegenModel(schema, targetpackage, sourcetype, annotationstyle, usedoublenumbers, includeaccessors, includeadditionalproperties, propertyworddelimiters, classname); codegenModel.build(new CodeWriter() { @Override public OutputStream openBinary(JPackage pkg, String fileName) throws IOException { return byteArrayOutputStream; } @Override public void close() throws IOException { byteArrayOutputStream.close(); } }); return byteArrayOutputStream.toString("utf-8"); }
/** * <p>createResourceInterface.</p> * * @param name a {@link java.lang.String} object. * @return a {@link com.sun.codemodel.JDefinedClass} object. * @throws java.lang.Exception if any. */ public JDefinedClass createResourceInterface(final String name) throws Exception { String actualName; int i = -1; while (true) { actualName = name + (++i == 0 ? "" : Integer.toString(i)); if (!resourcesMethods.containsKey(actualName)) { resourcesMethods.put(actualName, new HashSet<String>()); break; } } final JPackage pkg = codeModel._package(configuration.getBasePackageName() + "." +configuration.getRestIFPackageName()); return pkg._interface(actualName); }
@SuppressWarnings("unchecked") private static JAnnotationUse getOrAddXmlSchemaAnnotation(JPackage p, JClass xmlSchemaClass) { JAnnotationUse xmlAnn = null; final List<JAnnotationUse> annotations = getAnnotations(p); if (annotations != null) { for (JAnnotationUse annotation : annotations) { final JClass clazz = getAnnotationJClass(annotation); if (clazz == xmlSchemaClass) { xmlAnn = annotation; break; } } } if (xmlAnn == null) { // XmlSchema annotation not found, let's add one xmlAnn = p.annotate(xmlSchemaClass); } return xmlAnn; }
@Test public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithoutInheritance() throws Exception { final String simpleClassName = "EntityClass"; final String nodeLabel = "ENTITY_CLASS"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.annotate(Table.class).param("name", nodeLabel); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel), Arrays.asList(entityClass)); assertThat(clazz, equalTo(entityClass)); }
@Test public void testGetNamesOfIdPropertiesFromASingleClassHavingAFieldAnnotatedWithId() throws Exception { // GIVEN final String simpleClassName = "EntityClass"; final String idPropertyName = "key"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.field(JMod.PRIVATE, String.class, idPropertyName).annotate(Id.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); // WHEN final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass); // THEN assertThat(namesOfIdProperties.size(), equalTo(1)); assertThat(namesOfIdProperties, hasItem(idPropertyName)); }
@Test public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithId() throws Exception { // GIVEN final String simpleClassName = "EntityClass"; final String idPropertyName = "key"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); // WHEN final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass); // THEN assertThat(namesOfIdProperties.size(), equalTo(1)); assertThat(namesOfIdProperties, hasItem(idPropertyName)); }
@BeforeClass public static void generateTestModel() throws Exception { final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "A"); jClass.annotate(Entity.class); jClass.field(JMod.PRIVATE, Long.class, "id").annotate(Id.class); jClass.field(JMod.PRIVATE, String.class, "value"); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); entityAClass = loadClass(testFolder.getRoot(), jClass.name()); }
@Test public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@BeforeClass public static void generateModel() throws Exception { final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); JAnnotationUse jAnnotationUse = jClass.annotate(InitialDataSets.class); jAnnotationUse.param("value", "Script.file"); jClass.annotate(Cleanup.class); final JFieldVar jField = jClass.field(JMod.PRIVATE, String.class, "testField"); jField.annotate(PersistenceContext.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jAnnotationUse = jMethod.annotate(InitialDataSets.class); jAnnotationUse.param("value", "InitialDataSets.file"); jAnnotationUse = jMethod.annotate(ApplyScriptsAfter.class); jAnnotationUse.param("value", "ApplyScriptsAfter.file"); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); cut = loadClass(testFolder.getRoot(), jClass.name()); }
/** * @throws IllegalStateException if a packageRule or classRule is missing or if the ApiControllerMetadata * requires a missing methodSignatureRule. */ @Override public JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel codeModel) { if(packageRule == null || classRule == null) { throw new IllegalStateException("A packageRule and classRule are mandatory."); } if(!metadata.getApiCalls().isEmpty() && methodSignatureRule == null) { throw new IllegalStateException("Since there are API Calls in the metadata at least a methodSignatureRule is mandatory"); } JPackage jPackage = packageRule.apply(metadata, codeModel); JDefinedClass jClass = classRule.apply(metadata, jPackage); implementsExtendsRule.ifPresent(rule -> rule.apply(metadata, jClass)); classCommentRule.ifPresent(rule-> rule.apply(metadata, jClass)); classAnnotationRules.forEach(rule -> rule.apply(metadata, jClass)); fieldDeclerationRules.forEach(rule -> rule.apply(metadata, jClass)); metadata.getApiCalls().forEach( apiMappingMetadata -> { JMethod jMethod = methodSignatureRule.apply(apiMappingMetadata, jClass); methodCommentRule.ifPresent(rule-> rule.apply(apiMappingMetadata, jMethod)); methodAnnotationRules.forEach(rule -> rule.apply(apiMappingMetadata, jMethod)); methodBodyRule.ifPresent( rule -> rule.apply(apiMappingMetadata, CodeModelHelper.ext(jMethod, jClass.owner()))); }); return jClass; }
@Test public void applySpringMethodBodyRule_shouldCreate_valid_body() throws JClassAlreadyExistsException { SpringRestClientMethodBodyRule rule = new SpringRestClientMethodBodyRule("restTemplate", "baseUrl"); JPackage jPackage = jCodeModel.rootPackage(); JDefinedClass jClass = jPackage._class(JMod.PUBLIC, "MyClass"); JMethod jMethod = jClass.method(JMod.PUBLIC, Object.class, "getBase"); jMethod.param(jCodeModel._ref(String.class), "id"); rule.apply(getEndpointMetadata(2), CodeModelHelper.ext(jMethod, jCodeModel)); String serializeModel = serializeModel(); //ensure that we are adding the ACCEPT headers assertThat(serializeModel, containsString("httpHeaders.setAccept(acceptsList);")); //ensure that we are concatinating the base URL with the request URI to form the full url assertThat(serializeModel, containsString("String url = baseUrl.concat(\"/base/{id}\"")); //ensure that we are setting url paths vars in the uri assertThat(serializeModel, containsString("uriComponents = uriComponents.expand(uriParamMap)")); //ensure that the exchange invocation is as expected assertThat(serializeModel, containsString("return this.restTemplate.exchange(uriComponents.encode().toUri(), HttpMethod.GET, httpEntity, NamedResponseType.class);")); }
private MContainer getContainer(CClassInfoParent parent) { return parent.accept(new Visitor<MContainer>() { public MContainer onBean(CClassInfo bean) { return getTypeInfo(bean); } public MContainer onPackage(JPackage pkg) { return getPackage(pkg); } public MContainer onElement(CElementInfo element) { return getElementInfo(element); } }); }
private MPackageInfo getPackage(CClassInfoParent parent) { return parent.accept(new Visitor<MPackageInfo>() { public MPackageInfo onBean(CClassInfo bean) { return getPackage(bean.parent()); } public MPackageInfo onPackage(JPackage pkg) { return getPackage(pkg); } public MPackageInfo onElement(CElementInfo element) { return getPackage(element.parent); } }); }
/** * Returns a property file (created if necessary). * * @param thePackage * package to create property file * @param name * property file name. * @return Property file. */ public static JPropertyFile getOrCreatePropertyFile(JPackage thePackage, String name) { JPropertyFile propertyFile = null; for (Iterator<JResourceFile> iterator = thePackage.propertyFiles(); iterator .hasNext() && (null == propertyFile);) { final JResourceFile resourceFile = (JResourceFile) iterator.next(); if (resourceFile instanceof JPropertyFile && name.equals(resourceFile.name())) { propertyFile = (JPropertyFile) resourceFile; } } if (null == propertyFile) { propertyFile = new JPropertyFile(name); thePackage.addResourceFile(propertyFile); } return propertyFile; }
public static JDefinedClass _getClass(JCodeModel codeModel, String fullyQualifiedName) { final int idx = fullyQualifiedName.lastIndexOf('.'); if (idx < 0) { return codeModel.rootPackage()._getClass(fullyQualifiedName); } else { final String packageName = fullyQualifiedName.substring(0, idx); for (Iterator<JPackage> iterator = codeModel.packages(); iterator .hasNext();) { final JPackage _package = iterator.next(); if (packageName.equals(_package.name())) { return _getClass(_package, fullyQualifiedName.substring(idx + 1)); } } return null; } }
public static JDefinedClass _getClass(JPackage _package, String name) { final int idx = name.lastIndexOf('$'); if (idx < 0) { return _package._getClass(name); } else { final String parentClassName = name.substring(0, idx); final JDefinedClass parentClass = _package ._getClass(parentClassName); if (parentClass == null) { return null; } else { return _getClass(parentClass, name.substring(idx + 1)); } } }
public void testAnnotationImplements() throws Exception{ JCodeModel jmod = new JCodeModel(); // adding a test package JPackage pack = jmod._package("testAnnotationImplements"); // building an interface JDefinedClass interface1 = pack._interface("Interface1"); // adding annotations JDefinedClass annotation1 = pack._annotationTypeDeclaration("Annot1"); try{ //this is perfectly legal in CodeModel: annotation1._implements(interface1); fail("No Exception was thrown for Illegal behavior"); } catch ( IllegalArgumentException ie){ } jmod.build(new SingleStreamCodeWriter(System.out)); }
/** * Validates that all JDefinedClass instances in the code model have been properly * registered. See {@link #registerGeneratedClass}. */ protected void validateDefinedClassRegistration() { JCodeModel model = getCodeModel(); for(Iterator<JPackage> packageIterator = model.packages(); packageIterator.hasNext(); ) { JPackage p = packageIterator.next(); for(Iterator<JDefinedClass> classIterator = p.classes(); classIterator.hasNext(); ) { JDefinedClass clazz = classIterator.next(); if (_classToDataSchemaLocationMap.containsKey(clazz) == false) { throw new IllegalStateException("Attempting to generate unregistered class: '" + clazz.fullName() + "'"); } } } }
private JDefinedClass generateDerivedBuilder(JClass baseBuilderClass, JClass valueClass, String finderName, String derivedBuilderName, JPackage clientPackage) throws JClassAlreadyExistsException { JDefinedClass derivedBuilderClass = clientPackage._class(JMod.PUBLIC, derivedBuilderName); annotate(derivedBuilderClass, null); derivedBuilderClass._extends(baseBuilderClass.narrow(derivedBuilderClass)); JMethod derivedBuilderConstructor = derivedBuilderClass.constructor(JMod.PUBLIC); JVar uriParam = derivedBuilderConstructor.param(_stringClass, "baseUriTemplate"); JVar resourceSpecParam = derivedBuilderConstructor.param(_resourceSpecClass, "resourceSpec"); JVar requestOptionsParam = derivedBuilderConstructor.param(Rest4JRequestOptions.class, "requestOptions"); derivedBuilderConstructor.body().invoke(SUPER).arg(uriParam).arg(valueClass.dotclass()).arg(resourceSpecParam).arg(requestOptionsParam); if (finderName != null) { derivedBuilderConstructor.body().add(JExpr._super().invoke("name").arg(finderName)); } return derivedBuilderClass; }
@Override public void writeProgram(Module<NType, NClass> module, JSProgram program, Output output) { try { final JPackage _package = codeModel._package(output .getOutputPackageName()); _package.addResourceFile(createTextFile(output.getFileName(), program)); } catch (IOException ioex) { try { errorHandler.error(new SAXParseException(MessageFormat.format( "Could not create the code for the module [{0}].", module.getName()), null, ioex)); } catch (SAXException ignored) { } } }
@Override public void writeJsonStructure(Module<NType, NClass> module, JsonStructure structure, String fileName) { try { final JPackage _package = codeModel._package(""); _package.addResourceFile(createTextFile(fileName, structure)); } catch (IOException ioex) { try { errorHandler.error(new SAXParseException(MessageFormat.format( "Could not create the code for the module [{0}].", module.getName()), null, ioex)); } catch (SAXException ignored) { } } }
public Writer openSource(JPackage pkg, String fileName) throws IOException { Writer w = super.openSource(pkg,fileName); PrintWriter out = new PrintWriter(w); // write prolog if this is a java source file if( prolog != null ) { out.println( "//" ); String s = prolog; int idx; while( (idx=s.indexOf('\n'))!=-1 ) { out.println("// "+ s.substring(0,idx) ); s = s.substring(idx+1); } out.println("//"); out.println(); } out.flush(); // we can't close the stream for that would close the undelying stream. return w; }
protected File getFile(JPackage pkg, String fileName ) throws IOException { File dir; if(pkg.isUnnamed()) dir = target; else dir = new File(target, toDirName(pkg)); if(!dir.exists()) dir.mkdirs(); File fn = new File(dir,fileName); if (fn.exists()) { if (!fn.delete()) throw new IOException(fn + ": Can't delete previous version"); } if(readOnly) readonlyFiles.add(fn); return fn; }
private void outputSchema(JPackage avroPackage, List<NamedAvroType> types) { // set up the correct format for leading zeros (ensures proper order in filesystem) StringBuilder digits = new StringBuilder(); for (int i=0; i < Integer.toString(types.size()).length(); ++i) { digits.append("0"); } DecimalFormat format = new java.text.DecimalFormat(digits.toString()); AtomicInteger counter = new AtomicInteger(1); for (NamedAvroType type : types) { String id = format.format(counter.getAndIncrement()); JTextFile avroSchema = new JTextFile("avroSchema-"+ id +"_"+ type.name +".txt"); avroSchema.setContents(getJson(type)); avroPackage.addResourceFile(avroSchema); } }
private AvroType avroFromProperty(CPropertyInfo info, NType type, JPackage _package, boolean unionNull) { AvroType returnType = avroFromType(type, _package); String defaultValue = extractDefaultValue(info.getSchemaComponent()); if (!isPropertyRequired(info) && unionNull) { if (returnType instanceof AvroUnion) { throw new SchemagenException("nested unions are not allowed"); } returnType = new AvroUnion(AvroPrimitive.PrimitiveType.NULL.newInstance(), returnType); if (defaultValue == null) { defaultValue = AvroPrimitive.PrimitiveType.NULL.defaultValue; } } if (defaultValue != null) { returnType.setDefaultValue(defaultValue); } return returnType; }
@Test public void applyGeneratesDate() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "string"); TextNode formatNode = TextNode.valueOf("date-time"); objectNode.put("format", formatNode); JType mockDateType = mock(JType.class); FormatRule mockFormatRule = mock(FormatRule.class); when(mockFormatRule.apply(eq("fooBar"), eq(formatNode), Mockito.isA(JType.class), isNull(Schema.class))).thenReturn(mockDateType); when(ruleFactory.getFormatRule()).thenReturn(mockFormatRule); JType result = rule.apply("fooBar", objectNode, jpackage, null); assertThat(result, equalTo(mockDateType)); }