List of usage examples for java.lang Class getPackage
public Package getPackage()
From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java
@Test public void testLoadClassFindClass() throws ClassNotFoundException, IOException, KettleFileException { String canonicalName = ShimBridgingClassloader.class.getCanonicalName(); FileObject myFile = KettleVFS.getFileObject("ram://testLoadClassFindClass"); try (FileObject fileObject = myFile) { try (OutputStream outputStream = fileObject.getContent().getOutputStream(false)) { IOUtils.copy(/*ww w.j av a 2 s .c om*/ getClass().getClassLoader().getResourceAsStream(canonicalName.replace(".", "/") + ".class"), outputStream); } String packageName = ShimBridgingClassloader.class.getPackage().getName(); when(bundleWiring.findEntries("/" + packageName.replace(".", "/"), ShimBridgingClassloader.class.getSimpleName() + ".class", 0)) .thenReturn(Arrays.asList(fileObject.getURL())); when(parentClassLoader.loadClass(anyString(), anyBoolean())).thenAnswer(new Answer<Class<?>>() { @Override public Class<?> answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); return new ShimBridgingClassloader.PublicLoadResolveClassLoader(getClass().getClassLoader()) .loadClass((String) arguments[0], (boolean) arguments[1]); } }); Class<?> shimBridgingClassloaderClass = shimBridgingClassloader.loadClass(canonicalName, true); assertEquals(canonicalName, shimBridgingClassloaderClass.getCanonicalName()); assertEquals(shimBridgingClassloader, shimBridgingClassloaderClass.getClassLoader()); assertEquals(packageName, shimBridgingClassloaderClass.getPackage().getName()); Class<?> shimBridgingClassloaderClass2 = shimBridgingClassloader.loadClass(canonicalName, false); assertEquals(shimBridgingClassloaderClass, shimBridgingClassloaderClass2); } finally { myFile.delete(); } }
From source file:com.kjt.service.common.SoafwTesterMojo.java
private String readTestSrc(String className) { BufferedReader br = null;/*from w w w .j a va 2 s. co m*/ String test = className + "Test"; StringBuilder testSrc = new StringBuilder(); try { Class tstCls = cl.loadClass(test); Package pkg = tstCls.getPackage(); String pkgName = pkg.getName(); String relativePath = pkgName.replace(".", File.separator); String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java"; String testSrcFullPath = testBaseSrcPath + File.separator + relativePath + File.separator + tstCls.getSimpleName() + ".java"; br = new BufferedReader(new InputStreamReader(new FileInputStream(testSrcFullPath), "UTF-8")); String line = null; while ((line = br.readLine()) != null) { testSrc.append(line); testSrc.append("\n"); } } catch (Exception e) { this.getLog().error(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } this.getLog().info(testSrc); return testSrc.toString(); } }
From source file:com.github.philippn.springremotingautoconfigure.client.annotation.HttpInvokerProxyFactoryBeanRegistrar.java
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Set<String> basePackages = new HashSet<>(); for (String beanName : registry.getBeanDefinitionNames()) { BeanDefinition definition = registry.getBeanDefinition(beanName); if (definition.getBeanClassName() != null) { try { Class<?> resolvedClass = ClassUtils.forName(definition.getBeanClassName(), null); EnableHttpInvokerAutoProxy autoProxy = AnnotationUtils.findAnnotation(resolvedClass, EnableHttpInvokerAutoProxy.class); if (autoProxy != null) { if (autoProxy.basePackages().length > 0) { Collections.addAll(basePackages, autoProxy.basePackages()); } else { basePackages.add(resolvedClass.getPackage().getName()); }/* w ww. j av a 2 s.c om*/ } } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to inspect class " + definition.getBeanClassName() + " for @EnableHttpInvokerAutoProxy annotations"); } } } ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( false) { /* (non-Javadoc) * @see org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#isCandidateComponent(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) */ @Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent(); } }; scanner.addIncludeFilter(new AnnotationTypeFilter(RemoteExport.class)); for (String basePackage : basePackages) { for (BeanDefinition definition : scanner.findCandidateComponents(basePackage)) { if (definition.getBeanClassName() != null) { try { Class<?> resolvedClass = ClassUtils.forName(definition.getBeanClassName(), null); setupProxy(resolvedClass, registry); } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to inspect class " + definition.getBeanClassName() + " for @RemoteExport annotations"); } } } } }
From source file:org.javelin.sws.ext.bind.SweJaxbContext.java
/** * <p>Get a representation of a class and it's (JAXB2) metadata as a <i>pattern</i> of static and dynamic {@link XMLEvent XML events}.</p> * /* w w w.j a v a 2s .c o m*/ * <p>A class which is to be known by the registry should be directly convertible to a series of XML events. What is not mandatory here is * the root element of the marshalled object.</p> * * <p>The produced pattern is automatically cached in the registry. Also the metadata for {@link XmlRootElement} annotated classes is cached.</p> * * @param cl * @return */ @SuppressWarnings("unchecked") @Override public <T> TypedPattern<T> determineAndCacheXmlPattern(Class<T> cl) { // DESIGNFLAW: some check are done using map.containsKey(), some - using TypedPatternRegistry if (this.patterns.containsKey(cl)) { return (TypedPattern<T>) this.patterns.get(cl); } TypedPattern<T> pattern = null; log.trace("Mapping {} class to TypedPattern", cl.getName()); // defaults JaxbMetadata meta = this.package2meta.get(cl.getPackage().getName()); // package customization - cached if (!this.package2meta.containsKey(cl.getPackage().getName())) { meta = JaxbMetadata.defaultForPackage(cl.getPackage()); // determine package-level default accessor type XmlAccessorType xmlAccessorType = AnnotationUtils.getAnnotation(cl.getPackage(), XmlAccessorType.class); XmlSchema xmlSchema = AnnotationUtils.getAnnotation(cl.getPackage(), XmlSchema.class); if (xmlAccessorType != null) meta.setXmlAccessType(xmlAccessorType.value()); if (xmlSchema != null) { meta.setNamespace(xmlSchema.namespace()); meta.setElementForm(xmlSchema.elementFormDefault()); meta.setAttributeForm(xmlSchema.attributeFormDefault()); } this.package2meta.put(cl.getPackage().getName(), meta); } // class customization - not cached XmlAccessorType xmlAccessorType = AnnotationUtils.findAnnotation(cl, XmlAccessorType.class); XmlType xmlType = AnnotationUtils.getAnnotation(cl, XmlType.class); XmlAccessType xmlAccessType = xmlAccessorType == null ? meta.getXmlAccessType() : xmlAccessorType.value(); String namespace = xmlType == null || "##default".equals(xmlType.namespace()) ? meta.getNamespace() : xmlType.namespace(); QName typeName = new QName(namespace, xmlType == null || "##default".equals(xmlType.name()) ? cl.getSimpleName() : xmlType.name()); // before stepping into the class we'll add TemporaryTypedPattern to the mapping to be able to analyze cross-dependent classes TemporaryTypedPattern<T> txp = TemporaryTypedPattern.newTemporaryTypedPattern(typeName, cl); this.patterns.put(cl, txp); PropertyCallback<T> pc = new PropertyCallback<T>(this, cl, typeName, xmlAccessType, meta.getElementForm(), meta.getAttributeForm()); // this is where the magic happens pattern = pc.analyze(); txp.setRealPattern(pattern); // cache known global elements XmlRootElement xmlRootElement = AnnotationUtils.findAnnotation(cl, XmlRootElement.class); if (xmlRootElement != null) { String rootElementNamespace = "##default".equals(xmlRootElement.namespace()) ? meta.getNamespace() : xmlRootElement.namespace(); String rootElementName = "##default".equals(xmlRootElement.name()) ? cl.getSimpleName() : xmlRootElement.name(); QName rootQName = new QName(rootElementNamespace, rootElementName); ElementPattern<?> elementPattern = ElementPattern.newElementPattern(rootQName, pattern); this.rootPatterns.put(cl, elementPattern); this.rootPatternsForQNames.put(rootQName, elementPattern); } this.patterns.put(pattern.getJavaType(), pattern); this.patternsForTypeQNames.put(pattern.getSchemaType(), pattern); // see also XmlSeeAlso xmlSeeAlso = AnnotationUtils.findAnnotation(cl, XmlSeeAlso.class); if (xmlSeeAlso != null) { for (Class<?> c : xmlSeeAlso.value()) { log.trace("Analyzing @XmlSeeAlso class {}", c.getName()); this.determineAndCacheXmlPattern(c); } } return pattern; }
From source file:com.medallia.spider.SpiderServlet.java
/** * @return the servlet class; usually this is {@link #getClass()}, but if that * class is in a package named 'test' the superclass is used instead. *//*from ww w .j av a 2 s . c o m*/ @SuppressWarnings("unchecked") protected Class<? extends SpiderServlet> getServletClass() { Class<? extends SpiderServlet> c = getClass(); if (c.getPackage().getName().endsWith(".test")) c = (Class<? extends SpiderServlet>) c.getSuperclass(); return c; }
From source file:ips1ap101.lib.core.util.ClassX.java
public String subclassName(Class<?> baseClass, String subclassType) { Bitacora.trace(ClassX.class, "subclassName", baseClass, subclassType); if (baseClass == null) { throw new IllegalArgumentException(); }/*from w w w.ja va 2 s .c om*/ String sp, ss; String st = StringUtils.trimToNull(subclassType); if (st == null) { sp = PACKAGE; ss = SUFFIX; } else { sp = st + "_" + PACKAGE; ss = st + "_" + SUFFIX; } sp = CoreBundle.getString(SIMPLE, sp); ss = CoreBundle.getString(SIMPLE, ss); return baseClass.getPackage().getName() + "." + sp + "." + baseClass.getSimpleName() + ss; }
From source file:com.lawyer.cores.framework.mybatis.SqlSessionFactoryBean.java
/** * Build a {@code SqlSessionFactory} instance. * * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a * {@code SqlSessionFactory} instance based on an Reader. * * @return SqlSessionFactory/* w w w. j av a2s .co m*/ * @throws IOException if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { Configuration configuration; XMLConfigBuilder xmlConfigBuilder = null; if (this.configLocation != null) { xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); configuration = xmlConfigBuilder.getConfiguration(); } else { if (logger.isDebugEnabled()) { logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration"); } configuration = new Configuration(); configuration.setVariables(this.configurationProperties); } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } if (hasLength(this.typeAliasesPackage)) { Map<String, String> filterMap = new HashMap<String, String>(); ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>(); String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeAliasPackageArray) { //???domain wangxz update 20140417 resolverUtil.findAnnotated(MyBatisDomain.class, packageToScan); Set<Class<? extends Class<?>>> typeSet = resolverUtil.getClasses(); if (typeSet != null) { Iterator<Class<? extends Class<?>>> it = typeSet.iterator(); String packageName = ""; while (it.hasNext()) { Class<? extends Class<?>> c = it.next(); packageName = c.getPackage().getName(); if (!filterMap.containsKey(packageName)) { filterMap.put(packageName, packageName); configuration.getTypeAliasRegistry().registerAliases(packageName, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType); //System.out.println("Scanned package: '" + packageName + "' for aliases"); } } } } } if (!isEmpty(this.typeAliases)) { for (Class<?> typeAlias : this.typeAliases) { configuration.getTypeAliasRegistry().registerAlias(typeAlias); if (logger.isDebugEnabled()) { logger.debug("Registered type alias: '" + typeAlias + "'"); } } } if (!isEmpty(this.plugins)) { for (Interceptor plugin : this.plugins) { configuration.addInterceptor(plugin); if (logger.isDebugEnabled()) { logger.debug("Registered plugin: '" + plugin + "'"); } } } if (hasLength(this.typeHandlersPackage)) { String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeHandlersPackageArray) { configuration.getTypeHandlerRegistry().register(packageToScan); if (logger.isDebugEnabled()) { logger.debug("Scanned package: '" + packageToScan + "' for type handlers"); } } } if (!isEmpty(this.typeHandlers)) { for (TypeHandler<?> typeHandler : this.typeHandlers) { configuration.getTypeHandlerRegistry().register(typeHandler); if (logger.isDebugEnabled()) { logger.debug("Registered type handler: '" + typeHandler + "'"); } } } if (xmlConfigBuilder != null) { try { xmlConfigBuilder.parse(); if (logger.isDebugEnabled()) { logger.debug("Parsed configuration file: '" + this.configLocation + "'"); } } catch (Exception ex) { throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex); } finally { ErrorContext.instance().reset(); } } if (this.transactionFactory == null) { this.transactionFactory = new SpringManagedTransactionFactory(); } Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource); configuration.setEnvironment(environment); if (this.databaseIdProvider != null) { try { configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource)); } catch (SQLException e) { throw new NestedIOException("Failed getting a databaseId", e); } } if (!isEmpty(this.mapperLocations)) { for (Resource mapperLocation : this.mapperLocations) { if (mapperLocation == null) { continue; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e); } finally { ErrorContext.instance().reset(); } if (logger.isDebugEnabled()) { logger.debug("Parsed mapper file: '" + mapperLocation + "'"); } } } else { if (logger.isDebugEnabled()) { logger.debug("Property 'mapperLocations' was not specified or no matching resources found"); } } return this.sqlSessionFactoryBuilder.build(configuration); }
From source file:com.tower.service.test.SoafwTesterMojo.java
private StringBuffer createTestJHeadByClass(Class cls) { StringBuffer jHeadBuf = new StringBuffer(); jHeadBuf.append("package " + cls.getPackage().getName() + "; \n"); jHeadBuf.append("\n"); jHeadBuf.append("import org.junit.Test;\n"); jHeadBuf.append("import org.junit.runner.RunWith;\n"); jHeadBuf.append("import org.springframework.test.context.ContextConfiguration;\n"); jHeadBuf.append("import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\n\n"); jHeadBuf.append("import com.tower.service.annotation.SoaFwTest;\n"); jHeadBuf.append("@RunWith(SpringJUnit4ClassRunner.class)\n"); String name = project.getName(); if (config) { jHeadBuf.append("@ContextConfiguration( locations = { \"" + configFileLocations + "\"})\n"); } else {//from ww w . j ava 2s . com String suffix = "dao"; if (name.endsWith("-common")) { suffix = "common"; } else if (name.endsWith("-config")) { suffix = "config"; } else if (name.endsWith("-cache")) { suffix = "cache"; } else if (name.endsWith("-dao")) { suffix = "dao"; } else if (name.endsWith("-mq")) { suffix = "mq"; } else if (name.endsWith("-rpc")) { suffix = "rpc"; } else if (name.endsWith("-job")) { suffix = "job"; } else if (name.endsWith("-web")) { suffix = "dubbo"; } else if (name.endsWith("-domain") || name.endsWith("-service") || name.endsWith("-service-impl")) { suffix = "service"; } jHeadBuf.append("@ContextConfiguration( locations = { \"classpath*:/META-INF/config/spring/spring-" + suffix + ".xml\"})\n"); } jHeadBuf.append("public class " + cls.getSimpleName() + "Test {\n"); return jHeadBuf; }
From source file:core.mybatis.SqlSessionFactoryBean.java
/** * Build a {@code SqlSessionFactory} instance. * * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a * {@code SqlSessionFactory} instance based on an Reader. * * @return SqlSessionFactory//from w w w . j a va 2 s . c o m * @throws IOException if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { Configuration configuration; XMLConfigBuilder xmlConfigBuilder = null; if (this.configLocation != null) { xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); configuration = xmlConfigBuilder.getConfiguration(); } else { if (logger.isDebugEnabled()) { logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration"); } configuration = new Configuration(); configuration.setVariables(this.configurationProperties); } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } if (hasLength(this.typeAliasesPackage)) { Map<String, String> filterMap = new HashMap<String, String>(); ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>(); String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeAliasPackageArray) { //???domain wangxz update 20140417 resolverUtil.findAnnotated(core.mybatis.MyBatisDomain.class, packageToScan); Set<Class<? extends Class<?>>> typeSet = resolverUtil.getClasses(); if (typeSet != null) { Iterator<Class<? extends Class<?>>> it = typeSet.iterator(); String packageName = ""; while (it.hasNext()) { Class<? extends Class<?>> c = it.next(); packageName = c.getPackage().getName(); if (!filterMap.containsKey(packageName)) { filterMap.put(packageName, packageName); configuration.getTypeAliasRegistry().registerAliases(packageName, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType); System.out.println("Scanned package: '" + packageName + "' for aliases"); } } } } } if (!isEmpty(this.typeAliases)) { for (Class<?> typeAlias : this.typeAliases) { configuration.getTypeAliasRegistry().registerAlias(typeAlias); if (logger.isDebugEnabled()) { logger.debug("Registered type alias: '" + typeAlias + "'"); } } } if (!isEmpty(this.plugins)) { for (Interceptor plugin : this.plugins) { configuration.addInterceptor(plugin); if (logger.isDebugEnabled()) { logger.debug("Registered plugin: '" + plugin + "'"); } } } if (hasLength(this.typeHandlersPackage)) { String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeHandlersPackageArray) { configuration.getTypeHandlerRegistry().register(packageToScan); if (logger.isDebugEnabled()) { logger.debug("Scanned package: '" + packageToScan + "' for type handlers"); } } } if (!isEmpty(this.typeHandlers)) { for (TypeHandler<?> typeHandler : this.typeHandlers) { configuration.getTypeHandlerRegistry().register(typeHandler); if (logger.isDebugEnabled()) { logger.debug("Registered type handler: '" + typeHandler + "'"); } } } if (xmlConfigBuilder != null) { try { xmlConfigBuilder.parse(); if (logger.isDebugEnabled()) { logger.debug("Parsed configuration file: '" + this.configLocation + "'"); } } catch (Exception ex) { throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex); } finally { ErrorContext.instance().reset(); } } if (this.transactionFactory == null) { this.transactionFactory = new SpringManagedTransactionFactory(); } Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource); configuration.setEnvironment(environment); if (this.databaseIdProvider != null) { try { configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource)); } catch (SQLException e) { throw new NestedIOException("Failed getting a databaseId", e); } } if (!isEmpty(this.mapperLocations)) { for (Resource mapperLocation : this.mapperLocations) { if (mapperLocation == null) { continue; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e); } finally { ErrorContext.instance().reset(); } if (logger.isDebugEnabled()) { logger.debug("Parsed mapper file: '" + mapperLocation + "'"); } } } else { if (logger.isDebugEnabled()) { logger.debug("Property 'mapperLocations' was not specified or no matching resources found"); } } return this.sqlSessionFactoryBuilder.build(configuration); }