Example usage for java.lang Class getPackage

List of usage examples for java.lang Class getPackage

Introduction

In this page you can find the example usage for java.lang Class getPackage.

Prototype

public Package getPackage() 

Source Link

Document

Gets the package of this class.

Usage

From source file:gov.nih.nci.cabio.portal.portlet.ReportService.java

/**
 * Returns the Collection association for the specified object and rolename.
 * @param clazz A caBIO bean class /*from   w  w  w  . j a v  a  2s. co m*/
 * @param id Internal caBIO id of the object
 * @param targetAssoc rolename of the association to follow 
 * @return Object with certain associations preloaded
 * @throws ApplicationException
 */
public List getDetailObjects(Class clazz, Long id, String targetAssoc, ClassObject config) throws Exception {

    if (!clazz.getPackage().getName().startsWith("gov.nih.nci.cabio.")) {
        throw new ApplicationException("Invalid class specified.");
    }

    Object criteria = clazz.newInstance();
    Class target = Class.forName(config.getName());
    ReflectionUtils.set(criteria, "id", id);

    // Construct HQL for getting the associated objects
    StringBuffer sb = new StringBuffer("select dest from " + config.getName() + " as dest ");

    // Eager fetch all the needed associations
    for (LabeledObject attr : config.getNestedAttributes()) {
        String first = attr.getFirstPart();
        if (ClassUtils.isSingular(target, first)) {
            sb.append("left join fetch dest." + first + " ");
        }
    }

    sb.append(", " + clazz.getName() + " as src ");
    sb.append("where src." + targetAssoc + ".id=dest.id and src=? ");

    String hql = sb.toString();
    List params = new ArrayList();
    params.add(criteria);
    List results = appService.query(new HQLCriteria(hql, QueryUtils.createCountQuery(hql), params));

    // The above eager loads all many-to-1 associations needed for 
    // display of the class. The simpler (less efficient but more 
    // foolproof) way is this:
    //List results = appService.getAssociation(criteria, targetAssoc);

    if (results.isEmpty())
        return null;
    return results;
}

From source file:com.medallia.spider.api.StRenderer.java

/** @return the path to the .st file of the given name, relative to the package of the given class */
protected String findPathForTemplate(Class<?> c, String name) {
    name = getPageRelativePath() + name;
    String path = name + ".st";
    while (c != null) {
        if (c.getResource(path) != null)
            return c.getPackage().getName().replace('.', '/') + "/" + name;
        c = c.getSuperclass();//from  w w w  . j  ava  2 s  .c  o  m
    }
    throw new RuntimeException("Cannot find template " + name);
}

From source file:freemarker.ext.dump.BaseDumpDirective.java

private String getReturnTypeName(Method method) {
    Class<?> cls = method.getReturnType();
    Package pkg = cls.getPackage();
    if (pkg != null) { // void return type has null package
        String packageName = pkg.getName();
        if (packageName.startsWith("java")) {
            return getSimpleTypeName(cls);
        }/*from  w  w w .j  av a 2  s  . co m*/
    }
    return cls.getName();
}

From source file:org.apache.axis2.jaxws.utility.ClassUtils.java

/**
 * @param cls/*from w  w w.j a v  a 2  s  . c  o  m*/
 * @return true if this is a JAX-WS or JAX-WS generated class
 */
public static final boolean isJAXWSClass(Class cls) {
    // TODO Processing all of these annotations is very expensive.  We need to cache the 
    // result in a static WeakHashMap<Class, Boolean>

    // Kinds of generated classes: Service, Provider, Impl, Exception, Holder
    // Or the class is in the jaxws.xml.ws package

    // Check for Impl
    WebService wsAnn = (WebService) getAnnotation(cls, WebService.class);
    if (wsAnn != null) {
        return true;
    }

    // Check for service
    WebServiceClient wscAnn = (WebServiceClient) getAnnotation(cls, WebServiceClient.class);
    if (wscAnn != null) {
        return true;
    }

    // Check for provider
    WebServiceProvider wspAnn = (WebServiceProvider) getAnnotation(cls, WebServiceProvider.class);
    if (wspAnn != null) {
        return true;
    }

    // Check for Exception
    WebFault wfAnn = (WebFault) getAnnotation(cls, WebFault.class);
    if (wfAnn != null) {
        return true;
    }

    // Check for Holder
    if (Holder.class.isAssignableFrom(cls)) {
        return true;
    }

    // Check for a javax.xml.ws.Service class instance
    if (Service.class.isAssignableFrom(cls)) {
        return true;
    }

    String className = cls.getPackage() == null ? null : cls.getPackage().getName();
    if (className != null && className.startsWith("javax.xml.ws")
            && !className.startsWith("javax.xml.ws.wsaddressing")) {
        return true;
    }

    return false;
}

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java

