List of usage examples for java.lang Class getPackage
public Package getPackage()
From source file:org.debux.webmotion.server.convention.DefaultConventionScan.java
/** * Scan the controllers by convention.//from w w w. ja v a 2 s . c om */ public List<ActionRule> scanControllers(Mapping mapping) { Collection<Class<?>> controllers = ReflectionUtils.getClassesBySuperClass(ConventionController.class); List<ActionRule> rules = new ArrayList<ActionRule>(controllers.size()); for (Class<?> controller : controllers) { Method[] methods = controller.getMethods(); for (Method method : methods) { Class<?> declaringClass = method.getDeclaringClass(); if (!declaringClass.equals(Object.class) && !declaringClass.equals(WebMotionController.class)) { ActionRule rule = new ActionRule(); rule.setMapping(mapping); rule.setLine(-1); rules.add(rule); String className = controller.getName(); String methodName = method.getName(); // Create action Action action = new Action(); action.setFullName(className + "." + methodName); action.setType(Action.Type.ACTION); rule.setAction(action); // Search http method String httpMethod = "*"; if (methodName.startsWith("create")) { httpMethod = HttpContext.METHOD_PUT; methodName = methodName.replaceFirst("create", ""); } else if (methodName.startsWith("get")) { httpMethod = HttpContext.METHOD_GET; methodName = methodName.replaceFirst("get", ""); } else if (methodName.startsWith("delete")) { httpMethod = HttpContext.METHOD_DELETE; methodName = methodName.replaceFirst("delete", ""); } else if (methodName.startsWith("update")) { httpMethod = HttpContext.METHOD_POST; methodName = methodName.replaceFirst("update", ""); } rule.setMethods(Arrays.asList(httpMethod)); // Create path List<FragmentUrl> url = new ArrayList<FragmentUrl>(); String simpleClassName = controller.getSimpleName(); Package controllerPackage = controller.getPackage(); if (controllerPackage != null) { String packageName = controllerPackage.getName(); String subPackageName = StringUtils.substringAfterLast(packageName, "."); if (!StringUtils.startsWithIgnoreCase(simpleClassName, subPackageName)) { url.addAll(createFragmentUrlList(subPackageName)); } } url.addAll(createFragmentUrlList(simpleClassName)); if (methodName.length() != 0) { url.addAll(createFragmentUrlList(methodName)); } rule.setRuleUrl(url); } } } return rules; }
From source file:es.javocsoft.android.lib.toolbox.ToolBox.java
/** * Deletes a application desktop shortcut icon. * * Note://from w w w .j a v a 2 s. c o m * Manual way. * * This method need two additional permissions in the application: * * <code> * <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /> * </code> * * @param context The application context. * @param appClass Shortcut's activity class. */ public static void application_shortcutRemove_method2(Context context, Class appClass, String appName) { Intent intent = new Intent(); String oldShortcutUri = "#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10200000;package=" + appClass.getPackage().getName() + ";component=" + appClass.getPackage().getName() + "/." + appClass.getSimpleName() + ";end"; try { Intent altShortcutIntent = Intent.parseUri(oldShortcutUri, 0); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, altShortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName); //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } catch (URISyntaxException e) { } intent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT"); context.sendBroadcast(intent); }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates the Java source file that is a helper of {@link SPPersisterHelper}. * These helpers are not true {@link SPPersisterHelper}s because they only do * part of a helper's job. They also do not implement the interface because nothing * outside of the {@link SPPersisterHelper}s should be using them directly. * // w ww . ja v a 2s.c om * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param constructorImports * The {@link Set} of imports that the generated persister helper * requires for calling the {@link Constructor} annotated * constructor. * @param constructorParameters * The {@link List} of {@link ConstructorParameterObject}s that * contain information about what the parameter should be used * for. * @param propertiesToAccess * The {@link Map} of getter method names of persistable * properties to its property type. * @param accessorAdditionalInfo * The {@link Multimap} of getter methods mapped to additional * properties a session {@link SPPersister} requires to convert * the getter's returned value from a complex to basic * persistable type. * @param mutatorImports * The {@link Multimap} of setter methods to imports that the * generated persister helper requires for calling the * {@link Mutator} annotated setters. * @param propertiesToMutate * The {@link Map} of setter method names of persistable * properties to its property type. * @param mutatorExtraParameters * The {@link Multimap} of setter methods mapped to each of its * extra parameters (second parameter and onwards). * @param mutatorThrownTypes * The {@link Multimap} of {@link Exception}s thrown by each * persistable property setter. * @param propertiesToPersistOnlyIfNonNull * The {@link Set} of persistable properties that can only be * persisted if its value is not null. */ private void generateAbstractPersisterHelperFile(Class<? extends SPObject> visitedClass, Set<String> constructorImports, Map<String, Class<?>> propertiesToAccess, Multimap<String, String> accessorAdditionalInfo, Multimap<String, String> mutatorImports, Map<String, Class<?>> propertiesToMutate, Multimap<String, MutatorParameterObject> mutatorExtraParameters, Multimap<String, Class<? extends Exception>> mutatorThrownTypes, Set<String> propertiesToPersistOnlyIfNonNull) { try { final String helperPackage = visitedClass.getPackage().getName() + "." + PersisterHelperFinder.GENERATED_PACKAGE_NAME; final String simpleClassName = visitedClass.getSimpleName() + "PersisterHelper"; final Class<?> superclass = visitedClass.getSuperclass(); int tabs = 0; Filer f = environment.getFiler(); PrintWriter pw = new PrintWriter( f.createSourceFile(helperPackage + "." + simpleClassName).openOutputStream()); tabs++; final String commitPropertyMethod = generateCommitPropertyMethod(visitedClass, propertiesToMutate, mutatorExtraParameters, mutatorThrownTypes, tabs); final String findPropertyMethod = generateFindPropertyMethod(visitedClass, propertiesToAccess, accessorAdditionalInfo, tabs); final String persistObjectMethodHelper = generatePersistObjectMethodHelper(visitedClass, propertiesToAccess, propertiesToMutate, propertiesToPersistOnlyIfNonNull, tabs); final String getPersistedPropertiesMethod = generateGetPersistedPropertyListMethod(visitedClass, propertiesToMutate, tabs); tabs--; if (superclass == Object.class) { importedClassNames.add(AbstractSPPersisterHelper.class.getName()); } else { importedClassNames.add(PersisterHelperFinder.getPersisterHelperClassName(superclass.getName())); } final String generateImports = generateImports(visitedClass, constructorImports, mutatorImports); pw.print(generateWarning()); pw.print("\n"); pw.print(generateLicense()); pw.print("\n"); pw.print("package " + helperPackage + ";\n"); pw.print("\n"); pw.print(generateImports); pw.print("\n"); if (superclass == Object.class) { pw.print(String.format("public abstract class %s<%s extends %s> extends %s<%s> {\n", simpleClassName, TYPE_GENERIC_PARAMETER, visitedClass.getSimpleName(), AbstractSPPersisterHelper.class.getSimpleName(), TYPE_GENERIC_PARAMETER)); } else if (Modifier.isAbstract(superclass.getModifiers())) { pw.print(String.format("public abstract class %s<%s extends %s> extends %s<%s> {\n", simpleClassName, TYPE_GENERIC_PARAMETER, visitedClass.getSimpleName(), superclass.getSimpleName() + "PersisterHelper", TYPE_GENERIC_PARAMETER)); } else { pw.print(String.format("public abstract class %s<%s extends %s> extends %s {\n", simpleClassName, TYPE_GENERIC_PARAMETER, visitedClass.getSimpleName() + "PersisterHelper", superclass.getName())); } pw.print("\n"); pw.print(commitPropertyMethod); pw.print("\n"); pw.print(findPropertyMethod); pw.print("\n"); pw.print(persistObjectMethodHelper); pw.print("\n"); pw.print(getPersistedPropertiesMethod); pw.print("\n"); pw.print("}\n"); pw.close(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates the Java source file for an {@link SPPersisterHelper} class * that is to be used by a session {@link SPPersister} or workspace * persister listener. This generated persister helper class should deal * with creating new objects and applying persisted properties to a given * {@link SPObject}, or persisting objects and properties from an * {@link SPObject} to an {@link SPPersister}. * /*from ww w. java2 s . com*/ * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param constructorImports * The {@link Set} of imports that the generated persister helper * requires for calling the {@link Constructor} annotated * constructor. * @param constructorParameters * The {@link List} of {@link ConstructorParameterObject}s that * contain information about what the parameter should be used * for. * @param propertiesToAccess * The {@link Map} of getter method names of persistable * properties to its property type. * @param accessorAdditionalInfo * The {@link Multimap} of getter methods mapped to additional * properties a session {@link SPPersister} requires to convert * the getter's returned value from a complex to basic * persistable type. * @param mutatorImports * The {@link Multimap} of setter methods to imports that the * generated persister helper requires for calling the * {@link Mutator} annotated setters. * @param propertiesToMutate * The {@link Map} of setter method names of persistable * properties to its property type. * @param mutatorExtraParameters * The {@link Multimap} of setter methods mapped to each of its * extra parameters (second parameter and onwards). * @param mutatorThrownTypes * The {@link Multimap} of {@link Exception}s thrown by each * persistable property setter. * @param propertiesToPersistOnlyIfNonNull * The {@link Set} of persistable properties that can only be * persisted if its value is not null. */ private void generatePersisterHelperFile(Class<? extends SPObject> visitedClass, Set<String> constructorImports, List<ConstructorParameterObject> constructorParameters, Map<String, Class<?>> propertiesToAccess, Multimap<String, String> accessorAdditionalInfo, Multimap<String, String> mutatorImports, Map<String, Class<?>> propertiesToMutate, Multimap<String, MutatorParameterObject> mutatorExtraParameters, Multimap<String, Class<? extends Exception>> mutatorThrownTypes, Set<String> propertiesToPersistOnlyIfNonNull) { try { final String helperPackage = visitedClass.getPackage().getName() + "." + PersisterHelperFinder.GENERATED_PACKAGE_NAME; final String simpleClassName = visitedClass.getSimpleName() + "PersisterHelper"; final Class<?> superclass = visitedClass.getSuperclass(); int tabs = 0; Filer f = environment.getFiler(); PrintWriter pw = new PrintWriter( f.createSourceFile(helperPackage + "." + simpleClassName).openOutputStream()); tabs++; final String commitObjectMethod = generateCommitObjectMethod(visitedClass, constructorParameters, tabs); final String commitPropertyMethod = generateCommitPropertyMethod(visitedClass, propertiesToMutate, mutatorExtraParameters, mutatorThrownTypes, tabs); final String findPropertyMethod = generateFindPropertyMethod(visitedClass, propertiesToAccess, accessorAdditionalInfo, tabs); final String persistObjectMethod = generatePersistObjectMethod(visitedClass, constructorParameters, propertiesToAccess, propertiesToPersistOnlyIfNonNull, tabs); final String PersistObjectMethodHelper = generatePersistObjectMethodHelper(visitedClass, propertiesToAccess, propertiesToMutate, propertiesToPersistOnlyIfNonNull, tabs); final String getPersistedPropertiesMethod = generateGetPersistedPropertyListMethod(visitedClass, propertiesToMutate, tabs); tabs--; if (superclass == Object.class) { importedClassNames.add(AbstractSPPersisterHelper.class.getName()); } else { importedClassNames.add(PersisterHelperFinder.getPersisterHelperClassName(superclass.getName())); } final String imports = generateImports(visitedClass, constructorImports, mutatorImports); pw.print(generateWarning()); pw.print("\n"); pw.print(generateLicense()); pw.print("\n"); pw.print("package " + helperPackage + ";\n"); pw.print("\n"); pw.print(imports); pw.print("\n"); if (superclass == Object.class) { pw.print(String.format("public class %s extends %s<%s> {\n", simpleClassName, AbstractSPPersisterHelper.class.getSimpleName(), visitedClass.getSimpleName())); } else if (Modifier.isAbstract(superclass.getModifiers())) { pw.print(String.format("public class %s extends %s<%s> {\n", simpleClassName, superclass.getSimpleName() + "PersisterHelper", visitedClass.getSimpleName())); } else { pw.print(String.format("public class %s extends %s {\n", simpleClassName, superclass.getSimpleName() + "PersisterHelper")); } pw.print("\n"); pw.print(commitObjectMethod); pw.print("\n"); pw.print(commitPropertyMethod); pw.print("\n"); pw.print(findPropertyMethod); pw.print("\n"); pw.print(persistObjectMethod); pw.print("\n"); pw.print(PersistObjectMethodHelper); pw.print("\n"); pw.print(getPersistedPropertiesMethod); pw.print("\n"); pw.print("}\n"); pw.close(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.struts2.convention.PackageBasedActionConfigBuilder.java
@SuppressWarnings("unchecked") protected void buildConfiguration(Set<Class> classes) { Map<String, PackageConfig.Builder> packageConfigs = new HashMap<String, PackageConfig.Builder>(); for (Class<?> actionClass : classes) { Actions actionsAnnotation = actionClass.getAnnotation(Actions.class); Action actionAnnotation = actionClass.getAnnotation(Action.class); // Skip classes that can't be instantiated if (cannotInstantiate(actionClass)) { if (LOG.isTraceEnabled()) LOG.trace("Class [#0] did not pass the instantiation test and will be ignored", actionClass.getName()); continue; }//from w w w .jav a 2 s . co m if (eagerLoading) { // Tell the ObjectFactory about this class try { objectFactory.getClassInstance(actionClass.getName()); } catch (ClassNotFoundException e) { if (LOG.isErrorEnabled()) LOG.error("Object Factory was unable to load class [#0]", e, actionClass.getName()); throw new StrutsException("Object Factory was unable to load class " + actionClass.getName(), e); } } // Determine the action package String actionPackage = actionClass.getPackage().getName(); if (LOG.isDebugEnabled()) { LOG.debug("Processing class [#0] in package [#1]", actionClass.getName(), actionPackage); } // Determine the default namespace and action name List<String> namespaces = determineActionNamespace(actionClass); for (String namespace : namespaces) { String defaultActionName = determineActionName(actionClass); PackageConfig.Builder defaultPackageConfig = getPackageConfig(packageConfigs, namespace, actionPackage, actionClass, null); // Verify that the annotations have no errors and also determine if the default action // configuration should still be built or not. Map<String, List<Action>> map = getActionAnnotations(actionClass); Set<String> actionNames = new HashSet<String>(); boolean hasDefaultMethod = ReflectionTools.containsMethod(actionClass, DEFAULT_METHOD); if (!map.containsKey(DEFAULT_METHOD) && hasDefaultMethod && actionAnnotation == null && actionsAnnotation == null && (alwaysMapExecute || map.isEmpty())) { boolean found = false; for (String method : map.keySet()) { List<Action> actions = map.get(method); for (Action action : actions) { // Check if there are duplicate action names in the annotations. String actionName = action.value().equals(Action.DEFAULT_VALUE) ? defaultActionName : action.value(); if (actionNames.contains(actionName)) { throw new ConfigurationException("The action class [" + actionClass + "] contains two methods with an action name annotation whose value " + "is the same (they both might be empty as well)."); } else { actionNames.add(actionName); } // Check this annotation is the default action if (action.value().equals(Action.DEFAULT_VALUE)) { found = true; } } } // Build the default if (!found) { createActionConfig(defaultPackageConfig, actionClass, defaultActionName, DEFAULT_METHOD, null); } } // Build the actions for the annotations for (String method : map.keySet()) { List<Action> actions = map.get(method); for (Action action : actions) { PackageConfig.Builder pkgCfg = defaultPackageConfig; if (action.value().contains("/") && !slashesInActionNames) { pkgCfg = getPackageConfig(packageConfigs, namespace, actionPackage, actionClass, action); } createActionConfig(pkgCfg, actionClass, defaultActionName, method, action); } } // some actions will not have any @Action or a default method, like the rest actions // where the action mapper is the one that finds the right method at runtime if (map.isEmpty() && mapAllMatches && actionAnnotation == null && actionsAnnotation == null) { createActionConfig(defaultPackageConfig, actionClass, defaultActionName, null, actionAnnotation); } //if there are @Actions or @Action at the class level, create the mappings for them String methodName = hasDefaultMethod ? DEFAULT_METHOD : null; if (actionsAnnotation != null) { List<Action> actionAnnotations = checkActionsAnnotation(actionsAnnotation); for (Action actionAnnotation2 : actionAnnotations) createActionConfig(defaultPackageConfig, actionClass, defaultActionName, methodName, actionAnnotation2); } else if (actionAnnotation != null) createActionConfig(defaultPackageConfig, actionClass, defaultActionName, methodName, actionAnnotation); } } buildIndexActions(packageConfigs); // Add the new actions to the configuration Set<String> packageNames = packageConfigs.keySet(); for (String packageName : packageNames) { configuration.addPackageConfig(packageName, packageConfigs.get(packageName).build()); } }
From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java
/** * Determines the namespace(s) for the action based on the action class. If there is a {@link Namespace} * annotation on the class (including parent classes) or on the package that the class is in, than * it is used. Otherwise, the Java package name that the class is in is used in conjunction with * either the <b>struts.convention.action.packages</b> or <b>struts.convention.package.locators</b> * configuration values. These are used to determine which part of the Java package name should * be converted into the namespace for the XWork PackageConfig. * * @param actionClass The action class.// w ww .j a v a 2s. c o m * @return The namespace or an empty string. */ protected List<String> determineActionNamespace(Class<?> actionClass) { List<String> namespaces = new ArrayList<String>(); // Check if there is a class or package level annotation for the namespace //single namespace Namespace namespaceAnnotation = AnnotationTools.findAnnotation(actionClass, Namespace.class); if (namespaceAnnotation != null) { if (LOG.isTraceEnabled()) { LOG.trace("Using non-default action namespace from Namespace annotation of [#0]", namespaceAnnotation.value()); } namespaces.add(namespaceAnnotation.value()); } //multiple annotations Namespaces namespacesAnnotation = AnnotationTools.findAnnotation(actionClass, Namespaces.class); if (namespacesAnnotation != null) { if (LOG.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); for (Namespace namespace : namespacesAnnotation.value()) sb.append(namespace.value()).append(","); sb.deleteCharAt(sb.length() - 1); LOG.trace("Using non-default action namespaces from Namespaces annotation of [#0]", sb.toString()); } for (Namespace namespace : namespacesAnnotation.value()) namespaces.add(namespace.value()); } //don't use default if there are annotations if (!namespaces.isEmpty()) return namespaces; String pkg = actionClass.getPackage().getName(); String pkgPart = null; if (actionPackages != null) { for (String actionPackage : actionPackages) { if (pkg.startsWith(actionPackage)) { pkgPart = actionClass.getName().substring(actionPackage.length() + 1); } } } if (pkgPart == null && packageLocators != null) { for (String packageLocator : packageLocators) { int index = pkg.lastIndexOf(packageLocator); // This ensures that the match is at the end, beginning or has a dot on each side of it if (index >= 0 && (index + packageLocator.length() == pkg.length() || index == 0 || (pkg.charAt(index - 1) == '.' && pkg.charAt(index + packageLocator.length()) == '.'))) { pkgPart = actionClass.getName().substring(index + packageLocator.length() + 1); } } } if (pkgPart != null) { final int indexOfDot = pkgPart.lastIndexOf('.'); if (indexOfDot >= 0) { String convertedNamespace = actionNameBuilder.build(pkgPart.substring(0, indexOfDot)); namespaces.add("/" + convertedNamespace.replace('.', '/')); return namespaces; } } namespaces.add(""); return namespaces; }
From source file:org.apache.struts2.convention.PackageBasedActionConfigBuilder.java
/** * Determines the namespace(s) for the action based on the action class. If there is a {@link Namespace} * annotation on the class (including parent classes) or on the package that the class is in, than * it is used. Otherwise, the Java package name that the class is in is used in conjunction with * either the <b>struts.convention.action.packages</b> or <b>struts.convention.package.locators</b> * configuration values. These are used to determine which part of the Java package name should * be converted into the namespace for the XWork PackageConfig. * * @param actionClass The action class.//from w ww . j a v a 2 s .c o m * @return The namespace or an empty string. */ protected List<String> determineActionNamespace(Class<?> actionClass) { List<String> namespaces = new ArrayList<String>(); // Check if there is a class or package level annotation for the namespace //single namespace Namespace namespaceAnnotation = AnnotationUtils.findAnnotation(actionClass, Namespace.class); if (namespaceAnnotation != null) { if (LOG.isTraceEnabled()) { LOG.trace("Using non-default action namespace from Namespace annotation of [#0]", namespaceAnnotation.value()); } namespaces.add(namespaceAnnotation.value()); } //multiple annotations Namespaces namespacesAnnotation = AnnotationUtils.findAnnotation(actionClass, Namespaces.class); if (namespacesAnnotation != null) { if (LOG.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); for (Namespace namespace : namespacesAnnotation.value()) sb.append(namespace.value()).append(","); sb.deleteCharAt(sb.length() - 1); LOG.trace("Using non-default action namespaces from Namespaces annotation of [#0]", sb.toString()); } for (Namespace namespace : namespacesAnnotation.value()) namespaces.add(namespace.value()); } //don't use default if there are annotations if (!namespaces.isEmpty()) return namespaces; String pkg = actionClass.getPackage().getName(); String pkgPart = null; if (actionPackages != null) { for (String actionPackage : actionPackages) { if (pkg.startsWith(actionPackage)) { pkgPart = actionClass.getName().substring(actionPackage.length() + 1); } } } if (pkgPart == null && packageLocators != null) { for (String packageLocator : packageLocators) { // check subpackage and not a part of package name, eg. actions -> my.actions.transactions - WW-3803 int index = pkg.lastIndexOf("." + packageLocator + "."); // This ensures that the match is at the end, beginning or has a dot on each side of it if (index >= 0 && (index + packageLocator.length() == pkg.length() || index == 0 || (pkg.charAt(index) == '.' && pkg.charAt(index + 1 + packageLocator.length()) == '.'))) { pkgPart = actionClass.getName().substring(index + packageLocator.length() + 2); } } } if (pkgPart != null) { final int indexOfDot = pkgPart.lastIndexOf('.'); if (indexOfDot >= 0) { String convertedNamespace = actionNameBuilder.build(pkgPart.substring(0, indexOfDot)); namespaces.add("/" + convertedNamespace.replace('.', '/')); return namespaces; } } namespaces.add(""); return namespaces; }
From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java
/** * Build the ClassInfo representation for a Class. * /*w w w .j av a2s . c om*/ * @param type * the Class to introspect * @return ClassInfo build from the Class */ public ClassInfo buildClassInfo(final Class<?> type) { if (type == null) { String message = "Argument type must not be null."; LOG.warn(message); throw new IllegalArgumentException(message); } if (!isDescribeable(type)) { if (LOG.isDebugEnabled()) { String message = "Class: " + type + " cannot be described using this builder."; LOG.debug(message); } return null; } if (LOG.isInfoEnabled()) { LOG.info("Now starting to build ClassInfo for: " + type); } ClassInfo classInfo = createClassInfo(javaNaming.getClassName(type)); JaxbClassNature jaxbClassNature = new JaxbClassNature(classInfo); jaxbClassNature.setType(type); jaxbClassNature.setSupertype(type.getSuperclass()); jaxbClassNature.setInterfaces(type.getInterfaces()); jaxbClassNature.setHasPublicEmptyConstructor(hasPublicEmptyConstructor(type)); Annotation[] unprocessedClassAnnotations = this.classAnnotationProcessingService .processAnnotations(jaxbClassNature, type.getAnnotations()); for (Field field : type.getDeclaredFields()) { if (LOG.isInfoEnabled()) { LOG.info("Now evaluating field: " + field); } if (isDescribeable(type, field)) { buildFieldInfo(classInfo, field); } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring field: " + field + " of type: " + type.getName() + " it is not useable for mapping."); } } } for (Method method : type.getDeclaredMethods()) { if (LOG.isInfoEnabled()) { LOG.info("Now evaluating method: " + method); } if (isDescribeable(type, method)) { buildFieldInfo(classInfo, method); } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring method: " + method + " of type: " + type.getName() + " it is not useable for mapping."); } } } PackageInfo pi = buildPackageInfo(type.getPackage()); classInfo.setPackageInfo(pi); if (LOG.isInfoEnabled()) { LOG.info("ClassInfo for: " + type + " build is: " + classInfo); } return classInfo; }
From source file:com.kjt.service.common.SoafwTesterMojo.java
/** * /*from w ww. j av a 2 s . c o m*/ * @param className */ private void appendTest(String className) { /** * ?? ?public * ?MojoExecutionException?????? */ try { Map<String, Integer> methodCnt = new HashMap<String, Integer>(); boolean hasmethod = false; Map<String, String> methodDefs = new HashMap<String, String>(); Class cls = cl.loadClass(className);// Class[] inters = cls.getInterfaces(); int len = 0; if (inters == null || (len = inters.length) == 0) { return; } for (int i = 0; i < len; i++) { Class interCls = inters[i]; this.getLog().info("@interface: " + interCls.getName()); String name = project.getName(); Method[] methods = null; if (name.endsWith("-dao")) { methods = interCls.getDeclaredMethods(); } else { methods = interCls.getMethods(); } int mlen = 0; if (methods != null && (mlen = methods.length) > 0) { StringBuffer methodBuf = new StringBuffer(); for (int m = 0; m < mlen; m++) { Method method = methods[m]; int modf = method.getModifiers(); if (modf == 1025) {// ?? hasmethod = true; /** * ??????Test ???=??+Test * ??:basedPath+File.separator * +src+File.separator+test+File.separator * +pkg+definesArray[i]+Test+.java */ if (methodCnt.containsKey(method.getName())) { methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1); } else { methodCnt.put(method.getName(), 0); } int cnt = methodCnt.get(method.getName()); addMethod(methodDefs, methodBuf, method, cnt); } } } } Class tstCls = cl.loadClass(className + "Test");// Method[] methods = tstCls.getDeclaredMethods(); len = methods == null ? 0 : methods.length; this.getLog().info("" + tstCls.getSimpleName() + "?" + len); /** * ??public */ for (int m = 0; m < len; m++) { Method method = methods[m]; SoaFwTest test = method.getAnnotation(SoaFwTest.class); if (test == null) { this.getLog() .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest"); continue; } String id = test.id(); if (methodDefs.containsKey(id)) { methodDefs.remove(id); } } if ((len = methodDefs.size()) == 0) { return; } String[] methodImpls = new String[len]; methodDefs.keySet().toArray(methodImpls); // TODO ??? this.getLog().info("???"); StringBuilder src = new StringBuilder(); String srcs = readTestSrc(className); int index = srcs.lastIndexOf("}"); this.getLog().info(srcs); this.getLog().info("lastIndexOf(}):" + index); String impls = srcs.substring(0, index - 1); src.append(impls); src.append("\n"); StringBuilder appends = new StringBuilder(); this.getLog().info("?"); for (int i = 0; i < len; i++) { String methodId = methodImpls[i]; String method = methodDefs.get(methodId); appends.append(method); appends.append("\n"); } src.append(appends.toString()); src.append("}"); Package pkg = tstCls.getPackage(); String pkgName = pkg.getName(); String pkgPath = pkgName.replace(".", File.separator); String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java"; String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath; write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString()); } catch (Exception e) { this.getLog().error(e); } catch (Error er) { this.getLog().error(er); } }
From source file:com.tower.service.test.SoafwTesterMojo.java
/** * //from w w w . ja va2 s.c o m * @param className * */ private void appendTest(String className) { /** * ?? ?public * ?MojoExecutionException?????? */ try { Map<String, Integer> methodCnt = new HashMap<String, Integer>(); boolean hasmethod = false; Map<String, String> methodDefs = new HashMap<String, String>(); Class cls = cl.loadClass(className);// Class[] inters = cls.getInterfaces(); int len = 0; if (inters == null || (len = inters.length) == 0) { return; } for (int i = 0; i < len; i++) { Class interCls = inters[i]; this.getLog().info("@interface: " + interCls.getName()); String name = project.getName(); Method[] methods = null; if (name.endsWith("-dao")) { methods = interCls.getDeclaredMethods(); } else { methods = interCls.getMethods(); } int mlen = 0; if (methods != null && (mlen = methods.length) > 0) { StringBuffer methodBuf = new StringBuffer(); for (int m = 0; m < mlen; m++) { Method method = methods[m]; int modf = method.getModifiers(); if (modf == 1025) {// ?? hasmethod = true; /** * ??????Test ???=??+Test * ??:basedPath+File.separator * +src+File.separator+test+File.separator * +pkg+definesArray[i]+Test+.java */ if (methodCnt.containsKey(method.getName())) { methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1); } else { methodCnt.put(method.getName(), 0); } int cnt = methodCnt.get(method.getName()); addMethod(methodDefs, methodBuf, method, cnt); } } } } Class tstCls = cl.loadClass(className + "Test");// Method[] methods = tstCls.getDeclaredMethods(); len = methods == null ? 0 : methods.length; this.getLog().info("" + tstCls.getSimpleName() + "?" + len); /** * ??public */ for (int m = 0; m < len; m++) { Method method = methods[m]; SoaFwTest test = method.getAnnotation(SoaFwTest.class); if (test == null) { this.getLog() .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest"); continue; } String id = test.id(); if (methodDefs.containsKey(id)) { methodDefs.remove(id); } } if ((len = methodDefs.size()) == 0) { return; } String[] methodImpls = new String[len]; methodDefs.keySet().toArray(methodImpls); // TODO ??? StringBuilder src = new StringBuilder(); String srcs = readTestSrc(className); int index = srcs.lastIndexOf("}"); // this.getLog().info(srcs); //this.getLog().info("lastIndexOf(}):" + index); String impls = srcs.substring(0, index - 1); src.append(impls); src.append("\n"); this.getLog().info("?: " + className + "Test"); StringBuilder appends = new StringBuilder(); this.getLog().info("?"); for (int i = 0; i < len; i++) { String methodId = methodImpls[i]; String method = methodDefs.get(methodId); appends.append(method); appends.append("\n"); } src.append(appends.toString()); src.append("}"); Package pkg = tstCls.getPackage(); String pkgName = pkg.getName(); String pkgPath = pkgName.replace(".", File.separator); String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java"; String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath; write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString()); } catch (Exception e) { this.getLog().error(e); } catch (Error er) { this.getLog().error(er); } }