com.sun.codemodel.JPackage Java Examples

The following examples show how to use com.sun.codemodel.JPackage. 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: XJCCMInfoFactory.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
		}
	});
}
 
Example #2
Source File: GraphElementFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #3
Source File: SchemagenHelper.java    From Avro-Schema-Generator with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: SpringRulesTest.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
@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);"));
}
 
Example #5
Source File: AvroSchemagenPlugin.java    From Avro-Schema-Generator with Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #6
Source File: CodeModelUtils.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: CodeModelUtils.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
	}

}
 
Example #8
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #9
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #10
Source File: GenericJavaClassRule.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #11
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #12
Source File: JsonSchemaController.java    From sc-generator with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #13
Source File: PrologCodeWriter.java    From aem-component-generator with Apache License 2.0 6 votes vote down vote up
@Override
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) {

        String s = prolog;
        int idx;
        while ((idx = s.indexOf('\n')) != -1) {
            out.println(s.substring(0, idx));
            s = s.substring(idx + 1);
        }
    }
    out.flush();
    return w;
}
 
Example #14
Source File: InterfaceBuilder.java    From aem-component-generator with Apache License 2.0 6 votes vote down vote up
@SafeVarargs
private final JDefinedClass buildInterface(String interfaceName, String comment, List<Property>... propertiesLists) {
    try {
        JPackage jPackage = codeModel._package(generationConfig.getProjectSettings().getModelInterfacePackage());
        JDefinedClass interfaceClass = jPackage._interface(interfaceName);
        interfaceClass.javadoc().append(comment);
        interfaceClass.annotate(codeModel.ref("org.osgi.annotation.versioning.ConsumerType"));

        if (this.isAllowExporting) {
            interfaceClass._extends(codeModel.ref(ComponentExporter.class));
        }
        if (propertiesLists != null) {
            for (List<Property> properties : propertiesLists) {
                addGettersWithoutFields(interfaceClass, properties);
            }
        }
        return interfaceClass;
    } catch (JClassAlreadyExistsException e) {
        LOG.error("Failed to generate child interface.", e);
    }

    return null;
}
 
Example #15
Source File: SpringFeignClientInterfaceDeclarationRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JDefinedClass apply(ApiResourceMetadata controllerMetadata, JPackage generatableType) {

	String controllerClassName = controllerMetadata.getResourceName().concat("Client");
	JDefinedClass definedClass;
	try {
		definedClass = generatableType._interface(controllerClassName);
	} catch (JClassAlreadyExistsException e1) {
		definedClass = generatableType._getClass(controllerClassName);
	}
	return definedClass;
}
 
Example #16
Source File: ClassFieldDeclarationRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyClassFieldDeclarationRule_shouldCreate_validAutowiredField() throws JClassAlreadyExistsException {
	ClassFieldDeclarationRule rule = new ClassFieldDeclarationRule("field", String.class);

	JPackage jPackage = jCodeModel.rootPackage();
	JDefinedClass jClass = jPackage._class(JMod.PUBLIC, "MyClass");
	jClass._implements(Serializable.class);
	rule.apply(getControllerMetadata(), jClass);

	assertThat(serializeModel(), containsString("import org.springframework.beans.factory.annotation.Autowired;"));
	assertThat(serializeModel(), containsString("@Autowired"));
	assertThat(serializeModel(), containsString("private String field;"));
}
 
Example #17
Source File: PackageRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyPackageRule_shouldCreate_emptyBasePackage_onNullPackage() {
	String emptyBasePackage = "     ";
	TestConfig.setBasePackage(emptyBasePackage);

	JPackage jPackage = rule.apply(getControllerMetadata(), jCodeModel);
	assertThat(jPackage, is(notNullValue()));
	assertThat(jPackage.name(), equalTo(""));
}
 
Example #18
Source File: ClassFieldDeclarationRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyClassFieldDeclarationRule_shouldCreate_validValueAnnotedField() throws JClassAlreadyExistsException {
	ClassFieldDeclarationRule rule = new ClassFieldDeclarationRule("field", String.class, "${sample}");

	JPackage jPackage = jCodeModel.rootPackage();
	JDefinedClass jClass = jPackage._class(JMod.PUBLIC, "MyClass");
	jClass._implements(Serializable.class);
	rule.apply(getControllerMetadata(), jClass);

	assertFalse(serializeModel().contains("import org.springframework.beans.factory.annotation.Autowired;"));
	assertFalse((serializeModel().contains("@Autowired")));
	assertThat(serializeModel(), containsString("@Value(\"${sample}\")"));
	assertThat(serializeModel(), containsString("private String field;"));
}
 
