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:org.javelin.sws.ext.bind.SweJaxbContextFactory.java

/**
 * <p>Determines mapped classes in the context path and invokes {@link #createContext(Class[], Map)}</p>
 * <p>JAXB-RI uses {@code ObjectFactory} class and/or {@code jaxb.index} file</p>
 * <p>see: com.sun.xml.bind.v2.ContextFactory.createContext(String, ClassLoader, Map<String, Object>)</p>
 * /*  w  w w  .j ava 2 s  .  c om*/
 * @param contextPath
 * @param classLoader
 * @param properties
 * @return
 * @throws IOException 
 */
public static JAXBContext createContext(String contextPath, ClassLoader classLoader, Map<String, ?> properties)
        throws IOException {
    Assert.notNull(contextPath, "The contextPath should not be null");

    PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(
            classLoader);
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> classes = new LinkedList<Class<?>>();
    // scan the package(s)
    String[] packages = StringUtils.tokenizeToStringArray(contextPath, ":");
    for (String pkg : packages) {
        log.trace("Scanning package: {}", pkg);
        Resource[] resources = resourcePatternResolver
                .getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                        + ClassUtils.convertClassNameToResourcePath(pkg) + "/*.class");
        for (Resource classResource : resources) {
            MetadataReader mdReader = metadataReaderFactory.getMetadataReader(classResource);
            Class<?> cls = ClassUtils.resolveClassName(mdReader.getClassMetadata().getClassName(), classLoader);
            if (cls.getSimpleName().equals("package-info")) {
                XmlSchema xmlSchema = AnnotationUtils.getAnnotation(cls.getPackage(), XmlSchema.class);
                String namespace = xmlSchema == null || xmlSchema.namespace() == null
                        ? NamespaceUtils.packageNameToNamespace(cls.getPackage())
                        : xmlSchema.namespace();
                log.trace(" - found package-info: {}, namespace: {}", cls.getPackage().getName(), namespace);
            } else {
                log.trace(" - found class: {}", mdReader.getClassMetadata().getClassName());
                classes.add(cls);
            }
        }
    }

    return createContext(classes.toArray(new Class[0]), properties);
}

From source file:Main.java

public static String getNamespace(Class<?> clazz) {
    XmlType xmlType = clazz.getAnnotation(XmlType.class);

    String namespace = null;//from   ww  w .ja v  a 2s .c o m

    if (xmlType != null) {
        namespace = xmlType.namespace();
        if ("##default".equals(namespace)) {
            namespace = null;
        }
    }

    if (namespace == null) {
        Package itemPackage = clazz.getPackage();
        XmlSchema xmlSchema = itemPackage.getAnnotation(XmlSchema.class);
        if (xmlSchema != null) {
            namespace = xmlSchema.namespace();
        }
    }

    return namespace;
}

From source file:net.servicefixture.util.ReflectionUtils.java

/**
 * Finds all the concrete subclasses for given class in the the SAME JAR
 * file where the baseClass is loaded from.
 * // w ww . j  a  v a 2  s.  co  m
 * @param baseClass
 *            the base class
 */
public static Class[] findSubClasses(Class baseClass) {
    String packagePath = "/" + baseClass.getPackage().getName().replace('.', '/');
    URL url = baseClass.getResource(packagePath);
    if (url == null) {
        return new Class[0];
    }
    List<Class> derivedClasses = new ArrayList<Class>();
    try {
        URLConnection connection = url.openConnection();
        if (connection instanceof JarURLConnection) {
            JarFile jarFile = ((JarURLConnection) connection).getJarFile();
            Enumeration e = jarFile.entries();
            while (e.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                String entryName = entry.getName();
                if (entryName.endsWith(".class")) {
                    String clazzName = entryName.substring(0, entryName.length() - 6);

                    clazzName = clazzName.replace('/', '.');
                    try {
                        Class clazz = Class.forName(clazzName);
                        if (isConcreteSubclass(baseClass, clazz)) {
                            derivedClasses.add(clazz);
                        }
                    } catch (Throwable ignoreIt) {
                    }
                }
            }
        } else if (connection instanceof FileURLConnection) {
            File file = new File(url.getFile());
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                String filename = files[i].getName();
                if (filename.endsWith(".class")) {
                    filename = filename.substring(0, filename.length() - 6);
                    String clazzname = baseClass.getPackage().getName() + "." + filename;
                    try {
                        Class clazz = Class.forName(clazzname);
                        if (isConcreteSubclass(baseClass, clazz)) {
                            derivedClasses.add(clazz);
                        }
                    } catch (Throwable ignoreIt) {
                    }
                }
            }
        }
    } catch (IOException ignoreIt) {
    }
    return derivedClasses.toArray(new Class[derivedClasses.size()]);
}

From source file:org.sigmah.server.servlet.exporter.models.Realizer.java

/**
 * Find all the declared fields of the given class and its super classes
 * for Sigmah objects./* ww  w .  ja  v  a 2s.  c  o m*/
 * 
 * @param clazz
 *          Class to read.
 * @return A list of every declared fields (also contains static fields).
 * @throws SecurityException If one of the fields is protected.
 */
