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.apache.struts2.convention.Java8ClassFinder.java

public Java8ClassFinder(List<Class> classes) {
    this.classLoaderInterface = null;
    List<Info> infos = new ArrayList<Info>();
    List<Package> packages = new ArrayList<Package>();
    for (Class clazz : classes) {

        Package aPackage = clazz.getPackage();
        if (aPackage != null && !packages.contains(aPackage)) {
            infos.add(new PackageInfo(aPackage));
            packages.add(aPackage);//w w w .java2  s .  c  om
        }

        ClassInfo classInfo = new ClassInfo(clazz, this);
        infos.add(classInfo);
        classInfos.put(classInfo.getName(), classInfo);
        for (Method method : clazz.getDeclaredMethods()) {
            infos.add(new MethodInfo(classInfo, method));
        }

        for (Constructor constructor : clazz.getConstructors()) {
            infos.add(new MethodInfo(classInfo, constructor));
        }

        for (Field field : clazz.getDeclaredFields()) {
            infos.add(new FieldInfo(classInfo, field));
        }
    }

    for (Info info : infos) {
        for (AnnotationInfo annotation : info.getAnnotations()) {
            List<Info> annotationInfos = getAnnotationInfos(annotation.getName());
            annotationInfos.add(info);
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.DataManager.java

/**
 * Get the persistence handler defined for the specified entity type. If no
 * persistence handler found for the current class, search thru the super
 * classes to see if a handler is defined for any?
 * /*from  ww  w  .  j a  va  2  s  .co m*/
 * @param type
 *            - Class of the Entity.
 * @return
 * @throws Exception
 */
public AbstractPersister getPersister(final Class<?> type) throws Exception {
    String key = type.getCanonicalName();
    if (persistmap.containsKey(key))
        return persistmap.get(key);
    Class<?> ttype = type;
    key = type.getPackage().getName();
    if (persistmap.containsKey(key))
        return persistmap.get(key);
    while (true) {
        ttype = ttype.getSuperclass();
        if (ttype.getCanonicalName().compareTo(Object.class.getCanonicalName()) == 0) {
            break;
        }
        key = ttype.getCanonicalName();
        if (persistmap.containsKey(key))
            return persistmap.get(key);
    }
    throw new Exception("No persistence handler found for class [" + type.getCanonicalName() + "]");
}

From source file:org.romaframework.aspect.reporting.jr.template.TemplateManagerImpl.java

private InputStream getBaseClassSubDesign(Class<?> objectClass) {
    if (objectClass.equals(Object.class)) {
        return null;
    }//  w w  w . j  av a  2  s  .  c  o  m

    String packageFile = objectClass.getPackage().getName();
    packageFile = Utility.getResourcePath(packageFile);
    log.info("GetBaseClassSubDesign : " + Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR);
    URL resource = getClass().getResource(Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR
            + objectClass.getSimpleName() + Utility.PACKAGE_SEPARATOR_STRING + SUBTEMPLATE + JRXML_EXTENSION);
    if (resource == null) {
        return getBaseClassSubDesign(objectClass.getSuperclass());
    } else {
        log.info("GetBaseClassDesign file :" + resource.getFile());
        // log.info("GetBaseClassDesign file in jar : " + resource.getFile());
        final InputStream baseClassTemplate = VirtualFileFactory.getInstance().getFile(resource)
                .getInputStream();
        // log.info("GetBaseClassDesign file input String : " +
        // baseClassTemplate);
        return baseClassTemplate;
    }
}

From source file:org.romaframework.aspect.reporting.jr.template.TemplateManagerImpl.java

private InputStream getBaseClassDesign(Class<?> objectClass) {
    if (objectClass.equals(Object.class)) {
        return null;
    }/*from  ww w.  ja v a2s.c o  m*/
    String packageFile = objectClass.getPackage().getName();
    packageFile = Utility.getResourcePath(packageFile);
    log.info("GetBaseClassDesign: " + Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR
            + objectClass.getSimpleName() + Utility.PACKAGE_SEPARATOR_STRING + TEMPLATE + JRXML_EXTENSION);

    String resourceString = Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR
            + objectClass.getSimpleName() + Utility.PACKAGE_SEPARATOR_STRING + TEMPLATE + JRXML_EXTENSION;
    URL resource = getClass().getResource(resourceString);

    if (resource == null) {
        return getBaseClassDesign(objectClass.getSuperclass());
    } else {
        log.info("GetBaseClassDesign file :" + resource.getFile());
        // log.info("GetBaseClassDesign file in jar : " + resource.getFile());
        final InputStream baseClassTemplate = VirtualFileFactory.getInstance().getFile(resource)
                .getInputStream();
        // log.info("GetBaseClassDesign file input String : " +
        // baseClassTemplate);
        return baseClassTemplate;

    }
}

From source file:org.apache.struts2.convention.DefaultClassFinder.java

public DefaultClassFinder(List<Class> classes) {
    this.classLoaderInterface = null;
    List<Info> infos = new ArrayList<>();
    List<Package> packages = new ArrayList<>();
    for (Class clazz : classes) {

        Package aPackage = clazz.getPackage();
        if (aPackage != null && !packages.contains(aPackage)) {
            infos.add(new PackageInfo(aPackage));
            packages.add(aPackage);/*w w  w.  j a v  a2  s  . com*/
        }

        ClassInfo classInfo = new ClassInfo(clazz, this);
        infos.add(classInfo);
        classInfos.put(classInfo.getName(), classInfo);
        for (Method method : clazz.getDeclaredMethods()) {
            infos.add(new MethodInfo(classInfo, method));
        }

        for (Constructor constructor : clazz.getConstructors()) {
            infos.add(new MethodInfo(classInfo, constructor));
        }

        for (Field field : clazz.getDeclaredFields()) {
            infos.add(new FieldInfo(classInfo, field));
        }
    }

    for (Info info : infos) {
        for (AnnotationInfo annotation : info.getAnnotations()) {
            List<Info> annotationInfos = getAnnotationInfos(annotation.getName());
            annotationInfos.add(info);
        }
    }
}

From source file:com.amalto.core.storage.hibernate.FlatTypeMapping.java

private Object createReferencedObject(Session session, ComplexTypeMetadata referencedType,
        Class<?> referencedClass, Object referencedIdValue)
        throws InstantiationException, IllegalAccessException {
    if (referencedIdValue == null) {
        return null; // Means no reference (reference is null).
    }//  w w  w  .  ja  v  a 2  s. c o m
    if (referencedIdValue instanceof Wrapper) {
        return referencedIdValue; // It's already the referenced object.
    }
    // Try to load object from current session
    if (referencedIdValue instanceof DataRecord) {
        Serializable referencedValueId;
        DataRecord idAsDataRecord = (DataRecord) referencedIdValue;
        Collection<FieldMetadata> keyFields = idAsDataRecord.getType().getKeyFields();
        if (keyFields.size() == 1) {
            referencedValueId = (Serializable) idAsDataRecord.get(keyFields.iterator().next());
        } else {
            ClassLoader storageClassLoader = Thread.currentThread().getContextClassLoader();
            List<Object> ids = new LinkedList<Object>();
            for (FieldMetadata keyField : keyFields) {
                ids.add(idAsDataRecord.get(keyField));
            }
            referencedValueId = createCompositeId(storageClassLoader, referencedClass, ids);
        }
        // should actually load the object to validate the FK (for Record Validation), check by ThreadLocal won't affect performance or block function
        if (DataRecord.ValidateRecord.get()) {
            Object sessionObject = session.get(referencedClass, referencedValueId);
            if (sessionObject == null) {
                throw new ValidateException(
                        "Invalid foreign key: [" + referencedClass.getName() + "#" + referencedValueId //$NON-NLS-1$ //$NON-NLS-2$
                                + "] doesn't exist."); //$NON-NLS-1$
            } else {
                return sessionObject;
            }
        } else {
            Object sessionObject = session.load(referencedClass, referencedValueId);
            if (sessionObject != null) {
                return sessionObject;
            }
        }
    } else {
        throw new NotImplementedException("Unexpected state."); //$NON-NLS-1$
    }
    Class<?> fieldJavaType = referencedIdValue.getClass();
    // Null package might happen with proxy classes generated by Hibernate
    if (fieldJavaType.getPackage() != null && fieldJavaType.getPackage().getName().startsWith("java.")) { //$NON-NLS-1$
        Wrapper referencedObject = (Wrapper) referencedClass.newInstance();
        for (FieldMetadata fieldMetadata : referencedType.getFields()) {
            if (fieldMetadata.isKey()) {
                referencedObject.set(fieldMetadata.getName(), referencedIdValue);
            }
        }
        return referencedObject;
    } else {
        return referencedIdValue;
    }
}

From source file:com.amalto.core.storage.hibernate.SystemScatteredTypeMapping.java

private Object getReferencedObject(ClassLoader storageClassLoader, Session session,
        ComplexTypeMetadata referencedType, Object referencedIdValue) {
    Class<?> referencedClass;
    try {/*w ww. ja va  2 s  .  c  o  m*/
        referencedClass = ((StorageClassLoader) storageClassLoader).getClassFromType(referencedType);
    } catch (Exception e) {
        throw new RuntimeException("Could not get class for type '" + referencedType.getName() + "'", e);
    }
    try {
        if (referencedIdValue == null) {
            return null; // Means no reference (reference is null).
        }
        if (referencedIdValue instanceof Wrapper) {
            return referencedIdValue; // It's already the referenced object.
        }
        // Try to load object from current session
        if (referencedIdValue instanceof List) {
            // Handle composite id values
            Serializable result;
            try {
                Class<?> idClass = storageClassLoader.loadClass(referencedClass.getName() + "_ID"); //$NON-NLS-1$
                Class[] parameterClasses = new Class[((List) referencedIdValue).size()];
                int i = 0;
                for (Object o : (List) referencedIdValue) {
                    if (o == null) {
                        throw new IllegalStateException("Id cannot have a null value.");
                    }
                    parameterClasses[i++] = o.getClass();
                }
                Constructor<?> constructor = idClass.getConstructor(parameterClasses);
                result = (Serializable) constructor.newInstance(((List) referencedIdValue).toArray());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Serializable referencedValueId = result;

            Object sessionObject = session.load(referencedClass, referencedValueId);
            if (sessionObject != null) {
                return sessionObject;
            }
        } else if (referencedIdValue instanceof Serializable) {
            Object sessionObject = session.load(referencedClass, (Serializable) referencedIdValue);
            if (sessionObject != null) {
                return sessionObject;
            }
        } else {
            throw new NotImplementedException("Unexpected state.");
        }
        Class<?> fieldJavaType = referencedIdValue.getClass();
        // Null package might happen with proxy classes generated by Hibernate
        if (fieldJavaType.getPackage() != null && fieldJavaType.getPackage().getName().startsWith("java.")) { //$NON-NLS-1$
            Wrapper referencedObject = (Wrapper) referencedClass.newInstance();
            for (FieldMetadata fieldMetadata : referencedType.getFields()) {
                if (fieldMetadata.isKey()) {
                    referencedObject.set(fieldMetadata.getName(), referencedIdValue);
                }
            }
            return referencedObject;
        } else {
            return referencedIdValue;
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not create referenced object of type '" + referencedClass
                + "' with id '" + String.valueOf(referencedIdValue) + "'", e);
    }
}

From source file:org.apache.struts2.config.ClasspathConfigurationProvider.java

/**
 * Create a default action mapping for a class instance.
 *
 * The namespace annotation is honored, if found, otherwise
 * the Java package is converted into the namespace
 * by changing the dots (".") to slashes ("/").
 *
 * @param cls Action or POJO instance to process
 * @param pkgs List of packages that were scanned for Actions
 *//*w  ww .j  a  v  a  2s  .  c  o  m*/
protected void processActionClass(Class cls, String[] pkgs) {
    String name = cls.getName();
    String actionPackage = cls.getPackage().getName();
    String actionNamespace = null;
    String actionName = null;
    for (String pkg : pkgs) {
        if (name.startsWith(pkg)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("ClasspathConfigurationProvider: Processing class " + name);
            }
            name = name.substring(pkg.length() + 1);

            actionNamespace = "";
            actionName = name;
            int pos = name.lastIndexOf('.');
            if (pos > -1) {
                actionNamespace = "/" + name.substring(0, pos).replace('.', '/');
                actionName = name.substring(pos + 1);
            }
            break;
        }
    }

    PackageConfig pkgConfig = loadPackageConfig(actionNamespace, actionPackage, cls);

    // In case the package changed due to namespace annotation processing
    if (!actionPackage.equals(pkgConfig.getName())) {
        actionPackage = pkgConfig.getName();
    }

    Annotation annotation = cls.getAnnotation(ParentPackage.class);
    if (annotation != null) {
        String parent = ((ParentPackage) annotation).value();
        PackageConfig parentPkg = configuration.getPackageConfig(parent);
        if (parentPkg == null) {
            throw new ConfigurationException(
                    "ClasspathConfigurationProvider: Unable to locate parent package " + parent, annotation);
        }
        pkgConfig.addParent(parentPkg);

        if (!TextUtils.stringSet(pkgConfig.getNamespace()) && TextUtils.stringSet(parentPkg.getNamespace())) {
            pkgConfig.setNamespace(parentPkg.getNamespace());
        }
    }

    // Truncate Action suffix if found
    if (actionName.endsWith(ACTION)) {
        actionName = actionName.substring(0, actionName.length() - ACTION.length());
    }

    // Force initial letter of action to lowercase, if desired
    if ((forceLowerCase) && (actionName.length() > 1)) {
        int lowerPos = actionName.lastIndexOf('/') + 1;
        StringBuilder sb = new StringBuilder();
        sb.append(actionName.substring(0, lowerPos));
        sb.append(Character.toLowerCase(actionName.charAt(lowerPos)));
        sb.append(actionName.substring(lowerPos + 1));
        actionName = sb.toString();
    }

    ActionConfig actionConfig = new ActionConfig();
    actionConfig.setClassName(cls.getName());
    actionConfig.setPackageName(actionPackage);

    actionConfig.setResults(new ResultMap<String, ResultConfig>(cls, actionName, pkgConfig));
    pkgConfig.addActionConfig(actionName, actionConfig);
}

From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java

/**
 * Determine imports for the given bundle. Based on the user settings, this
 * method will consider only the the test hierarchy until the testing
 * framework is found or all classes available inside the test bundle. <p/>
 * Note that split packages are not supported.
 * /*from w  ww  .j a v  a2s  .  c o m*/
 * @return
 */
private String[] determineImports() {

    boolean useTestClassOnly = false;

    // no jar entry present, bail out.
    if (jarEntries == null || jarEntries.isEmpty()) {
        logger.debug("No test jar content detected, generating bundle imports from the test class");
        useTestClassOnly = true;
    }

    else if (createManifestOnlyFromTestClass()) {
        logger.info("Using the test class for generating bundle imports");
        useTestClassOnly = true;
    } else
        logger.info("Using all classes in the jar for the generation of bundle imports");

    // className, class resource
    Map entries;

    if (useTestClassOnly) {

        entries = new LinkedHashMap(4);

        // get current class (test class that bootstraps the OSGi infrastructure)
        Class<?> clazz = getClass();
        String clazzPackage = null;
        String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName();

        do {

            // consider inner classes as well
            List classes = new ArrayList(4);
            classes.add(clazz);
            CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes);

            for (Iterator iterator = classes.iterator(); iterator.hasNext();) {
                Class<?> classToInspect = (Class) iterator.next();

                Package pkg = classToInspect.getPackage();
                if (pkg != null) {
                    clazzPackage = pkg.getName();
                    String classFile = ClassUtils.getClassFileName(classToInspect);
                    entries.put(classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX),
                            new InputStreamResource(classToInspect.getResourceAsStream(classFile)));
                }
                // handle default package
                else {
                    logger.warn("Could not find package for class " + classToInspect + "; ignoring...");
                }
            }

            clazz = clazz.getSuperclass();

        } while (!endPackage.equals(clazzPackage));
    } else
        entries = jarEntries;

    return determineImportsFor(entries);

}

From source file:org.apache.hadoop.yarn.webapp.hamlet.HamletGen.java

/**
 * Generate a specific Hamlet implementation from a spec.
 * @param specClass holds hamlet interfaces. e.g. {@link HamletSpec}
 * @param implClass a generic hamlet implementation. e.g. {@link HamletImpl}
 * @param outputName name of the output class. e.g. {@link Hamlet}
 * @param outputPkg package name of the output class.
 * @throws IOException/*from w ww .  ja  v a 2s .  c om*/
 */
public void generate(Class<?> specClass, Class<?> implClass, String outputName, String outputPkg)
        throws IOException {
    LOG.info("Generating {} using {} and {}", new Object[] { outputName, specClass, implClass });
    out = new PrintWriter(outputName + ".java", "UTF-8");
    hamlet = basename(outputName);
    String pkg = pkgName(outputPkg, implClass.getPackage().getName());
    puts(0, "// Generated by HamletGen. Do NOT edit!\n", "package ", pkg, ";\n",
            "import java.io.PrintWriter;\n", "import java.util.EnumSet;\n",
            "import static java.util.EnumSet.*;\n", "import static ", implClass.getName(), ".EOpt.*;\n",
            "import org.apache.hadoop.yarn.webapp.SubView;");
    String implClassName = implClass.getSimpleName();
    if (!implClass.getPackage().getName().equals(pkg)) {
        puts(0, "import ", implClass.getName(), ';');
    }
    puts(0, "\n", "public class ", hamlet, " extends ", implClassName, " implements ",
            specClass.getSimpleName(), "._Html {\n", "  public ", hamlet, "(PrintWriter out, int nestLevel,",
            " boolean wasInline) {\n", "    super(out, nestLevel, wasInline);\n", "  }\n\n", // inline is context sensitive
            "  static EnumSet<EOpt> opt(boolean endTag, boolean inline, ", "boolean pre) {\n",
            "    EnumSet<EOpt> opts = of(ENDTAG);\n", "    if (!endTag) opts.remove(ENDTAG);\n",
            "    if (inline) opts.add(INLINE);\n", "    if (pre) opts.add(PRE);\n", "    return opts;\n",
            "  }");
    initLut(specClass);
    genImpl(specClass, implClassName, 1);
    LOG.info("Generating {} methods", hamlet);
    genMethods(hamlet, top, 1);
    puts(0, "}");
    out.close();
    LOG.info("Wrote {} bytes to {}.java", bytes, outputName);
}