Example #19
Source File: ClassFieldDeclarationRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyClassFieldDeclarationRule_shouldCreate_validNonAutowiredField() throws JClassAlreadyExistsException {
	ClassFieldDeclarationRule rule = new ClassFieldDeclarationRule("field", String.class, false);

	JPackage jPackage = jCodeModel.rootPackage();
	JDefinedClass jClass = jPackage._class(JMod.PUBLIC, "MyClass");
	jClass._implements(Serializable.class);
	rule.apply(getControllerMetadata(), jClass);

	assertFalse(serializeModel().contains("import org.springframework.beans.factory.annotation.Autowired;"));
	assertFalse((serializeModel().contains("@Autowired")));
	assertThat(serializeModel(), containsString("private String field;"));
}
 
Example #20
Source File: ResourceClassDeclarationRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JDefinedClass apply(ApiResourceMetadata controllerMetadata, JPackage generatableType) {
	String resourceClassName = controllerMetadata.getName() + classNameSuffix;
	JDefinedClass definedClass;
	try {
		definedClass = generatableType._class(resourceClassName);
	} catch (JClassAlreadyExistsException e1) {
		definedClass = generatableType._getClass(resourceClassName);
	}
	return definedClass;
}
 
Example #21
Source File: ControllerInterfaceDeclarationRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JDefinedClass apply(ApiResourceMetadata controllerMetadata, JPackage generatableType) {
	String controllerClassName = controllerMetadata.getName() + CONTROLLER_SUFFIX;
	JDefinedClass definedClass;
	try {
		definedClass = generatableType._interface(controllerClassName);
	} catch (JClassAlreadyExistsException e1) {
		definedClass = generatableType._getClass(controllerClassName);
	}
	return definedClass;
}
 
Example #22
Source File: LoggingCodeWriter.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public OutputStream openBinary(JPackage pkg, String fileName)
		throws IOException {
	if (verbose) {
		if (pkg.isUnnamed())
			log.info("XJC writing: " + fileName);
		else
			log.info("XJC writing: "
					+ pkg.name().replace('.', File.separatorChar)
					+ File.separatorChar + fileName);
	}

	return core.openBinary(pkg, fileName);
}
 
Example #23
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testJpaUnitRunnerAndJpaUnitRuleFieldExcludeEachOther() 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, "emf");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.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());

    try {
        // WHEN
        new JpaUnitRunner(cut);
        fail("InitializationError expected");
    } catch (final InitializationError e) {
        // expected
        assertThat(e.getCauses().get(0).getMessage(), containsString("exclude each other"));
    }

}
 
Example #24
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceUnitFieldOfWrongType() 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, "emf");
    emField.annotate(PersistenceUnit.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 @PersistenceUnit is not of type EntityManagerFactory"));
}
 
Example #25
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #26
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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 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"));
}
 
Example #27
Source File: XJC23Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private boolean isRelevantPackage(JPackage _package) {
	if (_package.propertyFiles().hasNext()) {
		return true;
	}
	Iterator<JDefinedClass> classes = _package.classes();
	for (; classes.hasNext();) {
		JDefinedClass _class = (JDefinedClass) classes.next();
		if (!_class.isHidden()) {
			return true;
		}
	}
	return false;
}
 
Example #28
Source File: XJC21Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private boolean isRelevantPackage(JPackage _package) {
	if (_package.propertyFiles().hasNext()) {
		return true;
	}
	Iterator<JDefinedClass> classes = _package.classes();
	for (; classes.hasNext();) {
		JDefinedClass _class = (JDefinedClass) classes.next();
		if (!_class.isHidden()) {
			return true;
		}
	}
	return false;
}
 
Example #29
Source File: IndexedCodeWriter.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see com.sun.codemodel.CodeWriter#openBinary(com.sun.codemodel.JPackage, java.lang.String)
 */
@Override
public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
    String fullname = pkg.name() + "." + fileName;
    fullname = fullname.replace(".java", "");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    this.index.put(fullname, stream);
    return stream;
}
 
Example #30
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
CreateTraversingVisitorClass(JDefinedClass visitor, JDefinedClass progressMonitor,
                             JDefinedClass traverser, Outline outline, JPackage jPackage,
                             Function<String, String> visitMethodNamer,
                             Function<String, String> traverseMethodNamer) {
    super(outline, jPackage);
    this.visitor = visitor;
    this.traverser = traverser;
    this.progressMonitor = progressMonitor;
    this.visitMethodNamer = visitMethodNamer;
    this.traverseMethodNamer = traverseMethodNamer;
}