private static List<Field> getFieldsOfClass(final Class<?> clazz) throws SecurityException {

    // Accessing fields from the given object.
    final ArrayList<Field> fields = new ArrayList<>();

    fields.addAll(Arrays.asList(clazz.getDeclaredFields()));

    // Accessing fields from the super classes.
    Class<?> superClass = clazz.getSuperclass();
    while (superClass.getPackage().getName().startsWith("org.sigmah")) {

        fields.addAll(Arrays.asList(superClass.getDeclaredFields()));

        superClass = superClass.getSuperclass();
    }

    return fields;
}

From source file:de.fu_berlin.inf.dpp.misc.pico.DotGraphMonitor.java

public static String getColorOld(Class<?> clazz, HashMap<String, String> colors) {
    String name;/*from   ww  w .  j a  v  a 2s  . c om*/
    Package myPackage = clazz.getPackage();
    if (myPackage == null) {
        name = "misc";
    } else {
        name = myPackage.getName();
    }

    while (name != null && name.length() > 0) {

        String color = colors.get(name);
        if (color != null) {
            return "  \"" + clazz.getSimpleName() + "\" [color=" + color + "];\n";
        }

        int index = name.lastIndexOf('.');
        if (index == -1)
            break;

        name = name.substring(0, index);
    }

    return null;
}

From source file:com.conversantmedia.mapreduce.tool.RunJob.java

private static String versionForDriverClass(Class<?> c, String annotatedVersion) {
    String version = annotatedVersion;
    String manifestVersion = c.getPackage().getImplementationVersion();
    if (StringUtils.isBlank(manifestVersion)) {
        manifestVersion = readVersionFromManifest(version);
    }/*ww w. j a v  a 2s  .c  om*/
    if (version.equals("N/A") && StringUtils.isNotBlank(manifestVersion)) {
        version = manifestVersion;
    }
    return version;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

/**
 * Performs the same function as {@link JAXBUtil#getJAXBIntrospector(String)}, but uses a JAXB
 * generated class object to retrieve the JAXB package name.
 *
 * @param jaxbClass - the {@link Class} object that the represents a JAXB generated class
 * @return an instance of {@link JAXBIntrospector} that corresponds to the JAXB package name
 * @throws JAXBException if an error occurs while creating a JAXB context
 *//* w  ww . ja  va  2  s  .  c o  m*/
public static JAXBIntrospector getJAXBIntrospector(final Class<?> jaxbClass) throws JAXBException {

    if (jaxbClass != null) {
        return getJAXBIntrospector(jaxbClass.getPackage().getName());
    } else {
        throw new JAXBException(
                "Could not instantiate JAXB introspector because the JAXB class object was null");
    }
}

From source file:com.jaeksoft.searchlib.analysis.ClassFactory.java

/**
 * /*w  w  w .  j  av a2 s .c o m*/
 * @param config
 * @param factoryClass
 * @return
 * @throws SearchLibException
 */
protected static <T extends ClassFactory> T createInstance(Config config, Class<T> factoryClass)
        throws SearchLibException {
    try {
        T o = factoryClass.newInstance();
        o.setParams(config, factoryClass.getPackage().getName(), factoryClass.getSimpleName());
        o.initProperties();
        return o;
    } catch (InstantiationException e) {
        throw new SearchLibException(e);
    } catch (IllegalAccessException e) {
        throw new SearchLibException(e);
    } catch (IOException e) {
        throw new SearchLibException(e);
    }
}

From source file:py.una.pol.karaku.test.util.TestUtils.java

/**
 * Retorna un recurso, que se supone esta en la misma ubicacin que la
 * clase.//from  w  w  w  . j a v a  2  s  .c  o  m
 * 
 * @param source
 *            Clase de dondese invoca
 * @param fileName
 *            nombre del archivo
 * @return ClassPath vlido
 * @throws KarakuRuntimeException
 *             si no se encuentra el archivo
 */
public static ClassPathResource getSiblingResource(Class<?> source, String resourceName) {

    ClassPathResource cpr = new ClassPathResource(resourceName);
    if (cpr.exists()) {
        return cpr;
    }

    String realPath = source.getPackage().getName().replaceAll("\\.", "/");
    realPath += "/" + resourceName;
    cpr = new ClassPathResource(realPath);

    if (!cpr.exists()) {
        throw new KarakuRuntimeException("File with name " + resourceName
                + " can not be found. Paths tried: Absolute:" + resourceName + "; Relative: " + realPath);
    }
    return cpr;
}

From source file:org.grouplens.lenskit.eval.graph.ComponentNodeBuilder.java

static String shortClassName(Class<?> type) {
    if (ClassUtils.isPrimitiveOrWrapper(type)) {
        if (!type.isPrimitive()) {
            type = ClassUtils.wrapperToPrimitive(type);
        }//from ww w . ja  va2  s. co m
        return type.getName();
    } else if (type.getPackage().equals(Package.getPackage("java.lang"))) {
        return type.getSimpleName();
    } else {
        String[] words = type.getName().split(" ");
        String fullClassName = words[words.length - 1];
        String[] path = fullClassName.split("\\.");
        int i = 0;
        while (!Character.isUpperCase(path[i + 1].charAt(0))) {
            path[i] = path[i].substring(0, 1);
            i++;
        }
        return StringUtils.join(path, ".");
    }
}