List of usage examples for java.lang Class getPackage
public Package getPackage()
From source file:blue.lapis.pore.impl.event.PoreEventTest.java
@Test public void findUnimplementedEvents() throws IOException { Set<Class<?>> events = Sets.newLinkedHashSet(); for (ClassPath.ClassInfo info : PoreTests.getClassPath().getTopLevelClassesRecursive(BUKKIT_PACKAGE)) { try {/* w w w.j a v a2 s. c o m*/ Class<?> event = info.load(); if (Event.class.isAssignableFrom(event) && !Modifier.isAbstract(event.getModifiers())) { events.add(event); } } catch (Throwable e) { PoreTests.getLogger().warn("Failed to load {}", info, e); } } for (ClassPath.ClassInfo info : PoreTests.getClassPath().getTopLevelClassesRecursive(PORE_PACKAGE)) { Class<?> type; try { type = info.load(); if (!Event.class.isAssignableFrom(type)) { continue; } } catch (Throwable e) { PoreTests.getLogger().warn("Failed to load {}", info, e); continue; } events.remove(type.getSuperclass()); } if (!events.isEmpty()) { for (Class<?> event : events) { String bukkitPackage = StringUtils.removeStart(event.getPackage().getName(), BUKKIT_PACKAGE + '.'); PoreTests.getLogger().warn("{}: Pore{} is missing", bukkitPackage, event.getSimpleName()); } } }
From source file:org.kuali.rice.krad.util.LegacyDetector.java
/** * Determines whether the given class is loaded into OJB. Accesses the OJB metadata manager via reflection to avoid * compile-time dependency. If null is passed to this method, it will always return false. * * @param dataObjectClass the data object class which may be loaded by the legacy framework * @return true if the legacy data framework is present and has loaded the specified class, false otherwise *///from w ww . jav a 2 s.com public boolean isOjbLoadedClass(Class<?> dataObjectClass) { if (dataObjectClass == null) { return false; } // some OJB objects may come in as proxies, we need to clear the CGLIB portion of the generated class name // before we can check it properly String dataObjectClassName = dataObjectClass.getName() .replaceAll("\\$\\$EnhancerByCGLIB\\$\\$[0-9a-f]{0,8}", ""); try { dataObjectClass = Class.forName(dataObjectClassName); } catch (ClassNotFoundException ex) { LOG.warn("Unable to resolve converted class name: " + dataObjectClassName + " from original: " + dataObjectClass + " -- Using as is"); } Boolean isLegacyLoaded = legacyLoadedCache.get(dataObjectClass); if (isLegacyLoaded == null) { if (dataObjectClass.getPackage() != null && StringUtils.startsWith(dataObjectClass.getPackage().getName(), "org.apache.ojb.")) { isLegacyLoaded = Boolean.TRUE; } else { try { Class<?> metadataManager = Class.forName(OJB_METADATA_MANAGER_CLASS, false, ClassUtils.getDefaultClassLoader()); // determine, via reflection, whether the legacy persistence layer has loaded the given class Object metadataManagerInstance = ReflectionUtils.invokeViaReflection(metadataManager, (Object) null, "getInstance", null); Validate.notNull(metadataManagerInstance, "unable to obtain " + OJB_METADATA_MANAGER_CLASS + " instance"); Object descriptorRepository = ReflectionUtils.invokeViaReflection(metadataManagerInstance, "getGlobalRepository", null); Validate.notNull(descriptorRepository, "unable to invoke legacy metadata provider (" + OJB_METADATA_MANAGER_CLASS + ")"); isLegacyLoaded = ReflectionUtils.invokeViaReflection(descriptorRepository, "hasDescriptorFor", new Class[] { Class.class }, dataObjectClass); } catch (ClassNotFoundException e) { // the legacy provider does not exist, so this class can't possibly have been loaded through it isLegacyLoaded = Boolean.FALSE; } } legacyLoadedCache.put(dataObjectClass, isLegacyLoaded); } return isLegacyLoaded.booleanValue(); }
From source file:org.tdar.core.service.ReflectionService.java
/** * Find all getters of beans that support the @link Obfuscatable interface and any child beans throughout the graph * //ww w .jav a2s . c o m * @param cls * @return */ @SuppressWarnings("unchecked") public List<Pair<Method, Class<? extends Obfuscatable>>> findAllObfuscatableGetters(Class<?> cls) { List<Method> declaredFields = new ArrayList<>(); List<Pair<Method, Class<? extends Obfuscatable>>> result = new ArrayList<>(); // iterate up the package hierarchy Class<?> actualClass = null; while (cls.getPackage().getName().startsWith(ORG_TDAR)) { // find first implemented tDAR class (actual class); if (actualClass == null) { actualClass = cls; } for (Method method : cls.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers()) && method.getName().startsWith(GET)) { declaredFields.add(method); } } cls = cls.getSuperclass(); } for (Method method : declaredFields) { Class<? extends Obfuscatable> type = null; // generic collections if (java.lang.reflect.Modifier.isStatic(method.getModifiers()) || java.lang.reflect.Modifier.isTransient(method.getModifiers()) || java.lang.reflect.Modifier.isFinal(method.getModifiers())) { continue; } // logger.info("TYPE: {} {} ", method.getGenericReturnType(), method.getName()); // logger.info("{} ==> {}", actualClass, method.getDeclaringClass()); // logger.info(" {} {} {} ", dcl.getTypeParameters(), dcl.getGenericInterfaces(), dcl.getGenericSuperclass()); boolean force = false; if (Collection.class.isAssignableFrom(method.getReturnType())) { Class<?> type2 = getType(method.getGenericReturnType()); if (type2 == null) { force = true; } else if (Obfuscatable.class.isAssignableFrom(type2)) { type = (Class<? extends Obfuscatable>) type2; logger.trace("\t -> {}", type); // class java.lang.String. } } // singletons if (Obfuscatable.class.isAssignableFrom(method.getReturnType())) { type = (Class<? extends Obfuscatable>) method.getReturnType(); logger.trace("\t -> {}", type); // class java.lang.String. } // things to add if ((type != null) || force) { if (force) { logger.trace( "forcing method to be obfuscated because cannot figure out gneric type {} (good luck)", method); } result.add(new Pair<Method, Class<? extends Obfuscatable>>(method, type)); } } return result; }
From source file:org.apache.axis2.deployment.util.Utils.java
public static boolean loadHandler(ClassLoader loader1, HandlerDescription desc) throws DeploymentException { String handlername = desc.getClassName(); Handler handler;/*from w ww. j a v a 2 s. c om*/ try { final Class handlerClass = Loader.loadClass(loader1, handlername); Package aPackage = (Package) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return handlerClass.getPackage(); } }); if (aPackage != null && aPackage.getName().equals("org.apache.axis2.engine")) { String name = handlerClass.getName(); log.warn("Dispatcher " + name + " is now deprecated."); if (name.indexOf("InstanceDispatcher") != -1) { log.warn("Please remove the entry for " + handlerClass.getName() + "from axis2.xml"); } else { log.warn( "Please edit axis2.xml and replace with the same class in org.apache.axis2.dispatchers package"); } } handler = (Handler) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedExceptionAction() { public Object run() throws InstantiationException, IllegalAccessException { return handlerClass.newInstance(); } }); handler.init(desc); desc.setHandler(handler); } catch (ClassNotFoundException e) { if (handlername.indexOf("jaxws") > 0) { log.warn("[JAXWS] - unable to load " + handlername); return false; } throw new DeploymentException(e); } catch (Exception e) { throw new DeploymentException(e); } return true; }
From source file:org.omnaest.utils.xml.JAXBXMLHelper.java
/** * Returns the {@link QName} defined by the {@link XmlRootElement} of the given {@link Class} type * //from w w w.ja va 2 s . co m * @param type * @return {@link QName} * @throws MissingXMLRootElementAnnotationException */ public static QName determineRootName(final Class<?> type) { // String selectingTagName = null; String selectingNamespace = null; // Assert.isNotNull(type, "type must not be null"); // final XmlRootElement xmlRootElement = ReflectionUtils.annotation(type, XmlRootElement.class); if (xmlRootElement == null) { // throw new MissingXMLRootElementAnnotationException(); } // String tagName = xmlRootElement.name(); if (tagName != null && !StringUtils.equalsIgnoreCase(tagName, "##default")) { selectingTagName = tagName; } else { selectingTagName = StringUtils.lowerCase(type.getSimpleName()); } // String namespace = xmlRootElement.namespace(); if (StringUtils.equalsIgnoreCase(namespace, "##default")) { // namespace = null; // final XmlSchema xmlSchema = ReflectionUtils.annotation(type.getPackage(), XmlSchema.class); if (xmlSchema != null) { namespace = xmlSchema.namespace(); } } selectingNamespace = namespace; // final QName qName = new QName(selectingNamespace, selectingTagName); return qName; }
From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java
/** * Method removes all Spring bean definitions of given type from the XML application context file. * @param project//from w ww . j av a 2 s. co m * @param type */ public void removeBeanDefinitions(File configFile, Project project, Class<?> type) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean-type.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); String beanElement = type.getAnnotation(XmlRootElement.class).name(); String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace(); //create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_element", beanElement); transformer.setParameter("bean_namespace", beanNamespace); //transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
From source file:org.op4j.devutils.selected.ImplFile.java
public ImplFile(final ImplType implType, final Class<?> interfaceClass) { super();/*from w w w . j a v a 2 s . c o m*/ try { this.implType = implType; this.imports = new LinkedHashSet<String>(); this.methodImplementations = new ArrayList<String>(); this.methodNames = new LinkedHashSet<String>(); this.interfaceTypeRep = new TypeRep(interfaceClass); this.packageName = interfaceClass.getPackage().getName().replace(".intf.", (implType == ImplType.OP ? ".impl.op." : ".impl.fn.")); this.imports.add(interfaceClass.getName()); this.className = StringUtils.substringBefore(this.interfaceTypeRep.getStringRep(), "<").substring(1) + "<" + StringUtils.substringAfter(this.interfaceTypeRep.getStringRep(), "<"); computeMethodImplementations(implType, interfaceClass); } catch (final Exception e) { throw new RuntimeException(e); } }
From source file:org.obsidian.test.TestAbstract.java
public <T> void appendDynamicImports(Class<T> classToImport) { boolean shouldBeIgnored = false; //Make sure: not already in dynamic imports for (String s : getDynamicImports()) { if (s.compareToIgnoreCase(classToImport.getName().replaceAll("\\$", ".")) == 0) { shouldBeIgnored = true;//from w w w . j a v a 2s . c o m } } if (!classToImport.isPrimitive() && !classToImport.isArray()) { //make sure: not in imports from constants for (String s : Content.IMPORTS) { if (s.compareToIgnoreCase(classToImport.getName()) == 0) { shouldBeIgnored = true; } } //make sure: not in same package if (classToImport.getPackage().toString() .compareToIgnoreCase(classTested.getPackage().toString()) == 0) { //#### Patch Submitted by Michael Cole (micole.3@gmail.com) 2/13/13 if (!(classToImport.isMemberClass() || classToImport.isEnum() || classToImport.isLocalClass())) { shouldBeIgnored = true; } } //make sure not private if (Modifier.isPrivate(classToImport.getModifiers())) { shouldBeIgnored = true; } //make sure: not importing from java.lang unless at least 3 deep //ex)java.lang.reflect String[] packageStructure = classToImport.getPackage().getName().split("\\."); int packageDepth = packageStructure.length; //if dataInputStream java.lang if (packageStructure[0].compareToIgnoreCase("java") == 0 && packageStructure[1].compareToIgnoreCase("lang") == 0) { //and less than three deep if (packageDepth < 3) { shouldBeIgnored = true; classToImport.getName(); } } } else { shouldBeIgnored = true; if (classToImport.isArray() && !classToImport.getComponentType().isPrimitive()) { appendDynamicImports(classToImport.getComponentType()); } } //if: not already in imports and not in same package if (!shouldBeIgnored) { //add to dynamic imports String importName = classToImport.getName(); importName = importName.replaceAll("\\$", "."); getDynamicImports().add(importName); } }
From source file:org.diorite.cfg.system.TemplateCreator.java
/** * Get template for given class./*from ww w. ja va 2 s. co m*/ * * @param clazz class to get template. * @param create if template should be created if it don't exisit yet. * @param cache if template should be saved to memory if created. * @param recreate if template should be force re-created even if it exisit. * @param <T> Type of template class * * @return template class or null. */ @SuppressWarnings("unchecked") public static <T> Template<T> getTemplate(final Class<T> clazz, final boolean create, final boolean cache, final boolean recreate) { if (!recreate) { final Template<T> template = (Template<T>) templateMap.get(clazz); if (template != null) { return template; } if (!create) { return null; } } Supplier<T> def = null; { final CfgDelegateDefault annotation = clazz.getAnnotation(CfgDelegateDefault.class); if (annotation != null) { final String path = annotation.value(); final Supplier<Object> basicDelegate = ConfigField.getBasicDelegate(path); if (basicDelegate != null) { def = (Supplier<T>) basicDelegate; } else if (path.equalsIgnoreCase("{new}")) { final ConstructorInvoker constructor = DioriteReflectionUtils.getConstructor(clazz); def = () -> (T) constructor.invoke(); } else { final int sepIndex = path.indexOf("::"); final Class<?> targetClass; final String methodName; if (sepIndex == -1) { targetClass = clazz; methodName = path; } else { try { Class<?> tmpClass = DioriteReflectionUtils .tryGetCanonicalClass(path.substring(0, sepIndex)); if (tmpClass == null) { tmpClass = DioriteReflectionUtils.tryGetCanonicalClass( clazz.getPackage().getName() + "." + path.substring(0, sepIndex)); if (tmpClass == null) { tmpClass = DioriteReflectionUtils.getNestedClass(clazz, path.substring(0, sepIndex)); } } targetClass = tmpClass; } catch (final Exception e) { throw new RuntimeException("Can't find class for: " + path, e); } methodName = path.substring(sepIndex + 2); } if (targetClass == null) { throw new RuntimeException("Can't find class for delegate: " + path); } final MethodInvoker methodInvoker = DioriteReflectionUtils.getMethod(targetClass, methodName, false); if (methodInvoker == null) { final ReflectGetter<Object> reflectGetter = DioriteReflectionUtils .getReflectGetter(methodName, targetClass); def = () -> (T) reflectGetter.get(null); } else { def = () -> (T) methodInvoker.invoke(null); } } } } final boolean allFields; // final boolean superFields; final boolean ignoreTransient; final String name; final String header; final String footer; final Collection<String> excludedFields = new HashSet<>(5); { final CfgClass cfgInfo = clazz.getAnnotation(CfgClass.class); if (cfgInfo != null) { allFields = cfgInfo.allFields(); // superFields = cfgInfo.superFields(); ignoreTransient = cfgInfo.ignoreTransient(); name = (cfgInfo.name() != null) ? cfgInfo.name() : clazz.getSimpleName(); Collections.addAll(excludedFields, cfgInfo.excludeFields()); } else { allFields = true; // superFields = true; ignoreTransient = true; name = clazz.getSimpleName(); } } { final String[] comments = readComments(clazz); header = comments[0]; footer = comments[1]; } final Set<ConfigField> fields = new TreeSet<>(); { final Collection<Class<?>> classes = new ArrayList<>(5); { Class<?> fieldsSrc = clazz; do { classes.add(fieldsSrc); fieldsSrc = fieldsSrc.getSuperclass(); if (fieldsSrc == null) { break; } final CfgClass cfgInfo = fieldsSrc.getAnnotation(CfgClass.class); if ((cfgInfo != null) && !cfgInfo.superFields()) { break; } } while (!fieldsSrc.equals(Object.class)); } for (final Class<?> fieldsSrc : classes) { int i = 0; for (final Field field : fieldsSrc.getDeclaredFields()) { if ((field.isAnnotationPresent(CfgField.class) || (!field.isAnnotationPresent(CfgExclude.class) && !field.isSynthetic() && (!ignoreTransient || !Modifier.isTransient(field.getModifiers())) && (allFields || field.isAnnotationPresent(CfgField.class)) && !excludedFields.contains(field.getName()))) && !Modifier.isStatic(field.getModifiers())) { fields.add(new ConfigField(field, i++)); } } } } final Template<T> template = new BaseTemplate<>(name, clazz, header, footer, fields, clazz.getClassLoader(), def); if (cache) { templateMap.put(clazz, template); TemplateCreator.fields.put(clazz, template.getFieldsNameMap()); } return template; }
From source file:org.apache.streams.plugins.StreamsScalaSourceGenerator.java
@Override public void run() { List<Class<?>> serializableClasses = detectSerializableClasses(); LOGGER.info("Detected {} serialiables:", serializableClasses.size()); for (Class clazz : serializableClasses) { LOGGER.debug(clazz.toString());//from w ww. j av a2 s .c om } List<Class<?>> pojoClasses = detectPojoClasses(serializableClasses); LOGGER.info("Detected {} pojos:", pojoClasses.size()); for (Class clazz : pojoClasses) { LOGGER.debug(clazz.toString()); } List<Class<?>> traits = detectTraits(pojoClasses); LOGGER.info("Detected {} traits:", traits.size()); for (Class clazz : traits) { LOGGER.debug(clazz.toString()); } List<Class<?>> cases = detectCases(pojoClasses); LOGGER.info("Detected {} cases:", cases.size()); for (Class clazz : cases) { LOGGER.debug(clazz.toString()); } for (Class clazz : traits) { String pojoPath = clazz.getPackage().getName().replace(".pojo.json", ".scala").replace(".", "/") + "/traits/"; String pojoName = clazz.getSimpleName() + ".scala"; String pojoScala = renderTrait(clazz); writeFile(outDir + "/" + pojoPath + pojoName, pojoScala); } for (Class clazz : traits) { String pojoPath = clazz.getPackage().getName().replace(".pojo.json", ".scala").replace(".", "/") + "/"; String pojoName = clazz.getSimpleName() + ".scala"; String pojoScala = renderClass(clazz); writeFile(outDir + "/" + pojoPath + pojoName, pojoScala); } for (Class clazz : cases) { String pojoPath = clazz.getPackage().getName().replace(".pojo.json", ".scala").replace(".", "/") + "/"; String pojoName = clazz.getSimpleName() + ".scala"; String pojoScala = renderCase(clazz); writeFile(outDir + "/" + pojoPath + pojoName, pojoScala); } }