@Test
public void testFindClassSuccess() throws ClassNotFoundException, IOException, KettleFileException {
    String canonicalName = ShimBridgingClassloader.class.getCanonicalName();
    FileObject myFile = KettleVFS.getFileObject("ram://testFindClassSuccess");
    try (FileObject fileObject = myFile) {
        try (OutputStream outputStream = fileObject.getContent().getOutputStream(false)) {
            IOUtils.copy(//www .  j a  v  a 2  s  . c  o  m
                    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.findClass(canonicalName);
        assertEquals(canonicalName, shimBridgingClassloaderClass.getCanonicalName());
        assertEquals(shimBridgingClassloader, shimBridgingClassloaderClass.getClassLoader());
        assertEquals(packageName, shimBridgingClassloaderClass.getPackage().getName());
    } finally {
        myFile.delete();
    }
}

From source file:name.livitski.tools.persista.StorageBootstrap.java

/**
 * Uses the package name of a persistent class to designate
 * a persistence unit for this object./*from  w w w.  ja v  a2  s .co  m*/
 * @see #setPersistenceUnit(String)
 * @see #getPersistenceUnit
 */
public void setPersistenceUnit(Class<?> persistentClass) {
    Package pkg = persistentClass.getPackage();
    if (null == pkg)
        throw new IllegalArgumentException("Class " + persistentClass.getName()
                + " from the default package cannot be used to set the persistence unit.");
    setPersistenceUnit(pkg.getName());
}

From source file:com.tower.service.test.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) {
            }
        }
        return testSrc.toString();
    }

}

From source file:com.evolveum.midpoint.repo.sql.query2.definition.ClassDefinitionParser.java

private Class getJaxbClass(Method method, Class returnedClass) {
    JaxbType annotation = (JaxbType) method.getAnnotation(JaxbType.class);
    if (annotation != null) {
        return annotation.type();
    }/*from  w w  w  .  j  a va 2 s  . com*/
    Class classFromEntity = getJaxbClassForEntity(returnedClass);
    if (classFromEntity != null) {
        return classFromEntity;
    }
    Package returnedClassPkg = returnedClass.getPackage();
    Package dataObjectsPkg = Marker.class.getPackage();
    if (returnedClassPkg != null && returnedClassPkg.getName().startsWith(dataObjectsPkg.getName())) {
        return null;
    } else {
        return returnedClass; // probably the JAXB value
    }
}

From source file:org.amplafi.hivemind.factory.servicessetter.ServicesSetterImpl.java

/**
 * @param propertyType//from   ww w  .  j av  a2  s .co m
 * @return true class can be wired up as a service
 */
@Override
public boolean isWireableClass(Class<?> propertyType) {
    if (
    // exclude primitives or other things that are not mockable in any form
    propertyType.isPrimitive() || propertyType.isAnnotation() || propertyType.isArray() || propertyType.isEnum()
    // generated classes
            || propertyType.getCanonicalName() == null
            // exclude java classes
            || propertyType.getPackage().getName().startsWith("java")) {
        return false;
    } else {
        // exclude things that are explicitly labeled as not being injectable
        NotService notService = propertyType.getAnnotation(NotService.class);
        return notService == null;
    }
}

From source file:com.ethanruffing.preferenceabstraction.AutoPreferences.java

/**
 * Sets this up for the given class, forcing use of the specified storage
 * system. Defaults to using an XML file if using file-based storage.
 *
 * @param c          The class for which the preferences are to be stored.
 * @param configType The storage system to use for the preferences.
 * @throws ConfigurationException Thrown if an error occurs while loading
 *                                the configuration file.
 *///  w w  w  . j a va 2 s . c o  m
private void setup(Class<?> c, ConfigurationType configType) throws ConfigurationException {
    prefsFor = c;
    this.configType = configType;
    switch (configType) {
    case LOCAL:
        fileConfig = new XMLConfiguration(new File(c.getPackage().getName() + ".xml"));
        fileConfig.setAutoSave(true);
        ((XMLConfiguration) fileConfig).setDelimiterParsingDisabled(true);
    case HOME:
        fileConfig = new XMLConfiguration(
                new File(System.getProperty("user.home"), "." + c.getPackage().getName() + ".xml"));
        fileConfig.setAutoSave(true);
        ((XMLConfiguration) fileConfig).setDelimiterParsingDisabled(true);
        break;
    case SYSTEM:
        prefs = Preferences.userNodeForPackage(c);
        break;
    }
}