private JType unboxIfNecessary(JType type, GenerationConfig config) { if (config.isUsePrimitives()) { return type.unboxify(); } else { return type; } }
/** * Returns the JType for an integer field. Handles type lookup and unboxing. */ private JType getIntegerType(JCodeModel owner, JsonNode node, GenerationConfig config) { if (config.isUseBigIntegers()) { return unboxIfNecessary(owner.ref(BigInteger.class), config); } else if (config.isUseLongIntegers() || node.has("minimum") && node.get("minimum").isLong() || node.has("maximum") && node.get("maximum").isLong()) { return unboxIfNecessary(owner.ref(Long.class), config); } else { return unboxIfNecessary(owner.ref(Integer.class), config); } }
/** * Returns the JType for a number field. Handles type lookup and unboxing. */ private JType getNumberType(JCodeModel owner, GenerationConfig config) { if (config.isUseBigDecimals()) { return unboxIfNecessary(owner.ref(BigDecimal.class), config); } else if (config.isUseDoubleNumbers()) { return unboxIfNecessary(owner.ref(Double.class), config); } else { return unboxIfNecessary(owner.ref(Float.class), config); } }
private void setupRuleFactoryToIncludeJsr303() { GenerationConfig config = mock(GenerationConfig.class); when(config.getPropertyWordDelimiters()).thenReturn(new char[] { '-', ' ', '_' }); RuleFactory ruleFactory = new RuleFactory(); ruleFactory.setGenerationConfig(config); rule = new RequiredArrayRule(ruleFactory); when(config.isIncludeJsr303Annotations()).thenReturn(true); }
/** * <p>Constructor for Context.</p> * * @param configuration a {@link org.raml.jaxrs.codegen.core.Configuration} object. * @param raml a {@link org.aml.apimodel.Api} object. * @throws java.io.IOException if any. */ public Context(final Configuration configuration, final Api raml) throws IOException { Validate.notNull(configuration, "configuration can't be null"); Validate.notNull(raml, "raml can't be null"); this.configuration = configuration; writer=new JavaWriter(); codeModel = writer.getModel(); writer.getConfig().setJacksonSupport(true); writer.getConfig().setJaxbSupport(true); writer.setDefaultPackageName(configuration.getBasePackageName()+"."+configuration.getModelPackageName()); resourcesMethods = new HashMap<String, Set<String>>(); // prime the HTTP method annotation cache httpMethodAnnotations = new HashMap<String, Object>(); for (final Class<? extends Annotation> clazz : JAXRS_HTTP_METHODS) { httpMethodAnnotations.put(clazz.getSimpleName(), clazz); } // configure the JSON -> POJO generator final GenerationConfig jsonSchemaGenerationConfig = configuration.createJsonSchemaGenerationConfig(); // schemaMapper = new SchemaMapper(new RuleFactory(jsonSchemaGenerationConfig, getAnnotator(jsonSchemaGenerationConfig), // new SchemaStore()), new SchemaGenerator()); }
/** * * @param config * @return */ private static Annotator getAnnotator(GenerationConfig config) { Annotator coreAnnotator = new AnnotatorFactory().getAnnotator(config.getAnnotationStyle()); if(config.getCustomAnnotator() != null){ Annotator customAnnotator = new AnnotatorFactory().getAnnotator(config.getCustomAnnotator()); return new CompositeAnnotator(coreAnnotator, customAnnotator); } return coreAnnotator; }
private JType getIntegerType(JCodeModel owner, GenerationConfig config) { if (config.isUseLongIntegers()) { return owner.ref(Long.class); } else { return owner.ref(Integer.class); } }
private JType getNumberType(JCodeModel owner, GenerationConfig config) { if (config.isUseDoubleNumbers()) { return owner.ref(Double.class); } else { return owner.ref(Float.class); } }
private void generateModelSources(JCodeModel codeModel, ApiBodyMetadata body, File rootDir, GenerationConfig config, Annotator annotator) { boolean build = false; if (codeModel == null) { this.getLog().info("Generating Model object for: " + body.getName()); build = true; if (config == null && annotator == null) { codeModel = body.getCodeModel(); } else { codeModel = body.getCodeModel(resolvedSchemaLocation, basePackage + NamingHelper.getDefaultModelPackage(), config, annotator); } } if (build && codeModel != null) { buildCodeModelToDisk(codeModel, body.getName(), rootDir); } }
/** * Applies a JSONSchema2Pojo config to this config * * @param generationConfig the config from which values will be pulled */ public void apply(GenerationConfig generationConfig) { this .withLongIntegers(generationConfig.isUseLongIntegers()) .withCommonsLang3(generationConfig.isUseCommonsLang3()) .withBigDecimals(generationConfig.isUseBigDecimals()) .withBigIntegers(generationConfig.isUseBigIntegers()) .withJSR303Annotations(generationConfig.isIncludeJsr303Annotations()) .withHashcodeEqualsToString((generationConfig.isIncludeHashcodeAndEquals() && generationConfig.isIncludeToString())) .withGenerateBuilderMethods(generationConfig.isGenerateBuilders()); }
public static boolean canUseJava7(GenerationConfig config) { return !LESS_THAN_7.contains(config.getTargetVersion()); }
public static boolean canUseJava8(GenerationConfig config) { return !LESS_THAN_8.contains(config.getTargetVersion()); }
public NameHelper(GenerationConfig generationConfig) { this.generationConfig = generationConfig; }
public static void main(String[] args) throws IOException { // BEGIN EXAMPLE JCodeModel codeModel = new JCodeModel(); URL source = new URL("file:///path/to/my/schema.json"); GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { // set config option by overriding method return true; } }; SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator()); mapper.generate(codeModel, "ClassName", "com.example", source); codeModel.build(new File("output")); // END EXAMPLE }
@Test public void existingTypeIsUsedWhenTypeIsAlreadyGenerated() throws URISyntaxException { JType previouslyGeneratedType = mock(JType.class); URI schemaUri = getClass().getResource("/schema/address.json").toURI(); SchemaStore schemaStore = new SchemaStore(); Schema schema = schemaStore.create(schemaUri, "#/."); schema.setJavaType(previouslyGeneratedType); final GenerationConfig mockGenerationConfig = mock(GenerationConfig.class); when(mockGenerationConfig.getRefFragmentPathDelimiters()).thenReturn("#/."); when(mockRuleFactory.getSchemaStore()).thenReturn(schemaStore); when(mockRuleFactory.getGenerationConfig()).thenReturn(mockGenerationConfig); ObjectNode schemaNode = new ObjectMapper().createObjectNode(); schemaNode.put("$ref", schemaUri.toString()); JType result = rule.apply(NODE_NAME, schemaNode, null, schema); assertThat(result, is(sameInstance(previouslyGeneratedType))); }
public static GenerationConfig mockConfig(String version) { GenerationConfig config = mock(GenerationConfig.class); when(config.getTargetVersion()).thenReturn(version); return config; }
public void createModel(File jsonFile, String modelName) throws IOException { //CapFirst for java classes modelName = modelName.substring(0, 1).toUpperCase() + modelName.substring(1); System.out.println("Model name :"+modelName); JCodeModel codeModel = new JCodeModel(); GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isIncludeConstructors() { return true; } @Override public boolean isUseDoubleNumbers() { return true; } @Override public boolean isUsePrimitives() { return true; } @Override public boolean isIncludeToString() { return false; } @Override public boolean isIncludeHashcodeAndEquals() { return false; } @Override public boolean isIncludeAdditionalProperties() { return false; } @Override public Class<? extends RuleFactory> getCustomRuleFactory() { return APXCustomRuleFactory.class; } }; SchemaMapper mapper = new SchemaMapper(new APXCustomRuleFactory(config, new ORMLiteAnotator(), new SchemaStore()), new SchemaGenerator()); JType m = mapper.generate(codeModel, modelName, PACKAGE_NAME + ".models", jsonFile.toURI().toURL()); File f = new File(PROJECT_SRC); codeModel.build(f); System.out.print("Model created at :"); System.out.println(m.fullName().replace('.', File.separatorChar) + ".java"); }
public APXCustomRuleFactory(GenerationConfig generationConfig, Annotator annotator, SchemaStore schemaStore) { super(generationConfig, annotator, schemaStore); }
/** * Generates classes based on json/jsonschema. * * @return class name * @throws IOException */ public String generate() throws IOException { String schemaPath = this.config.getJsonSchemaPath(); if (schemas.containsKey(schemaPath)){ LOG.info("Schema already exists " + schemaPath); return schemas.get(schemaPath); } JCodeModel codeModel = new JCodeModel(); URL source = new File(config.getInputPath()).toURI().toURL(); GenerationConfig generationConfig = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { // set config option by overriding metho return true; } @Override public SourceType getSourceType() { if (JsonPath.from(source).get("$schema") != null) { return SourceType.JSONSCHEMA; } return SourceType.JSON; } @Override public boolean isUseLongIntegers() { return true; } @Override public boolean isUseCommonsLang3() { return true; } }; SchemaMapper mapper = new SchemaMapper( new RuleFactory(generationConfig, new GsonAnnotator(), new SchemaStore()), new SchemaGenerator()); mapper.generate(codeModel, getClassName(), config.getPackageName(), source); codeModel.build(new File(config.getOutputPath())); schemas.put(schemaPath, getClassName()); return getClassName(); }
/** * Returns a generation config with the supplied parameters. If any of these parameters are * supplied null, it will * use the value defined in the default configuration * * @param generateBuilders * Enables or disables {@link GenerationConfig#isGenerateBuilders()} * @param includeAdditionalProperties * Enables or disables {@link GenerationConfig#isIncludeAdditionalProperties()} * @param includeDynamicAccessors * Enables or disables {@link GenerationConfig#isIncludeDynamicAccessors()} * @param useLongIntegers * Enables or disables {@link GenerationConfig#isUseLongIntegers()} * @return The GenerationConfig */ public static GenerationConfig getGenerationConfig(Boolean generateBuilders, Boolean includeAdditionalProperties, Boolean includeDynamicAccessors, Boolean useLongIntegers) { return new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { // set config option by overriding method if (generateBuilders != null) { return generateBuilders; } else { return true; } } @Override public boolean isIncludeAdditionalProperties() { if (includeAdditionalProperties != null) { return includeAdditionalProperties; } else { return false; } } @Override public boolean isIncludeDynamicAccessors() { if (includeDynamicAccessors != null) { return includeDynamicAccessors; } else { return false; } } @Override public boolean isUseLongIntegers() { if (useLongIntegers != null) { return useLongIntegers; } else { return super.isUseLongIntegers(); } } }; }
/** * Create a new rule factory with the given generation config options. * * @param generationConfig * The generation config options for type generation. These * config options will influence the java code generated by rules * created by this factory. * @param annotator * the annotator used to mark up Java types with any annotations * that are required to build JSON compatible types * @param schemaStore * the object used by this factory to get and store schemas */ public RuleFactory(GenerationConfig generationConfig, Annotator annotator, SchemaStore schemaStore) { this.generationConfig = generationConfig; this.annotator = annotator; this.schemaStore = schemaStore; this.nameHelper = new NameHelper(generationConfig); }
@Test public void generationConfigIsReturned() { GenerationConfig mockGenerationConfig = mock(GenerationConfig.class); RuleFactory ruleFactory = new RuleFactory(mockGenerationConfig, new NoopAnnotator(), new SchemaStore()); assertThat(ruleFactory.getGenerationConfig(), is(sameInstance(mockGenerationConfig))); }
@Test public void refsToOtherSchemasAreLoaded() throws URISyntaxException, JClassAlreadyExistsException { URI schemaUri = getClass().getResource("/schema/address.json").toURI(); ObjectNode schemaWithRef = new ObjectMapper().createObjectNode(); schemaWithRef.put("$ref", schemaUri.toString()); JDefinedClass jclass = new JCodeModel()._class(TARGET_CLASS_NAME); final GenerationConfig mockGenerationConfig = mock(GenerationConfig.class); when(mockGenerationConfig.getRefFragmentPathDelimiters()).thenReturn("#/."); TypeRule mockTypeRule = mock(TypeRule.class); when(mockRuleFactory.getTypeRule()).thenReturn(mockTypeRule); when(mockRuleFactory.getSchemaStore()).thenReturn(new SchemaStore()); when(mockRuleFactory.getGenerationConfig()).thenReturn(mockGenerationConfig); ArgumentCaptor<JsonNode> captureJsonNode = ArgumentCaptor.forClass(JsonNode.class); ArgumentCaptor<Schema> captureSchema = ArgumentCaptor.forClass(Schema.class); rule.apply(NODE_NAME, schemaWithRef, jclass, null); verify(mockTypeRule).apply(eq(NODE_NAME), captureJsonNode.capture(), eq(jclass.getPackage()), captureSchema.capture()); assertThat(captureSchema.getValue().getId(), is(equalTo(schemaUri))); assertThat(captureSchema.getValue().getContent(), is(equalTo(captureJsonNode.getValue()))); assertThat(captureJsonNode.getValue().get("description").asText(), is(equalTo("An Address following the convention of http://microformats.org/wiki/hcard"))); }
/** * Builds a JCodeModel for this body * * @param basePackage The package we will be using for the domain objects * @param schemaLocation The location of this schema, will be used to create absolute URIs for $ref tags eg "classpath:/" * @param config JsonSchema2Pojo configuration. if null a default config will be used * @param annotator JsonSchema2Pojo annotator. if null a default annotator will be used * @return built JCodeModel */ public JCodeModel getCodeModel(String basePackage, String schemaLocation, GenerationConfig config, Annotator annotator) { if (type != null) { return codeModel; } else { return SchemaHelper.buildBodyJCodeModel(schemaLocation, basePackage, name, schema, config, annotator); } }
/** * Gets the configuration options that will influence the java code * generated by rules created by this factory. * * @return A configuration object containing all configuration property * values. */ public GenerationConfig getGenerationConfig() { return generationConfig; }
/** * The generation config options for type generation. These config options * will influence the java code generated by rules created by this factory. * * @param generationConfig * Generation config */ public void setGenerationConfig(final GenerationConfig generationConfig) { this.generationConfig = generationConfig; this.nameHelper = new NameHelper(generationConfig); }
/** * Returns a configuration for the JSON Schema 2 POJO that is in line with the defaults used in * the plugin so far * * @return Default Generation Config */ public static GenerationConfig getDefaultGenerationConfig() { return getGenerationConfig(true, false, false, false); }