Java Examples for com.thoughtworks.qdox.model.JavaClass
The following java examples will help you to understand the usage of com.thoughtworks.qdox.model.JavaClass. These source code samples are taken from different open source projects.
Example 1
Project: cucumber-contrib-master File: GrammarGenTest.java View source code |
@Test
public void usecase() {
JavaProjectBuilder builder = new JavaProjectBuilder();
// Adding all .java files in a source tree (recursively).
builder.addSourceTree(new File("/Users/Arnauld/Projects/cucumber-contrib/src/test/java/sample/coffeemachine"));
for (JavaPackage pkg : builder.getPackages()) {
System.out.println("::: " + pkg.getName());
for (JavaClass klazz : pkg.getClasses()) {
System.out.println(" :: " + klazz);
for (JavaMethod method : klazz.getMethods()) {
System.out.println(" : " + method.getAnnotations());
}
}
}
}
Example 2
Project: JaxRs2Retrofit-master File: RetrofitGenerator.java View source code |
public JavaFile createResource(JavaClass jaxRsClass) {
// find path annotation
JavaAnnotation jaxRsPath = null;
JavaAnnotation jaxRsConsumes = null;
for (JavaAnnotation annotation : jaxRsClass.getAnnotations()) {
String annotationType = annotation.getType().getFullyQualifiedName();
if (annotationType.equals(Path.class.getName())) {
jaxRsPath = annotation;
} else if (annotationType.equals(Consumes.class.getName())) {
jaxRsConsumes = annotation;
}
}
// no a valid JAX RS resource
if (jaxRsPath == null)
return null;
if (jaxRsClass.getName().matches(settings.getExcludedClassNamesRegex()))
return null;
System.out.println(jaxRsClass.getName());
TypeSpec.Builder retrofitResourceBuilder = TypeSpec.interfaceBuilder(jaxRsClass.getName()).addModifiers(Modifier.PUBLIC);
addAboutJavadoc(retrofitResourceBuilder);
for (JavaMethod jaxRsMethod : jaxRsClass.getMethods()) {
Collection<MethodSpec> retrofitMethods = createMethod(jaxRsClass, jaxRsMethod, jaxRsPath, jaxRsConsumes);
if (retrofitMethods != null) {
for (MethodSpec method : retrofitMethods) {
retrofitResourceBuilder.addMethod(method);
}
}
}
return JavaFile.builder(settings.getPackageName(), retrofitResourceBuilder.build()).build();
}
Example 3
Project: liferay-portal-master File: ServiceBuilder.java View source code |
public static boolean hasAnnotation(AbstractBaseJavaEntity abstractBaseJavaEntity, String annotationName) {
Annotation[] annotations = abstractBaseJavaEntity.getAnnotations();
if (annotations == null) {
return false;
}
for (int i = 0; i < annotations.length; i++) {
Type type = annotations[i].getType();
JavaClass javaClass = type.getJavaClass();
if (annotationName.equals(javaClass.getName())) {
return true;
}
}
return false;
}
Example 4
Project: EasySOA-Incubation-master File: JaxWSSourcesHandler.java View source code |
// Pass 1 : Find all WS clients/interfaces public Map<String, JavaServiceInterfaceInformation> findWSInterfaces(JavaSource source, MavenDeliverableInformation mavenDeliverable, CodeDiscoveryRegistryClient registryClient, Log log) throws Exception { Map<String, JavaServiceInterfaceInformation> wsInjectableTypeSet = new HashMap<String, JavaServiceInterfaceInformation>(); JavaClass[] classes = source.getClasses(); for (JavaClass c : classes) { if (isWsInterface(c)) { String wsName = getWsName(c); String wsNamespace = getWsNamespace(c); Map<String, OperationInformation> operations = getOperationsInformation(c, null); wsInjectableTypeSet.put(c.getFullyQualifiedName(), new JavaServiceInterfaceInformation(this.codeDiscovery.getSubproject(), mavenDeliverable.getGroupId(), mavenDeliverable.getArtifactId(), c.getFullyQualifiedName(), wsNamespace, wsName, operations)); } } return wsInjectableTypeSet; }
Example 5
Project: testdox-master File: Main.java View source code |
void doSources(JavaSource[] sources) {
gen.startRun();
List<String> packagesStarted = new ArrayList<String>();
for (int i = 0; i < sources.length; i++) {
JavaSource source = sources[i];
JavaClass[] classes = source.getClasses();
doClasses(classes, source, packagesStarted);
}
gen.endGeneration();
gen.endRun();
}
Example 6
Project: MyPublicRepo-master File: JavaSourceParser.java View source code |
public static Map<String, String[]> methodToParamNamesMap(String javaSrcFile, Class<?> clazz) {
Map<String, String[]> map = new HashMap<String, String[]>();
try {
JavaDocBuilder builder = new JavaDocBuilder();
builder.addSource(new File(javaSrcFile));
JavaClass jc = builder.getClassByName(clazz.getName());
JavaMethod methods[] = jc.getMethods();
for (JavaMethod method : methods) {
// these methods should be exposed / added to the interface
if (method.isPublic() && !method.isStatic()) {
String methodName = method.getName();
String[] paramNames = getParameterNames(method);
map.put(methodName, paramNames);
}
}
} catch (IOException e) {
s_logger.log(Level.WARNING, "Failed to parse source file: " + javaSrcFile, e);
}
return map;
}
Example 7
Project: plexus-containers-master File: QDoxComponentGleaner.java View source code |
// ----------------------------------------------------------------------
// ComponentGleaner Implementation
// ----------------------------------------------------------------------
public ComponentDescriptor<?> glean(JavaClassCache classCache, JavaClass javaClass) throws ComponentGleanerException {
DocletTag tag = javaClass.getTagByName(PLEXUS_COMPONENT_TAG);
if (tag == null) {
return null;
}
Map<String, String> parameters = tag.getNamedParameterMap();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
String fqn = javaClass.getFullyQualifiedName();
//log.debug( "Creating descriptor for component: {}", fqn );
ComponentDescriptor<?> componentDescriptor = new ComponentDescriptor<Object>();
componentDescriptor.setImplementation(fqn);
// ----------------------------------------------------------------------
// Role
// ----------------------------------------------------------------------
String role = getParameter(parameters, PLEXUS_ROLE_PARAMETER);
if (role == null) {
role = findRole(javaClass);
if (role == null) {
return null;
}
}
componentDescriptor.setRole(role);
// ----------------------------------------------------------------------
// Role hint
// ----------------------------------------------------------------------
String roleHint = getParameter(parameters, PLEXUS_ROLE_HINT_PARAMETER);
if (roleHint != null) {
// getLogger().debug( " Role hint: " + roleHint );
}
componentDescriptor.setRoleHint(roleHint);
// ----------------------------------------------------------------------
// Version
// ----------------------------------------------------------------------
String version = getParameter(parameters, PLEXUS_VERSION_PARAMETER);
componentDescriptor.setVersion(version);
// ----------------------------------------------------------------------
// Lifecycle handler
// ----------------------------------------------------------------------
String lifecycleHandler = getParameter(parameters, PLEXUS_LIFECYCLE_HANDLER_PARAMETER);
componentDescriptor.setLifecycleHandler(lifecycleHandler);
// ----------------------------------------------------------------------
// Lifecycle handler
// ----------------------------------------------------------------------
String instatiationStrategy = getParameter(parameters, PLEXUS_INSTANTIATION_STARTEGY_PARAMETER);
componentDescriptor.setInstantiationStrategy(instatiationStrategy);
// ----------------------------------------------------------------------
// Alias
// ----------------------------------------------------------------------
componentDescriptor.setAlias(getParameter(parameters, PLEXUS_ALIAS_PARAMETER));
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
findExtraParameters(PLEXUS_COMPONENT_TAG, parameters);
// ----------------------------------------------------------------------
// Requirements
// ----------------------------------------------------------------------
findRequirements(classCache, componentDescriptor, javaClass);
// ----------------------------------------------------------------------
// Description
// ----------------------------------------------------------------------
String comment = javaClass.getComment();
if (comment != null) {
int i = comment.indexOf('.');
if (i > 0) {
// include the dot
comment = comment.substring(0, i + 1);
}
}
componentDescriptor.setDescription(comment);
// ----------------------------------------------------------------------
// Configuration
// ----------------------------------------------------------------------
XmlPlexusConfiguration configuration = new XmlPlexusConfiguration("configuration");
findConfiguration(configuration, javaClass);
componentDescriptor.setConfiguration(configuration);
return componentDescriptor;
}
Example 8
Project: turmeric-runtime-master File: JavaSourceParser.java View source code |
public static Map<String, String[]> methodToParamNamesMap(String javaSrcFile, Class<?> clazz) {
Map<String, String[]> map = new HashMap<String, String[]>();
try {
JavaDocBuilder builder = new JavaDocBuilder();
builder.addSource(new File(javaSrcFile));
JavaClass jc = builder.getClassByName(clazz.getName());
JavaMethod methods[] = jc.getMethods();
for (JavaMethod method : methods) {
// these methods should be exposed / added to the interface
if (method.isPublic() && !method.isStatic()) {
String methodName = method.getName();
String[] paramNames = getParameterNames(method);
map.put(methodName, paramNames);
}
}
} catch (IOException e) {
s_logger.log(Level.WARNING, "Failed to parse source file: " + javaSrcFile, e);
}
return map;
}
Example 9
Project: ipf-labs-master File: Documentation.java View source code |
public void registerMethod(String module, JavaClass cls, JavaMethod method) {
if (method.getTagByName(DSL_DOC_TAG) != null) {
validate(method);
String section = getSection(method);
List<ParamInfo> paramInfos = getParams(method);
ParamInfo returnParam = getReturns(method);
String dslDocLink = getDslDocLink(method);
String comment = javaDoc2Html(method.getComment(), cls);
MethodInfo methodInfo = new MethodInfo(method.getName(), comment, paramInfos, returnParam, dslDocLink);
this.addMethod(module, section, methodInfo);
}
}
Example 10
Project: openflexo-master File: FJPJavaDocBuilder.java View source code |
private void addClasses(JavaSource source) { Set resultSet = new HashSet(); addClassesRecursive(source, resultSet); JavaClass[] javaClasses = (JavaClass[]) resultSet.toArray(new JavaClass[resultSet.size()]); for (int classIndex = 0; classIndex < javaClasses.length; classIndex++) { JavaClass cls = javaClasses[classIndex]; addClass(cls); } }
Example 11
Project: testdox-maven-plugin-master File: TestDoxReportMojo.java View source code |
protected void executeReport(Locale locale) throws MavenReportException { Sink sink = getSink(); sink.head(); sink.title(); sink.text("TestDox Report"); sink.title_(); sink.head_(); sink.body(); getLog().debug("testdox report output is set to: " + getOutputDirectory()); String testSourceDirectory = mavenProject.getBuild().getTestSourceDirectory(); getLog().info("Processing test classes from: " + testSourceDirectory); JavaDocBuilder builder = new JavaDocBuilder(); builder.addSourceTree(new File(testSourceDirectory)); JavaSource[] sources = builder.getSources(); for (int i = 0; i < sources.length; i++) { JavaSource source = sources[i]; for (Iterator iter = getTestClasses(source).iterator(); iter.hasNext(); ) { JavaClass clazz = (JavaClass) iter.next(); getLog().info("Processing test class: " + clazz.getName()); sink.section1(); sink.sectionTitle1(); sink.text(formatter.prettifyTestClassName(clazz.getName())); sink.sectionTitle1_(); sink.section1_(); sink.list(); for (Iterator iterator = getTestMethods(clazz).iterator(); iterator.hasNext(); ) { JavaMethod method = (JavaMethod) iterator.next(); sink.listItem(); sink.text(formatter.prettifyTestMethodName(method.getName())); sink.listItem_(); } sink.list_(); } } sink.body_(); sink.flush(); sink.close(); }
Example 12
Project: codehaus-mojo-master File: GenerateAsyncMojo.java View source code |
/**
* @param sourceRoot the base directory to scan for RPC services
* @return true if some file have been generated
* @throws Exception generation failure
*/
private boolean scanAndGenerateAsync(File sourceRoot, JavaDocBuilder builder) throws Exception {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(sourceRoot);
scanner.setIncludes(new String[] { servicePattern });
scanner.scan();
String[] sources = scanner.getIncludedFiles();
if (sources.length == 0) {
return false;
}
boolean fileGenerated = false;
for (String source : sources) {
File sourceFile = new File(sourceRoot, source);
File targetFile = getTargetFile(source);
if (isUpToDate(sourceFile, targetFile)) {
getLog().debug(targetFile.getAbsolutePath() + " is up to date. Generation skipped");
// up to date, but still need to report generated-sources directory as sourceRoot
fileGenerated = true;
continue;
}
String className = getTopLevelClassName(source);
JavaClass clazz = builder.getClassByName(className);
if (isEligibleForGeneration(clazz)) {
targetFile.getParentFile().mkdirs();
generateAsync(clazz, targetFile);
fileGenerated = true;
}
}
return fileGenerated;
}
Example 13
Project: blammo-master File: BlammoParser.java View source code |
public List parse(File javaSourcesDir) throws BlammoParserException { messageIndex = messageOffset; ArrayList loggers = new ArrayList(); JavaDocBuilder builder = new JavaDocBuilder(); builder.addSourceTree(javaSourcesDir); JavaClass[] javaClasses = builder.getClasses(); for (int i = 0; i < javaClasses.length; i++) { JavaClass javaClass = javaClasses[i]; if (javaClass.isInterface()) { if (javaClass.getTagByName(TAG_LOGGER) != null) { Logger logger = new Logger(); logger.setJavaClass(javaClass); extractEvents(logger, javaClass); loggers.add(logger); } } } return loggers; }
Example 14
Project: bonecp-master File: TestXMLDefaultCreate.java View source code |
/**
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws IOException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
@Test
public void testCreateXMLFile() throws SecurityException, IllegalArgumentException, IllegalAccessException, IOException, InvocationTargetException, NoSuchMethodException {
// delete old state
new File("bonecp/src/main/resources/bonecp-default-config.xml").delete();
URL url = Thread.currentThread().getContextClassLoader().getResource("bonecp-default-config.xml");
String oldState = url.getFile();
if (oldState != null) {
new File(oldState).delete();
}
BoneCPConfig config = new BoneCPConfig();
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<!-- Default options loaded by BoneCP. Modify as per your needs. This file has\n");
sb.append(" been automatically generated. -->\n");
sb.append("<bonecp-config>\n");
sb.append("\t<default-config>\n");
JavaDocBuilder builder = new JavaDocBuilder();
// find the file (cater for maven/eclipse workflows)
File f = new File("bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java");
File out;
FileReader fr;
if (f.canRead()) {
fr = new FileReader(f);
out = new File("bonecp/src/main/resources/bonecp-default-config.xml");
} else {
fr = new FileReader("src/main/java/com/jolbox/bonecp/BoneCPConfig.java");
out = new File("src/main/resources/bonecp-default-config.xml");
}
builder.addSource(fr);
JavaClass cls = builder.getClassByName("com.jolbox.bonecp.BoneCPConfig");
for (JavaMethod method : cls.getMethods()) {
String mName = method.getName();
if (mName.startsWith("set") && method.isPublic()) {
Annotation[] a = method.getAnnotations();
if (method.getParameters().length == 1 && !method.getParameters()[0].getType().getJavaClass().getFullyQualifiedName().equals("java.util.Properties") && !(a.length > 0 && a[0].getType().getValue().equals("java.lang.Deprecated"))) {
sb.append(formatComment(method.getComment()));
String prop = toProperty(mName);
Object defaultVal;
try {
defaultVal = fetchDefaultValue(config, prop);
if (defaultVal == null) {
sb.append("\t\t<!-- <property name=\"" + prop + "\">(null or no default value)</property> -->\n\n");
} else {
sb.append("\t\t<property name=\"" + prop + "\">" + defaultVal + "</property>\n\n");
}
} catch (NoSuchFieldException e) {
}
}
}
}
sb.append("\t</default-config>\n");
sb.append("</bonecp-config>\n");
FileWriter fw = new FileWriter(out);
fw.write(sb.toString());
fw.close();
}
Example 15
Project: onos-master File: OnosSwaggerMojo.java View source code |
// Checks whether javaClass has a path tag associated with it and if it does
// processes its methods and creates a tag for the class on the root
void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags, ObjectNode definitions) {
// If the class does not have a Path tag then ignore it
JavaAnnotation annotation = getPathAnnotation(javaClass);
if (annotation == null) {
return;
}
String path = getPath(annotation);
if (path == null) {
return;
}
String resourcePath = "/" + path;
String tagPath = path.isEmpty() ? "/" : path;
// Create tag node for this class.
ObjectNode tagObject = mapper.createObjectNode();
tagObject.put("name", tagPath);
if (javaClass.getComment() != null) {
tagObject.put("description", shortText(javaClass.getComment()));
}
tags.add(tagObject);
// Create an array node add to all methods from this class.
ArrayNode tagArray = mapper.createArrayNode();
tagArray.add(tagPath);
processAllMethods(javaClass, resourcePath, paths, tagArray, definitions);
}
Example 16
Project: spring-me-master File: QDoxAugmentation.java View source code |
/** * Completes metadata of the {@link MutableInstance} passed in, accepting * <code>allInstances</code> for resolving references. * * @param instance The instance that must be completed. * @param context All beans in the context, for resolving references. */ private void attribute(MutableInstance instance, MutableContext context) { guaranteeType(instance, context); guaranteeTypes(context, instance.getConstructorArguments()); guaranteeTypes(context, instance.getSetters()); logger.logAttributing(instance.getName()); JavaClass cl = builder.getClassByName(instance.getType()); if (isFactoryBean(cl)) { logger.logFoundFactoryBean(instance.getName()); instance.setFactoryBean(true); } if (isInitializingBean(cl)) { instance.setInitMethod("afterPropertiesSet"); } for (MutablePropertySetter setter : instance.getSetters()) { BeanProperty property = cl.getBeanProperty(setter.getName(), true); if (property == null) { logger.logNoSuchProperty(setter.getName(), cl.getName()); } else { setter.setType(property.getType().getValue()); setter.setPrimitive(property.getType().isPrimitive()); attribute(setter.getSource(), context); } } if (instance.getConstructorArguments() != null && instance.getConstructorArguments().size() > 0) { logger.logInformConstructorArguments(instance.getName()); for (MutableConstructorArgument argument : instance.getConstructorArguments()) { attribute(argument.getSource(), context); } List<MutableConstructorArgument> arguments = instance.getConstructorArguments(); JavaMethod method = null; // If there is no factory method if (instance.getFactoryMethod() == null) { logger.logPlainOldConstructor(instance.getName()); method = findConstructor(cl, arguments); if (method == null) { logger.logNoMatchingConstructor(instance); } // If there *is* a factory method, but no factory bean } else if (instance.getFactoryInstance() == null) { logger.logFactoryMethod(instance.getName(), instance.getFactoryMethod()); JavaClass factoryClass = builder.getClassByName(instance.getReferencedType()); method = findMethod(factoryClass, true, instance.getFactoryMethod(), arguments); if (method == null) { logger.logNoMatchingFactoryMethod(instance); } // If there *is* a factory method, *and* a factory bean } else { MutableInstance factoryInstance = context.getByName(instance.getFactoryInstance()); logger.logFactoryBean(instance.getName(), factoryInstance.getName(), instance.getFactoryMethod()); JavaClass factoryClass = builder.getClassByName(factoryInstance.getType()); method = findMethod(factoryClass, false, instance.getFactoryMethod(), arguments); if (method == null) { logger.logNoMatchingFactoryInstanceMethod(instance); } } if (method != null) { copyTypes(method.getParameters(), arguments); } } }
Example 17
Project: citrus-tool-master File: InheritMojo.java View source code |
/** Maven plugin entry-point */
public void execute() throws MojoExecutionException {
// pre-load available plugin metadata - local and dependencies
PluginXml targetPlugin = loadPluginMetadata(m_outputDirectory);
// select maven source directories
JavaDocBuilder builder = new JavaDocBuilder();
for (Iterator i = m_project.getCompileSourceRoots().iterator(); i.hasNext(); ) {
builder.addSourceTree(new File((String) i.next()));
}
// scan local source for javadoc tags
JavaSource[] javaSources = builder.getSources();
for (int i = 0; i < javaSources.length; i++) {
JavaClass mojoClass = javaSources[i].getClasses()[0];
// need plugin inheritance
DocletTag extendsTag = mojoClass.getTagByName(EXTENDS_PLUGIN);
if (null != extendsTag) {
String pluginName = extendsTag.getValue();
getLog().info("Extending " + pluginName + " plugin");
// lookup using simple plugin name (ie. compiler, archetype, etc.)
PluginXml superPlugin = getDependentPluginMetaData(pluginName);
if (null == superPlugin) {
throw new MojoExecutionException(pluginName + " plugin is not a dependency");
} else {
mergePluginMojo(mojoClass, targetPlugin, superPlugin);
}
}
}
try {
targetPlugin.write();
} catch (IOException e) {
throw new MojoExecutionException("cannot update local plugin metadata", e);
}
}
Example 18
Project: fop-master File: EventProducerCollector.java View source code |
/** * Scans a file and processes it if it extends the {@link EventProducer} interface. * @param src the source file (a Java source file) * @return true if the file contained an EventProducer interface * @throws IOException if an I/O error occurs * @throws EventConventionException if the EventProducer conventions are violated * @throws ClassNotFoundException if a required class cannot be found */ public boolean scanFile(File src) throws IOException, EventConventionException, ClassNotFoundException { JavaDocBuilder builder = new JavaDocBuilder(this.tagFactory); builder.addSource(src); JavaClass[] classes = builder.getClasses(); boolean eventProducerFound = false; for (JavaClass clazz : classes) { if (clazz.isInterface() && implementsInterface(clazz, CLASSNAME_EVENT_PRODUCER)) { processEventProducerInterface(clazz); eventProducerFound = true; } } return eventProducerFound; }
Example 19
Project: jcute-master File: JUnitTestGenerator.java View source code |
private static boolean isTestPresent(File f, String testFun) { JavaSource source; boolean flag = false; JavaDocBuilder builder = new JavaDocBuilder(); try { builder.addSource(f); source = builder.getSources()[0]; JavaClass[] javaClasses = source.getClasses(); for (int i = 0; !flag && i < javaClasses.length; i++) { JavaClass javaClass = javaClasses[i]; JavaMethod[] methods = javaClass.getMethods(); for (int j = 0; !flag && j < methods.length; j++) { JavaMethod method = methods[j]; if (method.getName().equals(testFun)) { JavaParameter[] parameters = method.getParameters(); if (parameters.length == 0) { flag = true; } } } } } catch (IOException e) { e.printStackTrace(); } return flag; }
Example 20
Project: jsonschema2pojo-master File: JavaNameIT.java View source code |
@Test
public void originalPropertyNamesAppearInJavaDoc() throws NoSuchFieldException, IOException {
schemaRule.generateAndCompile("/schema/javaName/javaName.json", "com.example.javaname");
File generatedJavaFile = schemaRule.generated("com/example/javaname/JavaName.java");
JavaDocBuilder javaDocBuilder = new JavaDocBuilder();
javaDocBuilder.addSource(generatedJavaFile);
JavaClass classWithDescription = javaDocBuilder.getClassByName("com.example.javaname.JavaName");
JavaField javaPropertyField = classWithDescription.getFieldByName("javaProperty");
assertThat(javaPropertyField.getComment(), containsString("Corresponds to the \"propertyWithJavaName\" property."));
JavaField javaEnumField = classWithDescription.getFieldByName("javaEnum");
assertThat(javaEnumField.getComment(), containsString("Corresponds to the \"enumWithJavaName\" property."));
JavaField javaObjectField = classWithDescription.getFieldByName("javaObject");
assertThat(javaObjectField.getComment(), containsString("Corresponds to the \"objectWithJavaName\" property."));
}
Example 21
Project: jsystem-master File: SutTreeTableModel.java View source code |
/** * Gets the string representation of the javadoc for a given class * @param builder * Javadoc builder * @param soClass * Name of the class to get the javadoc for * @param soMethod * The method to get the javadoc for * @return String * String representation of the javadoc */ private static String getJavadoc(JavaDocBuilder builder, String soClass, String soMethod) { if (builder == null) { return null; } JavaClass cls = builder.getClassByName(soClass); JavaClass superCls = null; if (cls.getSuperJavaClass() != null) { superCls = builder.getClassByName(cls.getSuperJavaClass().getName().toString()); } else { superCls = builder.getClassByName(cls.getSuperClass().getFullQualifiedName()); } JavaClass[] interfacesCls = cls.getImplementedInterfaces(); JavaMethod methods[] = cls.getMethods(); // A setter is a method that has one parameter for (int index = 0; index < methods.length; index++) { JavaMethod method = methods[index]; if (method.getName().equals(soMethod) && method.getName().startsWith("set") && method.getParameters().length == 1) { StringBuilder buffer = new StringBuilder(); if (method.getComment() != null) { buffer.append(method.getComment()); } DocletTag[] tags = method.getTags(); if (tags != null && tags.length > 0) { if (buffer.length() > 0) { buffer.append("\n"); } for (DocletTag doclet : tags) { buffer.append(doclet.getName()).append(": ").append(doclet.getValue()); } } if (buffer.length() == 0) { for (JavaClass interfaceCls : interfacesCls) { JavaMethod interfaceMethods[] = interfaceCls.getMethods(); for (int jndex = 0; jndex < interfaceMethods.length; jndex++) { JavaMethod interfaceMethod = interfaceMethods[jndex]; if (interfaceMethod.getName().equals(method.getName())) { if (interfaceMethod.getParameters().length == 1) { if (interfaceMethod.getComment() != null) { buffer.append(interfaceMethod.getComment()); } tags = interfaceMethod.getTags(); if (tags != null && tags.length > 0) { buffer.append("\n"); for (DocletTag doclet : tags) { buffer.append(doclet.getName()).append(": ").append(doclet.getValue()); } } } } } } } if (buffer.length() == 0) { JavaMethod superMethods[] = superCls.getMethods(); for (int jndex = 0; jndex < superMethods.length; jndex++) { JavaMethod superMethod = superMethods[jndex]; if (superMethod.getName().equals(method.getName())) { if (superMethod.getParameters().length == 1) { if (superMethod.getComment() != null) { buffer.append(superMethod.getComment()); } tags = superMethod.getTags(); if (tags != null && tags.length > 0) { buffer.append("\n"); for (DocletTag doclet : tags) { buffer.append(doclet.getName()).append(": ").append(doclet.getValue()); } } } } } } if (buffer.length() == 0) { buffer.replace(0, buffer.length(), "N/A"); } return buffer.toString(); } } return null; }
Example 22
Project: livecycle-maven-master File: AnnotationDrivenQDoxComponentInfoExtractor.java View source code |
public boolean populateServices(Service service, JavaClass javaClass) {
service.setName(javaClass.getName());
service.setImplementationClass(javaClass.getFullyQualifiedName());
be.idamediafoundry.sofa.livecycle.dsc.annotations.Service serviceAnnotation = findAnnotation(javaClass, be.idamediafoundry.sofa.livecycle.dsc.annotations.Service.class);
if (StringUtils.isNotBlank(serviceAnnotation.smallIcon())) {
service.setSmallIcon(serviceAnnotation.smallIcon());
}
if (StringUtils.isNotBlank(serviceAnnotation.largeIcon())) {
service.setLargeIcon(serviceAnnotation.largeIcon());
}
String comment = javaClass.getComment();
service.setHint(getFirstSentence(comment));
service.setDescription(comment);
// Find factory method.
JavaMethod factoryMethod = findAnnotationOnMethods(javaClass, FactoryMethod.class);
if (factoryMethod != null) {
if (factoryMethod.isAbstract() || factoryMethod.isConstructor() || !factoryMethod.isPublic() || factoryMethod.isPropertyAccessor() || factoryMethod.isPropertyMutator() || !factoryMethod.isStatic()) {
throw new IllegalStateException("You should not annotate " + factoryMethod.getName() + " as FactoryMethod, it is not a valid factory method!");
}
service.setFactoryMethod(factoryMethod.getName());
}
if (serviceAnnotation.requestProcessingStrategy() != be.idamediafoundry.sofa.livecycle.dsc.annotations.Service.RequestProcessingStrategy.NONE) {
service.setRequestProcessingStrategy(serviceAnnotation.requestProcessingStrategy().name());
}
return true;
}
Example 23
Project: maven-plugins-master File: AbstractFixJavadocMojo.java View source code |
/** * {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { if (!fixClassComment && !fixFieldComment && !fixMethodComment) { getLog().info("Specified to NOT fix classes, fields and methods. Nothing to do."); return; } // verify goal params init(); if (fixTagsSplitted.length == 0) { getLog().info("No fix tag specified. Nothing to do."); return; } // add warranty msg if (!preCheck()) { return; } // run clirr try { executeClirr(); } catch (MavenInvocationException e) { if (getLog().isDebugEnabled()) { getLog().error("MavenInvocationException: " + e.getMessage(), e); } else { getLog().error("MavenInvocationException: " + e.getMessage()); } getLog().info("Clirr is ignored."); } // run qdox and process try { JavaClass[] javaClasses = getQdoxClasses(); if (javaClasses != null) { for (JavaClass javaClass : javaClasses) { processFix(javaClass); } } } catch (IOException e) { throw new MojoExecutionException("IOException: " + e.getMessage(), e); } }
Example 24
Project: nexus-core-master File: ReportWriter.java View source code |
public void writeReport() { // parse the java doc JavaDocBuilder builder = new JavaDocBuilder(); builder.addSourceTree(this.sourceDir); // all parsed // now find all of the test classes List<JavaClass> testClasses = new ArrayList<JavaClass>(); JavaClass[] classes = builder.getClasses(); List<JavaClass> classesWithoutDescriptions = new ArrayList<JavaClass>(); for (int ii = 0; ii < classes.length; ii++) { JavaClass javaClass = classes[ii]; if (!javaClass.isAbstract() && classHasMethodWithTestAnnotation(javaClass)) { testClasses.add(javaClass); // check if we have a javadoc comment if (StringUtils.isEmpty(javaClass.getComment())) { classesWithoutDescriptions.add(javaClass); } } } List<ReportBean> beans = new ArrayList<ReportBean>(); for (JavaClass javaClass : testClasses) { ReportBean bean = new ReportBean(); bean.setJavaClass(javaClass); bean.setTestId(this.getTestId(javaClass)); // add to the collection beans.add(bean); } // sort the beans. Collections.sort(beans); // now this would be nice to be configurable, but move the sample tests to the top of the list this.fudgeOrder(beans); // now write the report // TODO: get from container new ConsoleWikiReport().writeReport(beans); // print errors here.. this should be handled better, but there are no plans for this 'report' anyway. if (!classesWithoutDescriptions.isEmpty()) { System.err.println("\n\n\n\nErrors:\n"); for (Iterator<JavaClass> iter = classesWithoutDescriptions.iterator(); iter.hasNext(); ) { JavaClass javaClass = (JavaClass) iter.next(); System.err.println(javaClass.getName() + " is missing a javadoc comment."); } } }
Example 25
Project: org.ops4j.pax.construct-master File: InheritMojo.java View source code |
/**
* Maven plugin entry-point
*/
public void execute() throws MojoExecutionException {
// pre-load available plugin metadata - local and dependencies
PluginXml targetPlugin = loadPluginMetadata(m_outputDirectory);
Map dependentPluginsByName = loadDependentPluginMetaData();
// select maven source directories
JavaDocBuilder builder = new JavaDocBuilder();
for (Iterator i = m_project.getCompileSourceRoots().iterator(); i.hasNext(); ) {
builder.addSourceTree(new File((String) i.next()));
}
// scan local source for javadoc tags
JavaSource[] javaSources = builder.getSources();
for (int i = 0; i < javaSources.length; i++) {
JavaClass mojoClass = javaSources[i].getClasses()[0];
// need plugin inheritance
DocletTag extendsTag = mojoClass.getTagByName(EXTENDS_PLUGIN);
if (null != extendsTag) {
String pluginName = extendsTag.getValue();
getLog().info("Extending " + pluginName + " plugin");
// lookup using simple plugin name (ie. compiler, archetype, etc.)
PluginXml superPlugin = (PluginXml) dependentPluginsByName.get(pluginName);
if (null == superPlugin) {
throw new MojoExecutionException(pluginName + " plugin is not a dependency");
} else {
mergePluginMojo(mojoClass, targetPlugin, superPlugin);
}
}
}
try {
targetPlugin.write();
} catch (IOException e) {
throw new MojoExecutionException("cannot update local plugin metadata", e);
}
}
Example 26
Project: sling-master File: JcrOcmMojo.java View source code |
public void execute() throws MojoFailureException {
boolean hasFailures = false;
// prepare QDox and prime with the compile class path of the project
JavaDocBuilder builder = new JavaDocBuilder();
try {
builder.getClassLibrary().addClassLoader(this.getCompileClassLoader());
} catch (IOException ioe) {
throw new MojoFailureException("Cannot prepare QDox");
}
// add the sources from the project
for (Iterator i = this.project.getCompileSourceRoots().iterator(); i.hasNext(); ) {
try {
builder.addSourceTree(new File((String) i.next()));
} catch (OutOfMemoryError oome) {
builder = null;
throw new MojoFailureException("Failed analyzing source due to not enough memory, try setting Max Heap Size higher, e.g. using MAVEN_OPTS=-Xmx128m");
}
}
// parse the sources and get them
JavaSource[] javaSources = builder.getSources();
List descriptors = new ArrayList();
for (int i = 0; i < javaSources.length; i++) {
JavaClass[] javaClasses = javaSources[i].getClasses();
for (int j = 0; javaClasses != null && j < javaClasses.length; j++) {
DocletTag tag = javaClasses[j].getTagByName(ClassDescriptor.TAG_CLASS_DESCRIPTOR);
if (tag != null) {
ClassDescriptor descriptor = this.createClassDescriptor(javaClasses[j]);
if (descriptor != null) {
descriptors.add(descriptor);
} else {
hasFailures = true;
}
}
}
}
// after checking all classes, throw if there were any failures
if (hasFailures) {
throw new MojoFailureException("Jackrabbit OCM Descriptor parsing had failures (see log)");
}
// terminate if there is nothing to write
if (descriptors.isEmpty()) {
this.getLog().info("No Jackrabbit OCM Descriptors found in project");
return;
}
// finally the descriptors have to be written ....
if (StringUtils.isEmpty(this.finalName)) {
this.getLog().error("Descriptor file name must not be empty");
return;
}
// prepare the descriptor output file
File descriptorFile = new File(new File(this.outputDirectory, "SLING-INF"), this.finalName);
// ensure parent dir
descriptorFile.getParentFile().mkdirs();
this.getLog().info("Generating " + descriptors.size() + " OCM Mapping Descriptors to " + descriptorFile);
// write out all the class descriptors in parse order
FileOutputStream descriptorStream = null;
XMLWriter xw = null;
try {
descriptorStream = new FileOutputStream(descriptorFile);
xw = new XMLWriter(descriptorStream, false);
xw.printElementStart("jackrabbit-ocm", false);
for (Iterator di = descriptors.iterator(); di.hasNext(); ) {
ClassDescriptor sd = (ClassDescriptor) di.next();
sd.generate(xw);
}
xw.printElementEnd("jackrabbit-ocm");
} catch (IOException ioe) {
hasFailures = true;
this.getLog().error("Cannot write descriptor to " + descriptorFile, ioe);
throw new MojoFailureException("Failed to write descriptor to " + descriptorFile);
} finally {
IOUtil.close(xw);
IOUtil.close(descriptorStream);
// remove the descriptor file in case of write failure
if (hasFailures) {
descriptorFile.delete();
}
}
// now add the descriptor file to the maven resources
final String ourRsrcPath = this.outputDirectory.getAbsolutePath();
boolean found = false;
final Iterator rsrcIterator = this.project.getResources().iterator();
while (!found && rsrcIterator.hasNext()) {
final Resource rsrc = (Resource) rsrcIterator.next();
found = rsrc.getDirectory().equals(ourRsrcPath);
}
if (!found) {
final Resource resource = new Resource();
resource.setDirectory(this.outputDirectory.getAbsolutePath());
this.project.addResource(resource);
}
// and set include accordingly
this.project.getProperties().setProperty("Sling-Mappings", "SLING-INF/" + this.finalName);
}
Example 27
Project: zeppelin-master File: StaticRepl.java View source code |
public static String execute(String generatedClassName, String code) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
// Java parasing
JavaProjectBuilder builder = new JavaProjectBuilder();
JavaSource src = builder.addSource(new StringReader(code));
// get all classes in code (paragraph)
List<JavaClass> classes = src.getClasses();
String mainClassName = null;
// Searching for class containing Main method
for (int i = 0; i < classes.size(); i++) {
boolean hasMain = false;
for (int j = 0; j < classes.get(i).getMethods().size(); j++) {
if (classes.get(i).getMethods().get(j).getName().equals("main") && classes.get(i).getMethods().get(j).isStatic()) {
mainClassName = classes.get(i).getName();
hasMain = true;
break;
}
}
if (hasMain == true) {
break;
}
}
// if there isn't Main method, will retuen error
if (mainClassName == null) {
logger.error("Exception for Main method", "There isn't any class " + "containing static main method.");
throw new Exception("There isn't any class containing static main method.");
}
// replace name of class containing Main method with generated name
code = code.replace(mainClassName, generatedClassName);
JavaFileObject file = new JavaSourceFromString(generatedClassName, code.toString());
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
// Creating new stream to get the output data
PrintStream newOut = new PrintStream(baosOut);
PrintStream newErr = new PrintStream(baosErr);
// Save the old System.out!
PrintStream oldOut = System.out;
PrintStream oldErr = System.err;
// Tell Java to use your special stream
System.setOut(newOut);
System.setErr(newErr);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
// executing the compilation process
boolean success = task.call();
// if success is false will get error
if (!success) {
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
if (diagnostic.getLineNumber() == -1) {
continue;
}
System.err.println("line " + diagnostic.getLineNumber() + " : " + diagnostic.getMessage(null));
}
System.out.flush();
System.err.flush();
System.setOut(oldOut);
System.setErr(oldErr);
logger.error("Exception in Interpreter while compilation", baosErr.toString());
throw new Exception(baosErr.toString());
} else {
try {
// creating new class loader
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
// execute the Main method
Class.forName(generatedClassName, true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
System.out.flush();
System.err.flush();
// set the stream to old stream
System.setOut(oldOut);
System.setErr(oldErr);
return baosOut.toString();
} catch (ClassNotFoundExceptionNoSuchMethodException | IllegalAccessException | InvocationTargetException | e) {
logger.error("Exception in Interpreter while execution", e);
System.err.println(e);
e.printStackTrace(newErr);
throw new Exception(baosErr.toString(), e);
} finally {
System.out.flush();
System.err.flush();
System.setOut(oldOut);
System.setErr(oldErr);
}
}
}
Example 28
Project: cloud-rest-service-master File: ServiceDocBuilder.java View source code |
public List<ClassDoc> buildDoc() { List<ClassDoc> classDocs = new ArrayList<ClassDoc>(); List<JavaClass> javaClasses = findRestServices(); for (JavaClass javaClass : javaClasses) { ClassDoc classDoc = new ClassDoc(); classDoc.setServiceDesc(javaClass.getComment()); classDoc.setServiceName(javaClass.getTagByName("serviceName").getValue()); List<JavaMethod> javaMethods = findMethods(javaClass); for (JavaMethod method : javaMethods) { //方法文档信æ?¯ MethodDoc methodDoc = new MethodDoc(); Annotation[] annotations = method.getAnnotations(); for (Annotation ann : annotations) { if (ServiceMethod.class.getName().equals(ann.getType().getFullyQualifiedName())) { String name = (String) ann.getNamedParameter("value"); String version = (String) ann.getNamedParameter("version"); methodDoc.setName(StringUtils.strip(name.trim(), "\"")); methodDoc.setVersion(StringUtils.strip(version.trim(), "\"")); break; } } methodDoc.setDescription(method.getComment()); //返回值文档信æ?¯ ReturnDoc returnDoc = new ReturnDoc(); returnDoc.setDataType(method.getReturnType().getFullyQualifiedName()); if ("java.util.List".equals(returnDoc.getDataType())) { Type type = method.getReturnType().getActualTypeArguments()[0]; if (!ClassUtils.isPrimitiveOrWrapper(type.getFullyQualifiedName())) { returnDoc.setBeanName(type.getFullyQualifiedName()); JavaBeanDoc beanDoc = getJavaBeanDoc(type.getFullyQualifiedName()); classDoc.getBeanDocs().add(beanDoc); } } if (method.getTagByName("return") == null) { throw new RuntimeException("方法 " + method.getName() + " 没有return注释"); } //解æž?返回实例数æ?®ï¼Œä¾‹å¦‚è¿”å›žå€¼æ–‡æ¡£æ³¨é‡Šæ ¼å¼?: @return userid A2342312 $$ 用户ID String returnDesc = method.getTagByName("return").getValue(); String[] desces = returnDesc.split("\\$\\$"); if (desces.length > 1) { returnDoc.setExampleData(desces[0]); returnDoc.setDescription(desces[1]); } else { returnDoc.setDescription(returnDesc); } returnDoc.setDimensions(method.getReturnType().getDimensions()); methodDoc.setReturnDoc(returnDoc); //方法å?‚数文档信æ?¯ JavaParameter[] parameters = method.getParameters(); DocletTag[] paramTags = method.getTagsByName("param"); for (int i = 0, len = parameters.length; i < len; i++) { JavaParameter parameter = parameters[i]; String type = parameter.getType().getFullyQualifiedName(); String paramName = parameter.getName(); ParamDoc paramDoc = new ParamDoc(); paramDoc.setName(paramName); paramDoc.setDataType(type); //解æž?å?‚数实例数æ?®ï¼Œä¾‹å¦‚å?‚æ•°æ–‡æ¡£æ³¨é‡Šæ ¼å¼?: @param userid A2342312 $$ 用户ID String paramDesc = getParamDesc(paramName, paramTags); desces = paramDesc.split("\\$\\$"); if (desces.length > 1) { paramDoc.setExampleData(desces[0].trim()); paramDoc.setDescription(desces[1].trim()); } else { paramDoc.setDescription(paramDesc); } methodDoc.getParamDocs().add(paramDoc); //基本类型,和javax.servlet.*相关的类排除掉 if (!ClassUtils.isPrimitiveOrWrapper(type) && !type.startsWith("javax.servlet")) { classDoc.getBeanDocs().add(getJavaBeanDoc(type)); } } classDoc.getMethodDocs().add(methodDoc); } boolean isNew = true; for (ClassDoc doc : classDocs) { if (doc.getServiceName().equals(classDoc.getServiceName())) { doc.getBeanDocs().addAll(classDoc.getBeanDocs()); doc.getMethodDocs().addAll(classDoc.getMethodDocs()); isNew = false; break; } } if (isNew) classDocs.add(classDoc); } return classDocs; }
Example 29
Project: DrakkarKeel-master File: JavaParser.java View source code |
/**
* Analiza el fichero que puede contener mas de una clase java.
* Extrae el nombre del paquete, y por cada clase su nombre, atributos,
* metodos y comentarios.
* @param f
* @throws IOException
*/
public void AnalyzeDocument(File f) throws IOException {
getBuilder().addSource(new FileReader(f.getCanonicalPath()));
setSrc(getBuilder().getSources());
//Getting all code of the file
allSource = getSrc()[0].getCodeBlock();
//Getting package
if (getSrc()[0].getPackage() != null) {
setPkg(getSrc()[0].getPackage());
setClassPackage(getPkg().getName());
}
//Getting classesnames
if (getSrc()[0].getClasses() != null) {
setClassdef(getSrc()[0].getClasses());
setClassNumber(getClassdef().length);
classNames = new String[classesDefinition.length];
classVarNames = new String[classesDefinition.length][];
setClassVarComments(new String[classesDefinition.length][]);
classMethodNames = new String[classesDefinition.length][];
classMethodsComments = new String[classesDefinition.length][];
classComments = new String[classesDefinition.length];
setClassJavaDocs(new String[classesDefinition.length]);
for (int i = 0; i < classesDefinition.length; i++) {
JavaClass jclass = classesDefinition[i];
classNames[i] = jclass.getName();
//Getting variables
if (jclass.getFields() != null) {
vars = jclass.getFields();
setClassVariableNumber(vars.length);
classVarNames = new String[classesDefinition.length][vars.length];
setClassVarComments(new String[classesDefinition.length][vars.length]);
for (int j = 0; j < vars.length; j++) {
JavaField jfield = vars[j];
classVarNames[i][j] = jfield.getName();
classVarJavaDocs = new String[classesDefinition.length][vars.length];
if (jfield.getComment() != null) {
getClassVarComments()[i][j] = jfield.getComment();
}
if (jfield.getTags().length != 0) {
String value = "", name = "", line = "";
DocletTag[] doclet = jfield.getTags();
if (doclet.length != 0) {
for (DocletTag docletTag : doclet) {
name = docletTag.getName();
value = docletTag.getValue();
line += name + " " + value + " ";
}
classVarJavaDocs[i][j] = line;
}
}
}
}
//Getting methods
if (jclass.getMethods() != null) {
JavaMethod[] jmethod = jclass.getMethods();
setClassMethodNumber(jmethod.length);
classMethodNames = new String[classesDefinition.length][jmethod.length];
for (int k = 0; k < jmethod.length; k++) {
JavaMethod javaMethod = jmethod[k];
classMethodNames[i][k] = javaMethod.getName();
classMethodJavaDocs = new String[classesDefinition.length][jmethod.length];
//duda
classMethodsComments = new String[classesDefinition.length][jmethod.length];
if (javaMethod.getComment() != null) {
classMethodsComments[i][k] = javaMethod.getComment();
}
if (javaMethod.getTags().length != 0) {
String value = "", name = "", line = "";
DocletTag[] doclet = javaMethod.getTags();
for (DocletTag docletTag : doclet) {
name = docletTag.getName();
value = docletTag.getValue();
line += name + " " + value + " ";
}
classMethodJavaDocs[i][k] = line;
}
}
}
//Getting comments
if (jclass.getComment() != null) {
classComments[i] = jclass.getComment();
}
//Getting class javadocs
if (jclass.getTags().length != 0) {
String value = "", name = "", line = "";
DocletTag[] doclet = jclass.getTags();
for (DocletTag docletTag : doclet) {
name = docletTag.getName();
value = docletTag.getValue();
line += name + " " + value + " ";
}
getClassJavaDocs()[i] = line;
}
}
}
}
Example 30
Project: gwt-maven-plugin-master File: GenerateAsyncMojo.java View source code |
/**
* @param sourceRoot the base directory to scan for RPC services
* @return true if some file have been generated
* @throws Exception generation failure
*/
private boolean scanAndGenerateAsync(File sourceRoot, JavaDocBuilder builder) throws Exception {
Scanner scanner = buildContext.newScanner(sourceRoot);
scanner.setIncludes(new String[] { servicePattern });
scanner.scan();
String[] sources = scanner.getIncludedFiles();
if (sources.length == 0) {
return false;
}
boolean fileGenerated = false;
for (String source : sources) {
File sourceFile = new File(sourceRoot, source);
File targetFile = getTargetFile(source);
if (!force && buildContext.isUptodate(targetFile, sourceFile)) {
getLog().debug(targetFile.getAbsolutePath() + " is up to date. Generation skipped");
// up to date, but still need to report generated-sources directory as sourceRoot
fileGenerated = true;
continue;
}
String className = getTopLevelClassName(source);
JavaClass clazz = builder.getClassByName(className);
if (isEligibleForGeneration(clazz)) {
getLog().debug("Generating async interface for service " + className);
targetFile.getParentFile().mkdirs();
generateAsync(clazz, targetFile);
fileGenerated = true;
}
}
return fileGenerated;
}
Example 31
Project: monkeytalk-master File: MetaAPIGenerator.java View source code |
public static String generateComponents(File srcDir) {
JavaDocBuilder javadoc = new JavaDocBuilder();
javadoc.addSourceTree(srcDir);
Map<String, String> componentMap = new HashMap<String, String>();
StringBuilder sb = new StringBuilder();
for (JavaSource src : javadoc.getSources()) {
if (IGNORE_FLEX && src.getPackageName().endsWith(".flex")) {
// }
continue;
}
for (JavaClass clazz : src.getClasses()) {
if (clazz.getTagByName("ignoreMeta") != null) {
continue;
}
System.out.println(clazz.getFullyQualifiedName());
sb.append("components.add(new Component(\n ");
sb.append('"').append(clazz.getName()).append("\",\n ");
sb.append('"').append(cleanString(clazz.getComment())).append("\",\n ");
Type[] extendz = clazz.getImplements();
sb.append(extendz == null || extendz.length == 0 || extendz[0].getJavaClass() == null || extendz[0].getJavaClass().getName().equalsIgnoreCase("mtobject") ? "null" : '"' + extendz[0].getJavaClass().getName().toString() + '"').append(",\n ");
StringBuilder actions = new StringBuilder();
for (JavaMethod meth : clazz.getMethods()) {
if (meth.getTagByName("ignoreMeta") != null) {
continue;
}
if (actions.length() > 0) {
actions.append(",\n");
}
actions.append(" new Action(\n ");
actions.append('"').append(upperCamel(meth.getName())).append("\",\n ");
actions.append('"').append(cleanString(meth.getComment())).append("\",\n ");
StringBuilder args = new StringBuilder();
for (DocletTag param : meth.getTagsByName("param")) {
String value = param.getValue();
int idx = value.indexOf("\n");
if (idx == -1) {
throw new RuntimeException("ERROR: " + clazz.getName() + "#" + meth.getName() + "() - bad @param javadoc");
}
String pname = value.substring(0, idx);
String pdesc = value.substring(idx + 1);
JavaParameter p = meth.getParameterByName(pname);
if (p == null) {
throw new RuntimeException("ERROR: " + clazz.getName() + "#" + meth.getName() + "() - @param " + pname + " has no matching method argument");
}
String ptype = p.getType().getJavaClass().getName();
if (args.length() > 0) {
args.append(",\n");
}
args.append(" new Arg(");
args.append('"').append(pname).append('"');
args.append(",\"").append(cleanString(pdesc)).append('"');
args.append(",\"").append(ptype).append('"');
args.append(p.isVarArgs() ? ",true" : "");
args.append(")");
}
if (args.length() > 0) {
actions.append("new ArrayList<Arg>(Arrays.asList(\n").append(args.toString()).append("\n )),\n ");
} else {
actions.append("null,\n ");
}
actions.append('"').append(meth.getReturnType() != null ? meth.getReturnType().getJavaClass().getName() : "").append("\",\n ");
actions.append('"').append(meth.getTagByName("return") != null ? cleanString(meth.getTagByName("return").getValue()) : "").append("\")");
}
if (actions.length() > 0) {
sb.append("new ArrayList<Action>(Arrays.asList(\n").append(actions.toString()).append("\n ))\n ,\n ");
} else {
sb.append("null,\n ");
}
StringBuilder properties = new StringBuilder();
for (DocletTag tag : clazz.getTagsByName("prop")) {
String val = tag.getParameters()[0];
String tagVal = tag.getValue();
int sep = tagVal.indexOf("-");
String desc = (sep != -1 ? tagVal.substring(sep + 1).trim() : null);
String args = (sep != -1 ? tagVal.substring(0, sep).trim() : tagVal);
args = (args.equals(val) ? null : args.substring(val.length()));
if (properties.length() > 0) {
properties.append(",\n");
}
properties.append(" new Property(");
properties.append("\"").append(val).append("\", ");
if (args == null) {
properties.append("null, ");
} else if (args.startsWith("(") && args.endsWith(")")) {
properties.append("\"").append(cleanString(args.substring(1, args.length() - 1))).append("\", ");
} else {
properties.append("\"").append(cleanString(args)).append("\", ");
}
if (desc == null) {
properties.append("null)");
} else {
properties.append("\"").append(cleanString(desc)).append("\")");
}
}
if (properties.length() > 0) {
sb.append("new ArrayList<Property>(Arrays.asList(\n").append(properties.toString()).append("\n ))\n )");
} else {
sb.append("null)");
}
sb.append("\n);\n");
componentMap.put(clazz.getName(), sb.toString());
sb = new StringBuilder();
}
}
// sort by component name (we do this now, during codegen, to avoid sorting later)
sb = new StringBuilder();
List<String> keys = new ArrayList<String>(componentMap.keySet());
Collections.sort(keys);
for (String k : keys) {
sb.append(componentMap.get(k));
}
return "IGNORE_FLEX = " + IGNORE_FLEX + ";\n\n" + sb.toString();
}
Example 32
Project: turmeric-releng-master File: JavaSourceAssert.java View source code |
/** * Assert that the java source file is valid, parseable, and is declared as an Interface. * * @param java * the java source file. * @throws IOException */ public static JavaClass assertIsInterface(File java) throws IOException { JavaDocBuilder builder = new JavaDocBuilder(); JavaSource src = builder.addSource(java); JavaClass jc = getClassName(src, java); Assert.assertThat("Failed to parse java source: " + java.getAbsolutePath(), jc, notNullValue()); String msg = String.format("JavaSource: (%s) should be an interface: %s", jc.getName(), java); Assert.assertThat(msg, jc.isInterface(), is(true)); return jc; }
Example 33
Project: CONRAD-master File: RegistryEditor.java View source code |
/**
* Example for getting comments from a java file using qdox.
* This requires access to the actual java file in the list of ressources.
* (Use source folder as output folder for class files in eclipse)
*/
private void generateKeyTableFromSources() {
// read java sources to parser from qdox
InputStream stream = RegKeys.class.getResourceAsStream("RegKeys.java");
InputStreamReader reader = new InputStreamReader(stream);
JavaDocBuilder builder = new JavaDocBuilder();
builder.addSource(reader);
// generate table with line wrapping cells in colum 2
final int wordWrapColumnIndex = 1;
descTable = new JTable() {
private static final long serialVersionUID = 7516482246121817003L;
public TableCellRenderer getCellRenderer(int row, int column) {
if (column == wordWrapColumnIndex) {
return new MultilineTableCell();
} else {
return super.getCellRenderer(row, column);
}
}
};
// Use qdox parser to parse RegKeys sources
JavaClass cls = builder.getClassByName("edu.stanford.rsl.conrad.utils.RegKeys");
// get list of fields
JavaField[] fields = cls.getFields();
// build table model
String[][] tableData = new String[fields.length][2];
String[] label = { "Key", "Description" };
int i = 0;
for (JavaField field : fields) {
tableData[i][0] = field.getName();
tableData[i][1] = field.getComment();
if (tableData[i][1] != null) {
tableData[i][1] = field.getComment().replace("<BR>", "\n").replace("<br>", "\n").replace("<b>", "\n").replace("</b>", "\n");
} else {
tableData[i][1] = "";
}
i++;
}
DefaultTableModel model = new DefaultTableModel(tableData, label);
descTable.setModel(model);
}
Example 34
Project: extreme-fishbowl-master File: AttributeCompiler.java View source code |
protected void generateClass(JavaClass javaClass) throws Exception {
String name = null;
File sourceFile = null;
File destFile = null;
String packageName = null;
String className = null;
packageName = javaClass.getPackage();
if (packageName == null) {
packageName = "";
}
if (javaClass.isInner()) {
sourceFile = getSourceFile(javaClass);
String nonPackagePrefix = javaClass.getParent().getClassNamePrefix();
if (packageName.length() > 0) {
nonPackagePrefix = nonPackagePrefix.substring(packageName.length() + 1);
}
className = nonPackagePrefix + javaClass.getName();
name = javaClass.getParent().getClassNamePrefix() + javaClass.getName();
} else {
name = javaClass.getFullyQualifiedName();
sourceFile = getSourceFile(javaClass);
className = javaClass.getName();
}
if (sourceFile == null) {
log("Unable to find source file for: " + name);
}
destFile = new File(destDir, name.replace('.', '/') + "$__attributeRepository.java");
if (!hasAttributes(javaClass)) {
if (destFile.exists()) {
destFile.delete();
}
return;
}
if (destFile.exists() && sourceFile != null && destFile.lastModified() >= sourceFile.lastModified()) {
return;
}
numGenerated++;
destFile.getParentFile().mkdirs();
PrintWriter pw = new PrintWriter(new FileWriter(destFile));
try {
if (packageName != null && !packageName.equals("")) {
pw.println("package " + packageName + ";");
}
if (sourceFile != null) {
copyImports(sourceFile, pw);
}
StringTokenizer tok = new StringTokenizer(attributePackages, ";");
while (tok.hasMoreTokens()) {
pw.println("import " + tok.nextToken() + ".*;");
}
pw.println("public class " + className + "$__attributeRepository implements org.apache.commons.attributes.AttributeRepositoryClass {");
{
pw.println(" private final java.util.Set classAttributes = new java.util.HashSet ();");
pw.println(" private final java.util.Map fieldAttributes = new java.util.HashMap ();");
pw.println(" private final java.util.Map methodAttributes = new java.util.HashMap ();");
pw.println(" private final java.util.Map constructorAttributes = new java.util.HashMap ();");
pw.println();
pw.println(" public " + className + "$__attributeRepository " + "() {");
pw.println(" initClassAttributes ();");
pw.println(" initMethodAttributes ();");
pw.println(" initFieldAttributes ();");
pw.println(" initConstructorAttributes ();");
pw.println(" }");
pw.println();
pw.println(" public java.util.Set getClassAttributes () { return classAttributes; }");
pw.println(" public java.util.Map getFieldAttributes () { return fieldAttributes; }");
pw.println(" public java.util.Map getConstructorAttributes () { return constructorAttributes; }");
pw.println(" public java.util.Map getMethodAttributes () { return methodAttributes; }");
pw.println();
pw.println(" private void initClassAttributes () {");
addExpressions(javaClass.getTags(), pw, "classAttributes", sourceFile);
pw.println(" }");
pw.println();
// ---- Field Attributes
pw.println(" private void initFieldAttributes () {");
pw.println(" java.util.Set attrs = null;");
JavaField[] fields = javaClass.getFields();
for (int i = 0; i < fields.length; i++) {
JavaField member = (JavaField) fields[i];
if (member.getTags().length > 0) {
String key = member.getName();
pw.println(" attrs = new java.util.HashSet ();");
addExpressions(member.getTags(), pw, "attrs", sourceFile);
pw.println(" fieldAttributes.put (\"" + key + "\", attrs);");
pw.println(" attrs = null;");
pw.println();
}
}
pw.println(" }");
// ---- Method Attributes
pw.println(" private void initMethodAttributes () {");
pw.println(" java.util.Set attrs = null;");
pw.println(" java.util.List bundle = null;");
JavaMethod[] methods = javaClass.getMethods();
for (int i = 0; i < methods.length; i++) {
JavaMethod member = (JavaMethod) methods[i];
if (!member.isConstructor() && member.getTags().length > 0) {
StringBuffer sb = new StringBuffer();
sb.append(member.getName()).append("(");
sb.append(getParameterTypes(member.getParameters()));
sb.append(")");
String key = sb.toString();
pw.println(" bundle = new java.util.ArrayList ();");
pw.println(" attrs = new java.util.HashSet ();");
addExpressions(member.getTags(), null, pw, "attrs", sourceFile);
pw.println(" bundle.add (attrs);");
pw.println(" attrs = null;");
pw.println(" attrs = new java.util.HashSet ();");
addExpressions(member.getTags(), "return", pw, "attrs", sourceFile);
pw.println(" bundle.add (attrs);");
pw.println(" attrs = null;");
JavaParameter[] parameters = member.getParameters();
for (int j = 0; j < parameters.length; j++) {
JavaParameter parameter = (JavaParameter) parameters[j];
pw.println(" attrs = new java.util.HashSet ();");
addExpressions(member.getTags(), parameter.getName(), pw, "attrs", sourceFile);
pw.println(" bundle.add (attrs);");
pw.println(" attrs = null;");
}
pw.println(" methodAttributes.put (\"" + key + "\", bundle);");
pw.println(" bundle = null;");
pw.println();
}
}
pw.println(" }");
// ---- Constructor Attributes
pw.println(" private void initConstructorAttributes () {");
pw.println(" java.util.Set attrs = null;");
pw.println(" java.util.List bundle = null;");
JavaMethod[] constructors = javaClass.getMethods();
for (int i = 0; i < constructors.length; i++) {
JavaMethod member = (JavaMethod) constructors[i];
if (member.isConstructor() && member.getTags().length > 0) {
StringBuffer sb = new StringBuffer();
sb.append("(");
sb.append(getParameterTypes(member.getParameters()));
sb.append(")");
String key = sb.toString();
pw.println(" bundle = new java.util.ArrayList ();");
pw.println(" attrs = new java.util.HashSet ();");
addExpressions(member.getTags(), null, pw, "attrs", sourceFile);
pw.println(" bundle.add (attrs);");
pw.println(" attrs = null;");
JavaParameter[] parameters = member.getParameters();
for (int j = 0; j < parameters.length; j++) {
JavaParameter parameter = (JavaParameter) parameters[j];
pw.println(" attrs = new java.util.HashSet ();");
addExpressions(member.getTags(), parameter.getName(), pw, "attrs", sourceFile);
pw.println(" bundle.add (attrs);");
pw.println(" attrs = null;");
}
pw.println(" constructorAttributes.put (\"" + key + "\", bundle);");
pw.println(" bundle = null;");
pw.println();
}
}
pw.println(" }");
}
pw.println("}");
pw.close();
} catch (Exception e) {
pw.close();
destFile.delete();
throw e;
}
}
Example 35
Project: jaxb2-maven-plugin-master File: AbstractXsdGeneratorMojo.java View source code |
/**
* <p>The SchemaGenerator does not support directories as arguments, implying we must resolve source
* files in the compilation unit. This fact is shown when supplying a directory argument as source, when
* the tool emits:
* <blockquote>Caused by: java.lang.IllegalArgumentException: directories not supported</blockquote></p>
* <p>There seems to be two ways of adding sources to the SchemaGen tool:</p>
* <dl>
* <dt>1. <strong>Java Source</strong> files</dt>
* <dd>Define the relative paths to source files, calculated from the System.property {@code user.dir}
* (i.e. <strong>not</strong> the Maven {@code basedir} property) on the form
* {@code src/main/java/se/west/something/SomeClass.java}.<br/>
* <em>Sample</em>: {@code javac -d . .
* ./github_jaxb2_plugin/src/it/schemagen-main/src/main/java/se/west/gnat/Foo.java}</dd>
* <dt>2. <strong>Bytecode</strong> files</dt>
* <dd>Define the {@code CLASSPATH} to point to build output directories (such as target/classes), and then
* use package notation arguments on the form {@code se.west.something.SomeClass}.<br/>
* <em>Sample</em>: {@code schemagen -d . -classpath brat se.west.gnat.Foo}</dd>
* </dl>
* <p>The jaxb2-maven-plugin uses these two methods in the order given</p>
*
* @param sources The compiled sources (as calculated from the local project's
* source paths, {@code getSources()}).
* @return A sorted List holding all sources to be used by the SchemaGenerator. According to the SchemaGenerator
* documentation, the order in which the source arguments are provided is irrelevant.
* The sources are to be rendered as the final (open-ended) argument to the schemagen execution.
* @see #getSources()
*/
private List<String> getSchemaGeneratorSourceFiles(final List<URL> sources) throws IOException, MojoExecutionException {
final SortedMap<String, String> className2SourcePath = new TreeMap<String, String>();
final File baseDir = getProject().getBasedir();
final File userDir = new File(System.getProperty("user.dir"));
final String encoding = getEncoding(true);
// 1) Find/add all sources available in the compilation unit.
for (URL current : sources) {
final File sourceCodeFile = FileSystemUtilities.getFileFor(current, encoding);
// Calculate the relative path for the current source
final String relativePath = FileSystemUtilities.relativize(FileSystemUtilities.getCanonicalPath(sourceCodeFile), userDir);
if (getLog().isDebugEnabled()) {
getLog().debug("SourceCodeFile [" + FileSystemUtilities.getCanonicalPath(sourceCodeFile) + "] and userDir [" + FileSystemUtilities.getCanonicalPath(userDir) + "] ==> relativePath: " + relativePath + ". (baseDir: " + FileSystemUtilities.getCanonicalPath(baseDir) + "]");
}
// Find the Java class(es) within the source.
final JavaProjectBuilder builder = new JavaProjectBuilder();
builder.setEncoding(encoding);
//
if (sourceCodeFile.getName().trim().equalsIgnoreCase(PACKAGE_INFO_FILENAME)) {
// For some reason, QDox requires the package-info.java to be added as a URL instead of a File.
builder.addSource(current);
final Collection<JavaPackage> packages = builder.getPackages();
if (packages.size() != 1) {
throw new MojoExecutionException("Exactly one package should be present in file [" + sourceCodeFile.getPath() + "]");
}
// Make the key indicate that this is the package-info.java file.
final JavaPackage javaPackage = packages.iterator().next();
className2SourcePath.put("package-info for (" + javaPackage.getName() + ")", relativePath);
continue;
}
// This is not a package-info.java file, so QDox lets us add this as a File.
builder.addSource(sourceCodeFile);
// Map any found FQCN to the relativized path of its source file.
for (JavaSource currentJavaSource : builder.getSources()) {
for (JavaClass currentJavaClass : currentJavaSource.getClasses()) {
final String className = currentJavaClass.getFullyQualifiedName();
if (className2SourcePath.containsKey(className)) {
if (getLog().isWarnEnabled()) {
getLog().warn("Already mapped. Source class [" + className + "] within [" + className2SourcePath.get(className) + "]. Not overwriting with [" + relativePath + "]");
}
} else {
className2SourcePath.put(className, relativePath);
}
}
}
}
if (getLog().isDebugEnabled()) {
final int size = className2SourcePath.size();
getLog().debug("[ClassName-2-SourcePath Map (size: " + size + ")] ...");
int i = 0;
for (Map.Entry<String, String> current : className2SourcePath.entrySet()) {
getLog().debug(" " + (++i) + "/" + size + ": [" + current.getKey() + "]: " + current.getValue());
}
getLog().debug("... End [ClassName-2-SourcePath Map]");
}
// Sort the source paths and place them first in the argument array
final ArrayList<String> toReturn = new ArrayList<String>(className2SourcePath.values());
Collections.sort(toReturn);
// All Done.
return toReturn;
}
Example 36
Project: maven-plugin-tools-master File: JavaJavadocMojoDescriptorExtractor.java View source code |
// ----------------------------------------------------------------------
// Mojo descriptor creation from @tags
// ----------------------------------------------------------------------
/**
* @param javaClass not null
* @return a mojo descriptor
* @throws InvalidPluginDescriptorException if any
*/
protected MojoDescriptor createMojoDescriptor(JavaClass javaClass) throws InvalidPluginDescriptorException {
ExtendedMojoDescriptor mojoDescriptor = new ExtendedMojoDescriptor();
mojoDescriptor.setLanguage("java");
mojoDescriptor.setImplementation(javaClass.getFullyQualifiedName());
mojoDescriptor.setDescription(javaClass.getComment());
// ----------------------------------------------------------------------
// Mojo annotations in alphabetical order
// ----------------------------------------------------------------------
// Aggregator flag
DocletTag aggregator = findInClassHierarchy(javaClass, JavadocMojoAnnotation.AGGREGATOR);
if (aggregator != null) {
mojoDescriptor.setAggregator(true);
}
// Configurator hint
DocletTag configurator = findInClassHierarchy(javaClass, JavadocMojoAnnotation.CONFIGURATOR);
if (configurator != null) {
mojoDescriptor.setComponentConfigurator(configurator.getValue());
}
// Additional phase to execute first
DocletTag execute = findInClassHierarchy(javaClass, JavadocMojoAnnotation.EXECUTE);
if (execute != null) {
String executePhase = execute.getNamedParameter(JavadocMojoAnnotation.EXECUTE_PHASE);
String executeGoal = execute.getNamedParameter(JavadocMojoAnnotation.EXECUTE_GOAL);
if (executePhase == null && executeGoal == null) {
throw new InvalidPluginDescriptorException(javaClass.getFullyQualifiedName() + ": @execute tag requires either a 'phase' or 'goal' parameter");
} else if (executePhase != null && executeGoal != null) {
throw new InvalidPluginDescriptorException(javaClass.getFullyQualifiedName() + ": @execute tag can have only one of a 'phase' or 'goal' parameter");
}
mojoDescriptor.setExecutePhase(executePhase);
mojoDescriptor.setExecuteGoal(executeGoal);
String lifecycle = execute.getNamedParameter(JavadocMojoAnnotation.EXECUTE_LIFECYCLE);
if (lifecycle != null) {
mojoDescriptor.setExecuteLifecycle(lifecycle);
if (mojoDescriptor.getExecuteGoal() != null) {
throw new InvalidPluginDescriptorException(javaClass.getFullyQualifiedName() + ": @execute lifecycle requires a phase instead of a goal");
}
}
}
// Goal name
DocletTag goal = findInClassHierarchy(javaClass, JavadocMojoAnnotation.GOAL);
if (goal != null) {
mojoDescriptor.setGoal(goal.getValue());
}
// inheritByDefault flag
boolean value = getBooleanTagValue(javaClass, JavadocMojoAnnotation.INHERIT_BY_DEFAULT, mojoDescriptor.isInheritedByDefault());
mojoDescriptor.setInheritedByDefault(value);
// instantiationStrategy
DocletTag tag = findInClassHierarchy(javaClass, JavadocMojoAnnotation.INSTANTIATION_STRATEGY);
if (tag != null) {
mojoDescriptor.setInstantiationStrategy(tag.getValue());
}
// executionStrategy (and deprecated @attainAlways)
tag = findInClassHierarchy(javaClass, JavadocMojoAnnotation.MULTI_EXECUTION_STRATEGY);
if (tag != null) {
getLogger().warn("@" + JavadocMojoAnnotation.MULTI_EXECUTION_STRATEGY + " in " + javaClass.getFullyQualifiedName() + " is deprecated: please use '@" + JavadocMojoAnnotation.EXECUTION_STATEGY + " always' instead.");
mojoDescriptor.setExecutionStrategy(MojoDescriptor.MULTI_PASS_EXEC_STRATEGY);
} else {
mojoDescriptor.setExecutionStrategy(MojoDescriptor.SINGLE_PASS_EXEC_STRATEGY);
}
tag = findInClassHierarchy(javaClass, JavadocMojoAnnotation.EXECUTION_STATEGY);
if (tag != null) {
mojoDescriptor.setExecutionStrategy(tag.getValue());
}
// Phase name
DocletTag phase = findInClassHierarchy(javaClass, JavadocMojoAnnotation.PHASE);
if (phase != null) {
mojoDescriptor.setPhase(phase.getValue());
}
// Dependency resolution flag
DocletTag requiresDependencyResolution = findInClassHierarchy(javaClass, JavadocMojoAnnotation.REQUIRES_DEPENDENCY_RESOLUTION);
if (requiresDependencyResolution != null) {
String v = requiresDependencyResolution.getValue();
if (StringUtils.isEmpty(v)) {
v = "runtime";
}
mojoDescriptor.setDependencyResolutionRequired(v);
}
// Dependency collection flag
DocletTag requiresDependencyCollection = findInClassHierarchy(javaClass, JavadocMojoAnnotation.REQUIRES_DEPENDENCY_COLLECTION);
if (requiresDependencyCollection != null) {
String v = requiresDependencyCollection.getValue();
if (StringUtils.isEmpty(v)) {
v = "runtime";
}
mojoDescriptor.setDependencyCollectionRequired(v);
}
// requiresDirectInvocation flag
value = getBooleanTagValue(javaClass, JavadocMojoAnnotation.REQUIRES_DIRECT_INVOCATION, mojoDescriptor.isDirectInvocationOnly());
mojoDescriptor.setDirectInvocationOnly(value);
// Online flag
value = getBooleanTagValue(javaClass, JavadocMojoAnnotation.REQUIRES_ONLINE, mojoDescriptor.isOnlineRequired());
mojoDescriptor.setOnlineRequired(value);
// Project flag
value = getBooleanTagValue(javaClass, JavadocMojoAnnotation.REQUIRES_PROJECT, mojoDescriptor.isProjectRequired());
mojoDescriptor.setProjectRequired(value);
// requiresReports flag
value = getBooleanTagValue(javaClass, JavadocMojoAnnotation.REQUIRES_REPORTS, mojoDescriptor.isRequiresReports());
mojoDescriptor.setRequiresReports(value);
// ----------------------------------------------------------------------
// Javadoc annotations in alphabetical order
// ----------------------------------------------------------------------
// Deprecation hint
DocletTag deprecated = javaClass.getTagByName(JavadocMojoAnnotation.DEPRECATED);
if (deprecated != null) {
mojoDescriptor.setDeprecated(deprecated.getValue());
}
// What version it was introduced in
DocletTag since = findInClassHierarchy(javaClass, JavadocMojoAnnotation.SINCE);
if (since != null) {
mojoDescriptor.setSince(since.getValue());
}
// Thread-safe mojo
value = getBooleanTagValue(javaClass, JavadocMojoAnnotation.THREAD_SAFE, true, mojoDescriptor.isThreadSafe());
mojoDescriptor.setThreadSafe(value);
extractParameters(mojoDescriptor, javaClass);
return mojoDescriptor;
}
Example 37
Project: cocoon-master File: SitemapTask.java View source code |
/**
* Determine the type of the class
*/
private String classType(JavaClass clazz) {
if (clazz.isA(GENERATOR)) {
return "generator";
} else if (clazz.isA(TRANSFORMER)) {
return "transformer";
} else if (clazz.isA(READER)) {
return "reader";
} else if (clazz.isA(SERIALIZER)) {
return "serializer";
} else if (clazz.isA(ACTION)) {
return "action";
} else if (clazz.isA(MATCHER)) {
return "matcher";
} else if (clazz.isA(SELECTOR)) {
return "selector";
} else if (clazz.isA(PIPELINE)) {
return "pipe";
// Should qdox resolve recursively? ie: HTMLGenerator isA ServiceableGenerator isA AbstractGenerator isA Generator
} else if (clazz.getPackage().equals("org.apache.cocoon.generation") && (clazz.isA("Generator") || clazz.isA("ServiceableGenerator"))) {
return "generator";
} else if (clazz.isA("org.apache.cocoon.generation.ServiceableGenerator")) {
return "generator";
} else if (clazz.getPackage().equals("org.apache.cocoon.transformation") && clazz.isA("Transformer")) {
return "transformer";
} else if (clazz.getPackage().equals("org.apache.cocoon.reading") && clazz.isA("Reader")) {
return "reader";
} else if (clazz.getPackage().equals("org.apache.cocoon.serialization") && clazz.isA("Serializer")) {
return "serializer";
} else if (clazz.getPackage().equals("org.apache.cocoon.acting") && clazz.isA("Action")) {
return "action";
} else if (clazz.getPackage().equals("org.apache.cocoon.matching") && clazz.isA("Matcher")) {
return "matcher";
} else if (clazz.getPackage().equals("org.apache.cocoon.selection") && clazz.isA("Selector")) {
return "selector";
} else if (clazz.getPackage().equals("org.apache.cocoon.components.pipeline") && clazz.isA("ProcessingPipeline")) {
return "pipe";
} else {
return null;
}
}
Example 38
Project: tzatziki-master File: GrammarParserStatisticsListener.java View source code |
@Override
public void exitingClass(JavaClass klazz) {
classesParsed++;
}
Example 39
Project: RoboBuggy-master File: QDox.java View source code |
JavaClass getClassByName(String className) {
return javaDocBuilder.getClassByName(className);
}