com.sun.codemodel.JCodeModel Java Examples
The following examples show how to use
com.sun.codemodel.JCodeModel.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GenericJavaClassRule.java From springmvc-raml-plugin with Apache License 2.0 | 6 votes |
/** * @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; }
Example #2
Source File: JavaCodeBuilder.java From aem-component-generator with Apache License 2.0 | 6 votes |
protected JavaCodeBuilder(JCodeModel codeModel, GenerationConfig generationConfig) { this.codeModel = codeModel; this.generationConfig = generationConfig; Set<Property> occurredProperties = new HashSet<>(); this.globalProperties = filterProperties(occurredProperties, CommonUtils.getSortedPropertiesBasedOnTabs(generationConfig.getOptions().getGlobalProperties(), generationConfig.getOptions().getGlobalTabProperties())); occurredProperties.addAll(this.globalProperties); this.sharedProperties = filterProperties(occurredProperties, CommonUtils.getSortedPropertiesBasedOnTabs(generationConfig.getOptions().getSharedProperties(), generationConfig.getOptions().getSharedTabProperties())); occurredProperties.addAll(this.sharedProperties); this.privateProperties = filterProperties(occurredProperties, CommonUtils.getSortedPropertiesBasedOnTabs(generationConfig.getOptions().getProperties(), generationConfig.getOptions().getTabProperties())); occurredProperties.addAll(this.privateProperties); }
Example #3
Source File: RunPluginsForCases.java From jaxb2-basics with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void compilesSchema() throws Exception { new File("target/generated-sources/xjc").mkdirs(); URL schema = getClass().getResource("/cases.xsd"); // URL binding = getClass().getResource("/cases.xjb"); final String[] arguments = new String[] { "-xmlschema", schema.toExternalForm(), // "-b", binding.toExternalForm(), "-d", "target/generated-sources/xjc", "-extension", "-XsimpleHashCode", "-XsimpleEquals", // "-XsimpleToString" }; Options options = new Options(); options.parseArguments(arguments); ConsoleErrorReporter receiver = new ConsoleErrorReporter(); Model model = ModelLoader.load(options, new JCodeModel(), receiver); model.generateCode(options, receiver); com.sun.codemodel.CodeWriter cw = options.createCodeWriter(); model.codeModel.build(cw); }
Example #4
Source File: ConnectPlugin.java From kafka-connect-transform-xml with Apache License 2.0 | 6 votes |
void processToStruct(JFieldVar schemaField, JCodeModel codeModel, ClassOutline classOutline) { final Map<String, JFieldVar> fields = classOutline.implClass.fields(); final JClass structClass = codeModel.ref(Struct.class); final JMethod method = classOutline.implClass.method(JMod.PUBLIC, structClass, "toStruct"); final JBlock methodBody = method.body(); final JVar structVar = methodBody.decl(structClass, "struct", JExpr._new(structClass).arg(schemaField)); for (final Map.Entry<String, JFieldVar> field : fields.entrySet()) { log.trace("processSchema() - processing name = '{}' type = '{}'", field.getKey(), field.getValue().type().name()); if (schemaField.name().equals(field.getKey())) { log.trace("processSchema() - skipping '{}' cause we added it.", field.getKey()); continue; } methodBody.invoke(structVar, "put") .arg(field.getKey()) .arg(JExpr.ref(JExpr._this(), field.getKey())); } methodBody._return(structVar); }
Example #5
Source File: JsonixPluginTest.java From jsonix-schema-compiler with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void compilesOWS_V_1_1_0() throws Exception { new File("target/generated-sources/ows-v_1_1_0").mkdirs(); URL schema = getClass().getResource("/ogc/ows/1.1.0/owsAll.xsd"); URL binding = getClass().getResource("/ogc/ows-v_1_1_0.xjb"); final String[] arguments = new String[] { "-xmlschema", schema.toExternalForm(), "-b", binding.toExternalForm(), "-d", "target/generated-sources/ows-v_1_1_0", "-extension", "-Xjsonix" }; Options options = new Options(); options.parseArguments(arguments); ConsoleErrorReporter receiver = new ConsoleErrorReporter(); Model model = ModelLoader.load(options, new JCodeModel(), receiver); model.generateCode(options, receiver); com.sun.codemodel.CodeWriter cw = options.createCodeWriter(); model.codeModel.build(cw); }
Example #6
Source File: RunSimplifyPlugin.java From jaxb2-basics with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void compilesSchema() throws Exception { new File("target/generated-sources/xjc").mkdirs(); URL schema = getClass().getResource("/schema.xsd"); URL binding = getClass().getResource("/bindings.xjb"); final String[] arguments = new String[] { "-xmlschema", schema.toExternalForm(), "-b", binding.toExternalForm(), "-d", "target/generated-sources/xjc", "-extension", "-Xsimplify", "-Xsimplify-usePluralForm=true"}; Options options = new Options(); options.parseArguments(arguments); ConsoleErrorReporter receiver = new ConsoleErrorReporter(); Model model = ModelLoader.load(options, new JCodeModel(), receiver); model.generateCode(options, receiver); com.sun.codemodel.CodeWriter cw = options.createCodeWriter(); model.codeModel.build(cw); }
Example #7
Source File: JsonixPluginTest.java From jsonix-schema-compiler with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void compilesContext_V_1_1_0() throws Exception { new File("target/generated-sources/context-v_1_1_0").mkdirs(); final String[] arguments = new String[] { "-xmlschema", getClass().getResource("/ogc/context/1.1.0/wmcAll.xsd") .toExternalForm(), "-b", getClass().getResource("/ogc/context-v_1_1_0.xjb") .toExternalForm(), "-d", "target/generated-sources/context-v_1_1_0", "-extension", "-Xjsonix" }; Options options = new Options(); options.parseArguments(arguments); ConsoleErrorReporter receiver = new ConsoleErrorReporter(); Model model = ModelLoader.load(options, new JCodeModel(), receiver); model.generateCode(options, receiver); com.sun.codemodel.CodeWriter cw = options.createCodeWriter(); model.codeModel.build(cw); }
Example #8
Source File: OperationProcessor.java From jpmml-evaluator with GNU Affero General Public License v3.0 | 6 votes |
private void createReportingValueClass(JCodeModel codeModel, Class<? extends Value<?>> valueClazz, JPrimitiveType type) throws JClassAlreadyExistsException { JClass reportClazz = codeModel.ref(Report.class); JDefinedClass reportingValueClazz = codeModel._class(JMod.PUBLIC, asReportingClass(valueClazz), ClassType.CLASS); reportingValueClazz._extends(codeModel.ref(valueClazz)); reportingValueClazz._implements(codeModel.ref(HasReport.class)); JFieldVar reportField = reportingValueClazz.field(JMod.PRIVATE, reportClazz, "report", JExpr._null()); createCopyMethod(reportingValueClazz); createOperationMethods(reportingValueClazz, valueClazz, type); createReportMethod(reportingValueClazz); createExpressionMethods(reportingValueClazz); createAccessorMethods(reportingValueClazz, reportField); createFormatMethod(reportingValueClazz, type); }
Example #9
Source File: SimpleToStringPlugin.java From jaxb2-basics with BSD 2-Clause "Simplified" License | 6 votes |
protected JMethod generateObject$toString(final ClassOutline classOutline, final JDefinedClass theClass) { final JCodeModel codeModel = theClass.owner(); final JMethod object$toString = theClass.method(JMod.PUBLIC, codeModel.ref(String.class), "toString"); object$toString.annotate(Override.class); { final JBlock body = object$toString.body(); final JVar toStringStrategy = body.decl(JMod.FINAL, codeModel.ref(ToStringStrategy2.class), "strategy", createToStringStrategy(codeModel)); final JVar buffer = body.decl(JMod.FINAL, codeModel.ref(StringBuilder.class), "buffer", JExpr._new(codeModel.ref(StringBuilder.class))); body.invoke("append").arg(JExpr._null()).arg(buffer) .arg(toStringStrategy); body._return(buffer.invoke("toString")); } return object$toString; }
Example #10
Source File: MModelInfoLoader.java From jsonix-schema-compiler with BSD 2-Clause "Simplified" License | 6 votes |
public MModelInfo<NType, NClass> loadModel(String resource) throws Exception { System.setProperty("javax.xml.accessExternalSchema", "all"); new File("target/generated-sources/" + resource).mkdirs(); final String[] arguments = new String[] { "-xmlschema", getClass().getResource("/" + resource).toExternalForm(), "-d", "target/generated-sources/" + resource, "-extension", "-Xjsonix", "-Xjsonix-generateJsonSchema" }; Options options = new Options(); options.parseArguments(arguments); ConsoleErrorReporter receiver = new ConsoleErrorReporter(); Model model = ModelLoader.load(options, new JCodeModel(), receiver); model.generateCode(options, receiver); com.sun.codemodel.CodeWriter cw = options.createCodeWriter(); model.codeModel.build(cw); final MModelInfo<NType, NClass> modelInfo = new XJCCMInfoFactory(model) .createModel(); return modelInfo; }
Example #11
Source File: CopyablePlugin.java From jaxb2-basics with BSD 2-Clause "Simplified" License | 6 votes |
protected JMethod generateCopyTo$copyTo(final ClassOutline classOutline, final JDefinedClass theClass) { final JCodeModel codeModel = theClass.owner(); final JMethod copyTo$copyTo = theClass.method(JMod.PUBLIC, codeModel.ref(Object.class), "copyTo"); copyTo$copyTo.annotate(Override.class); { final JVar target = copyTo$copyTo.param(Object.class, "target"); final JBlock body = copyTo$copyTo.body(); final JVar copyStrategy = body.decl(JMod.FINAL, codeModel.ref(CopyStrategy2.class), "strategy", createCopyStrategy(codeModel)); body._return(JExpr.invoke("copyTo").arg(JExpr._null()).arg(target) .arg(copyStrategy)); } return copyTo$copyTo; }
Example #12
Source File: XmlAdapterXjcUtils.java From hyperjaxb3 with BSD 2-Clause "Simplified" License | 5 votes |
public static JExpression unmarshallJAXBElement(JCodeModel codeModel, JClass xmlAdapterClass, JExpression value) { return codeModel.ref(XmlAdapterUtils.class).staticInvoke( "unmarshallJAXBElement").arg(xmlAdapterClass.dotclass()).arg( value); }
Example #13
Source File: SecuritySchemesHelper.java From raml-java-client-generator with Apache License 2.0 | 5 votes |
public static Collection<? extends JFieldVar> createBasicAuthFields(JDefinedClass containerClass) { List<JFieldVar> fieldVarList = new ArrayList<>(); JCodeModel jCodeModel = new JCodeModel(); fieldVarList.add(containerClass.field(JMod.PRIVATE | JMod.STATIC, jCodeModel._ref(String.class), USERNAME)); fieldVarList.add(containerClass.field(JMod.PRIVATE | JMod.STATIC, jCodeModel._ref(String.class), PASSWORD)); return fieldVarList; }
Example #14
Source File: RamlJavaClientGenerator.java From raml-java-client-generator with Apache License 2.0 | 5 votes |
private void buildActionMethods(JCodeModel cm, JDefinedClass resourceClass, Resource resource, String resourcePath, String resourceName, ApiModel apiModel) throws IOException, JClassAlreadyExistsException { final Map<ActionType, Action> actions = resource.getActions(); for (Map.Entry<ActionType, Action> actionTypeActionEntry : actions.entrySet()) { final ActionType actionType = actionTypeActionEntry.getKey(); final Action action = actionTypeActionEntry.getValue(); logger.info(" " + action.getType() + ""); final Response response = getActionResponse(action); final List<JTypeWithMimeType> bodiesType = buildBodyType(cm, actionType, action, resourcePath, resourceName); final JTypeWithMimeType returnType = buildReturnType(cm, actionType, response, resourcePath, resourceName); final JType queryParameterType = buildQueryParametersType(cm, actionType, action, resourcePath, resourceName); final JType headerParameterType = buildHeaderType(cm, resourcePath, resourceName, actionType, action); if (bodiesType.isEmpty()) { clientGenerator.callHttpMethod(cm, resourceClass, returnType, outputVersion, null, queryParameterType, headerParameterType, action, apiModel); } else { for (JTypeWithMimeType bodyType : bodiesType) { // final MimeType type = bodyType.getMimeType(); // if (MimeTypeHelper.isMultiPartType(type)) { // //TODO lautaro do something. // asdasd // } clientGenerator.callHttpMethod(cm, resourceClass, returnType, outputVersion, bodyType, queryParameterType, headerParameterType, action, apiModel); } } } }
Example #15
Source File: RamlJavaClientGenerator.java From raml-java-client-generator with Apache License 2.0 | 5 votes |
private JTypeWithMimeType buildReturnType(JCodeModel cm, ActionType actionType, Response response, String resourcePath, String resourceName) throws IOException { JTypeWithMimeType returnType = new JTypeWithMimeType(cm.VOID, null); if (response != null) { if (response.getBody() != null) { final Iterator<Map.Entry<String, MimeType>> bodies = response.getBody().entrySet().iterator(); if (bodies.hasNext()) { final Map.Entry<String, MimeType> bodyEntry = bodies.next(); final MimeType mimeType = bodyEntry.getValue(); if (MimeTypeHelper.isJsonType(mimeType)) { String className = NameHelper.toValidClassName(resourceName) + NameHelper.toCamelCase(actionType.name(), false) + RESPONSE_CLASS_SUFFIX; if (outputVersion.ordinal() >= OutputVersion.v2.ordinal()) { className = className + BODY_CLASS_SUFFIX; } returnType = new JTypeWithMimeType(getOrGeneratePojoFromJsonSchema(cm, resourcePath, mimeType, className), mimeType); } else if (MimeTypeHelper.isTextType(mimeType)) { returnType = new JTypeWithMimeType(cm.ref(String.class), mimeType); } else if (MimeTypeHelper.isBinaryType(mimeType)) { returnType = new JTypeWithMimeType(cm.ref(InputStream.class), mimeType); } else { returnType = new JTypeWithMimeType(cm.ref(Object.class), mimeType); } } } } return returnType; }
Example #16
Source File: PackageRule.java From springmvc-raml-plugin with Apache License 2.0 | 5 votes |
@Override public JPackage apply(ApiResourceMetadata controllerMetadata, JCodeModel generatableType) { if (StringUtils.hasText(Config.getBasePackage())) { return generatableType._package(Config.getBasePackage()); } return generatableType.rootPackage(); }
Example #17
Source File: RamlJavaClientGenerator.java From raml-java-client-generator with Apache License 2.0 | 5 votes |
private JType buildMap(JCodeModel cm, ActionType actionType, String resourcePath, String resourceName, Map<String, TypeFieldDefinition> queryParameters, String queryParamClassSuffix) throws JClassAlreadyExistsException { JType queryParameterType = null; if (queryParameters != null && !queryParameters.isEmpty()) { final String className = NameHelper.toValidClassName(resourceName) + NameHelper.toCamelCase(actionType.name(), false) + queryParamClassSuffix; queryParameterType = toParametersJavaBean(cm, className, queryParameters, resourcePath); } return queryParameterType; }
Example #18
Source File: ApiActionMetadata.java From springmvc-raml-plugin with Apache License 2.0 | 5 votes |
private void parseResponse(JCodeModel codeModel, String responseContentTypeFilter) { RamlResponse response = RamlHelper.getSuccessfulResponse(action); if (response != null && response.getBody() != null && !response.getBody().isEmpty()) { for (Entry<String, RamlMimeType> body : response.getBody().entrySet()) { if (responseContentTypeFilter == null || body.getKey().equals(responseContentTypeFilter)) { if (body.getKey().toLowerCase().contains("json") || body.getKey().toLowerCase().equals("body")) { // if we have a json type we need to return an object // Continue here! ApiBodyMetadata responseBody = null; RamlDataType type = body.getValue().getType(); String schema = body.getValue().getSchema(); // prefer type if we have it. String name = StringUtils.capitalize(getName()) + "Response"; if (type != null && type.getType() != null && !(type.getType() instanceof JSONTypeDeclaration)) { responseBody = RamlTypeHelper.mapTypeToPojo(codeModel, parent.getDocument(), type.getType()); } else if (StringUtils.hasText(schema)) { responseBody = SchemaHelper.mapSchemaToPojo(parent.getDocument(), schema, Config.getPojoPackage(), name, null); } if (responseBody != null) { this.responseBody.put(body.getKey(), responseBody); } } } } } }
Example #19
Source File: MethodParamsRule.java From springmvc-raml-plugin with Apache License 2.0 | 5 votes |
protected JVar paramObjects(ApiActionMetadata endpointMetadata, CodeModelHelper.JExtMethod generatableType) { String requestBodyName = endpointMetadata.getRequestBody().getName(); String requestBodyFullName = requestBodyName; if (BigDecimal.class.getSimpleName().equals(requestBodyName)) { requestBodyFullName = BigDecimal.class.getName(); } else if (BigInteger.class.getSimpleName().equals(requestBodyName)) { requestBodyFullName = BigInteger.class.getName(); } boolean array = endpointMetadata.getRequestBody().isArray(); List<JCodeModel> codeModels = new ArrayList<>(); if (endpointMetadata.getRequestBody().getCodeModel() != null) { codeModels.add(endpointMetadata.getRequestBody().getCodeModel()); } if (generatableType.owner() != null) { codeModels.add(generatableType.owner()); } JClass requestBodyType = findFirstClassBySimpleName(codeModels.toArray(new JCodeModel[codeModels.size()]), requestBodyFullName); if (allowArrayParameters && array) { JClass arrayType = generatableType.owner().ref(List.class); requestBodyType = arrayType.narrow(requestBodyType); } if (addParameterJavadoc) { generatableType.get().javadoc().addParam(NamingHelper.getParameterName(requestBodyName) + " The Request Body Payload"); } JVar param = generatableType.get().param(requestBodyType, NamingHelper.getParameterName(requestBodyName)); if (Config.getPojoConfig().isIncludeJsr303Annotations() && !RamlActionType.PATCH.equals(endpointMetadata.getActionType())) { // skip Valid annotation for PATCH actions since it's a partial // update so some required fields might be omitted param.annotate(Valid.class); } return param; }
Example #20
Source File: DateTypeInterpreter.java From springmvc-raml-plugin with Apache License 2.0 | 5 votes |
@Override public RamlInterpretationResult interpret(RamlRoot document, TypeDeclaration type, JCodeModel builderModel, boolean property) { RamlInterpretationResult result = new RamlInterpretationResult(type.required()); result.setResolvedClass(builderModel.ref(SchemaHelper.mapDateFormat(type.type()))); return result; }
Example #21
Source File: JpaUnitRunnerTest.java From jpa-unit with Apache License 2.0 | 5 votes |
@Test public void testClassWithPersistenceContextFieldOfWrongType() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "em"); emField.annotate(PersistenceContext.class); 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 RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("annotated with @PersistenceContext is not of type EntityManager")); }
Example #22
Source File: SpringControllerDecoratorRule.java From springmvc-raml-plugin with Apache License 2.0 | 5 votes |
@Override public final JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel generatableType) { JDefinedClass generatedInterface = new GenericJavaClassRule().setPackageRule(new PackageRule()) .setClassCommentRule(new ClassCommentRule()).setClassRule(new ControllerInterfaceDeclarationRule()) .addClassAnnotationRule(new GeneratedClassAnnotationRule()).setMethodCommentRule(new MethodCommentRule()) .setMethodSignatureRule(new ControllerMethodSignatureRule(getReturnTypeRule(false), new MethodParamsRule(isAddParameterJavadoc(), isAllowArrayParameters(), !Config.isInjectHttpHeadersParameter()))) .apply(metadata, generatableType); String delegateFieldName = StringUtils.uncapitalize(generatedInterface.name() + "Delegate"); GenericJavaClassRule delegateGenerator = new GenericJavaClassRule().setPackageRule(new PackageRule()) .setClassCommentRule(new ClassCommentRule()).addClassAnnotationRule(getControllerAnnotationRule()) .addClassAnnotationRule(new SpringRequestMappingClassAnnotationRule()) .addClassAnnotationRule(new SpringValidatedClassAnnotationRule()).addClassAnnotationRule(new GeneratedClassAnnotationRule()) .setClassRule(new ControllerClassDeclarationRule("Decorator")) .setImplementsExtendsRule(new ImplementsControllerInterfaceRule(generatedInterface)) .addFieldDeclarationRule(new SpringDelegateFieldDeclerationRule(delegateFieldName)) .setMethodCommentRule(new MethodCommentRule()).addMethodAnnotationRule(new SpringRequestMappingMethodAnnotationRule()) .addMethodAnnotationRule(getResponseBodyAnnotationRule()) .setMethodSignatureRule(new ControllerMethodSignatureRule(getReturnTypeRule(false), new SpringMethodParamsRule(isAddParameterJavadoc(), isAllowArrayParameters(), !Config.isInjectHttpHeadersParameter()))) .setMethodBodyRule(new DelegatingMethodBodyRule(delegateFieldName)); return delegateGenerator.apply(metadata, generatableType); }
Example #23
Source File: BooleanTypeInterpreter.java From springmvc-raml-plugin with Apache License 2.0 | 5 votes |
@Override public RamlInterpretationResult interpret(RamlRoot document, TypeDeclaration type, JCodeModel builderModel, boolean property) { RamlInterpretationResult result = new RamlInterpretationResult(type.required()); result.setResolvedClass(CodeModelHelper.findFirstClassBySimpleName(builderModel, Boolean.class.getSimpleName())); return result; }
Example #24
Source File: JpaUnitRunnerTest.java From jpa-unit with Apache License 2.0 | 5 votes |
@Test public void testClassWithMultiplePersistenceContextFields() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1"); em1Field.annotate(PersistenceContext.class); final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2"); em2Field.annotate(PersistenceContext.class); 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 RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("Only single field is allowed")); }
Example #25
Source File: XJC22Mojo.java From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License | 5 votes |
protected void writeCode(Outline outline) throws MojoExecutionException { if (getWriteCode()) { final Model model = outline.getModel(); final JCodeModel codeModel = model.codeModel; final File targetDirectory = model.options.targetDir; if (getVerbose()) { getLog().info( MessageFormat.format("Writing output to [{0}].", targetDirectory.getAbsolutePath())); } try { if (getCleanPackageDirectories()) { if (getVerbose()) { getLog().info("Cleaning package directories."); } cleanPackageDirectories(targetDirectory, codeModel); } final CodeWriter codeWriter = new LoggingCodeWriter( model.options.createCodeWriter(), getLog(), getVerbose()); codeModel.build(codeWriter); } catch (IOException e) { throw new MojoExecutionException("Unable to write files: " + e.getMessage(), e); } } else { getLog().info( "The [writeCode] setting is set to false, the code will not be written."); } }
Example #26
Source File: XJC20Mojo.java From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License | 5 votes |
protected Model loadModel(Options options) throws MojoExecutionException { if (getVerbose()) { getLog().info("Parsing input schema(s)..."); } final Model model = ModelLoader.load(options, new JCodeModel(), new LoggingErrorReceiver("Error while parsing schema(s).", getLog(), getVerbose())); if (model == null) throw new MojoExecutionException( "Unable to parse input schema(s). Error messages should have been provided."); return model; }
Example #27
Source File: JpaUnitRuleTest.java From jpa-unit with Apache License 2.0 | 5 votes |
@Test public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() 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, EntityManagerFactory.class, "emf"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.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")); }
Example #28
Source File: JpaUnitRuleTest.java From jpa-unit with Apache License 2.0 | 5 votes |
@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")); }
Example #29
Source File: AlphaMInfoFactoryTest.java From jaxb2-basics with BSD 2-Clause "Simplified" License | 5 votes |
@BeforeClass public static void createModel() throws BadCommandLineException, IOException { final String generateDirectory = "target/generated-sources/" + AlphaMInfoFactoryTest.class.getPackage().getName(); new File(generateDirectory).mkdirs(); final URL schema = AlphaMInfoFactoryTest.class .getResource("schema.xsd"); final URL binding = AlphaMInfoFactoryTest.class .getResource("binding.xjb"); final String[] arguments = new String[] { "-xmlschema", schema.toExternalForm(), "-b", binding.toExternalForm(), "-d", generateDirectory, "-extension" }; Options options = new Options(); options.parseArguments(arguments); ConsoleErrorReporter receiver = new ConsoleErrorReporter(); Model model = ModelLoader.load(options, new JCodeModel(), receiver); Assert.assertNotNull(model); final XJCCMInfoFactory factory = new XJCCMInfoFactory(model); AlphaMInfoFactoryTest.MODEL_INFO = factory.createModel(); model.generateCode(options, receiver); com.sun.codemodel.CodeWriter cw = options.createCodeWriter(); model.codeModel.build(cw); }
Example #30
Source File: JpaUnitRunnerTest.java From jpa-unit with Apache License 2.0 | 5 votes |
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); 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 JpaUnitRunner runner = new JpaUnitRunner(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")); }