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.romaframework.aspect.reporting.jr.template.TemplateManagerImpl.java

private File getClassDirectory(SchemaClassDefinition classDefinition) {
    String packageFile;/*  w  ww. ja v  a 2s  .  c  om*/
    final Class<?> toSave = ((SchemaClassReflection) classDefinition.getSchemaClass()).getLanguageType();
    packageFile = toSave.getPackage().getName();
    packageFile = Utility.getResourcePath(packageFile);
    log.info("GetClassDirectory : " + Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR);
    final File templateDir = new File(
            getClass().getResource(Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR).getFile());
    return templateDir;
}

From source file:com.netspective.sparx.value.BasicDbHttpServletValueContext.java

public String getClassSourceHtml(Class cls, boolean showShortClassName) {
    String className = cls.getName();
    String packageName = cls.getPackage().getName();
    String classNameNoInner = className.replace('$', '.');
    String classNameShort = classNameNoInner.substring(packageName.length() + 1);
    String showClassName = showShortClassName ? classNameShort : className;

    if (packageName.startsWith("java.lang"))
        return "<span title='" + className + "'>" + showClassName + "</span>";
    else {/*  www . j av  a 2  s  .  c om*/
        String classJavaSourceFileName = ClassPath.getClassFileName(className);
        if (classJavaSourceFileName == null)
            return "<span title='" + className + "'>" + showClassName + "</span>";
        else {
            File classJavaSourceFile = new File(classJavaSourceFileName);
            if (classJavaSourceFile.exists()) {
                String servletRootPath = getHttpServlet().getServletContext().getRealPath("");
                if (classJavaSourceFile.getAbsolutePath().startsWith(servletRootPath)) {
                    String relativePath = classJavaSourceFile.getAbsolutePath()
                            .substring(servletRootPath.length());
                    String relativePathProperDelims = relativePath.replace('\\', '/');
                    String relativePathProperExtn = relativePathProperDelims.substring(0,
                            relativePathProperDelims.length() - ".class".length()) + ".java";
                    return "<a href='" + getConsoleUrl() + "/project/files/" + relativePathProperExtn
                            + "' title='" + className + " (" + classJavaSourceFileName + ")'>" + showClassName
                            + "</a>";
                } else
                    return "<span title='" + className + " (" + classJavaSourceFileName + ")'>" + showClassName
                            + "</span>";

            } else
                return "<span title='" + classJavaSourceFileName + "'>" + showClassName + "</span>";
        }
    }
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {/* ww w. j ava  2s. co  m*/
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr4"));
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

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

public synchronized void saveTemplate(JasperDesign design, SchemaClassDefinition clazz) throws Exception {

    log.info("[TemplateManager] Saving Template: " + design.getName());
    final Class<?> toSave = ((SchemaClassReflection) clazz.getSchemaClass()).getLanguageType();
    String packageFile = toSave.getPackage().getName();
    packageFile = Utility.getResourcePath(packageFile);
    log.info("SaveTemplate : " + Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR
            + design.getName() + JRXML_EXTENSION);
    File fileToSave = new File(
            getClass().getResource(Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR).getFile()
                    + design.getName() + JRXML_EXTENSION);

    FileOutputStream file2 = new FileOutputStream(fileToSave);
    JRXmlWriter.writeReport(design, file2, UTF_8);
    file2.close();/*from   ww w .  j a va  2s  .  co  m*/
    Roma.component(AutoReloadManager.class).addResource(fileToSave, this);

}

From source file:org.eclipse.wb.internal.rcp.databinding.emf.model.bindables.PropertiesSupport.java

private Map<String, ClassInfo> loadEmfClassInfos(IType literalsType, Set<String> allClasses) throws Exception {
    Class<?> literalsClass = m_classLoader.loadClass(literalsType.getFullyQualifiedName());
    String packageName = literalsClass.getPackage().getName();
    Map<String, ClassInfo> packageClasses = Maps.newHashMap();
    String literalsReference = literalsType.getFullyQualifiedName('.') + ".";
    List<Field> eClasses = Lists.newArrayList();
    List<Field> eProperties = Lists.newArrayList();
    // collect literals
    for (Field field : literalsClass.getFields()) {
        Class<?> fieldType = field.getType();
        if (m_EClass.isAssignableFrom(fieldType)) {
            eClasses.add(field);/*from w  w w  .j  ava 2s.  c o m*/
        } else if (m_EAttribute.isAssignableFrom(fieldType) || m_EReference.isAssignableFrom(fieldType)
                || m_EStructuralFeature.isAssignableFrom(fieldType)) {
            eProperties.add(field);
        }
    }
    // process EClass & its properties
    for (Field eClassField : eClasses) {
        String fieldName = eClassField.getName();
        ClassInfo classInfo = new ClassInfo(fieldName);
        packageClasses.put(fieldName, classInfo);
        //
        String unformatClassName = packageName + "." + EmfCodeGenUtil.unformat(classInfo.className);
        //
        try {
            classInfo.thisClass = m_classLoader.loadClass(unformatClassName);
        } catch (Throwable e) {
            for (String className : allClasses) {
                if (unformatClassName.equalsIgnoreCase(className)) {
                    try {
                        classInfo.thisClass = m_classLoader.loadClass(className);
                    } catch (Throwable t) {
                    }
                }
            }
        }
        //
        String propertyPrefix = fieldName + "__";
        for (Field ePropertyField : eProperties) {
            String propertyName = ePropertyField.getName();
            if (propertyName.startsWith(propertyPrefix)) {
                classInfo.properties.add(new PropertyInfo(classInfo, literalsReference + propertyName,
                        propertyName.substring(propertyPrefix.length())));
            }
        }
    }
    //
    for (ClassInfo classInfo : packageClasses.values()) {
        linkClassProperties(classInfo);
    }
    //
    return packageClasses;
}

From source file:com.cloud.agent.AgentShell.java

public void init(String[] args) throws ConfigurationException {

    final ComponentLocator locator = ComponentLocator.getLocator("agent");

    final Class<?> c = this.getClass();
    _version = c.getPackage().getImplementationVersion();
    if (_version == null) {
        throw new CloudRuntimeException("Unable to find the implementation version of this agent");
    }/*from  w ww . j a va  2 s . c  o  m*/
    s_logger.info("Implementation Version is " + _version);

    loadProperties();
    parseCommand(args);

    List<String> properties = Collections.list((Enumeration<String>) _properties.propertyNames());
    for (String property : properties) {
        s_logger.debug("Found property: " + property);
    }

    _storage = locator.getManager(StorageComponent.class);
    if (_storage == null) {
        s_logger.info("Defaulting to using properties file for storage");
        _storage = new PropertiesStorage();
        _storage.configure("Storage", new HashMap<String, Object>());
    }

    // merge with properties from command line to let resource access
    // command line parameters
    for (Map.Entry<String, Object> cmdLineProp : getCmdLineProperties().entrySet()) {
        _properties.put(cmdLineProp.getKey(), cmdLineProp.getValue());
    }

    final Adapters adapters = locator.getAdapters(BackoffAlgorithm.class);
    final Enumeration en = adapters.enumeration();
    while (en.hasMoreElements()) {
        _backoff = (BackoffAlgorithm) en.nextElement();
        break;
    }
    if (en.hasMoreElements()) {
        s_logger.info("More than one backoff algorithm specified.  Using the first one ");
    }

    if (_backoff == null) {
        s_logger.info("Defaulting to the constant time backoff algorithm");
        _backoff = new ConstantTimeBackoff();
        _backoff.configure("ConstantTimeBackoff", new HashMap<String, Object>());
    }
}

From source file:org.makersoft.mvc.builder.PackageBasedUrlPathBuilder.java

/**
 * ?Controller?URL//from w ww  .ja v  a 2  s .co  m
 * 
 * @param clazz
 *            Controller
 * @return URL Path
 */
public String[] buildUrlPath(Class<?> controllerClass, String methodName, String... values) {

    // Skip classes that can't be instantiated
    if (cannotInstantiate(controllerClass)) {
        if (LOG.isTraceEnabled())
            LOG.trace("Class [#0] did not pass the instantiation test and will be ignored",
                    controllerClass.getName());
    }

    // Determine the action package
    String controllerPackage = controllerClass.getPackage().getName();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing class [#0] in package [#1]", controllerClass.getName(), controllerPackage);
    }

    // Determine the default namespace and action name
    String namespace = determineControllerNamespace(controllerClass);

    String defaultControllerName = determineControllerName(controllerClass);

    // reversion
    String[] urlPaths = null;

    // fixed root path
    if (root.equals(defaultControllerName + "#" + methodName)) {
        urlPaths = new String[] { "/" };
    } else if (values.length != 0) {
        urlPaths = new String[values.length];
        for (int i = 0; i < values.length; i++) {
            String value = values[i];
            urlPaths[i] = namespace + "/" + defaultControllerName + value;
        }
    } else {
        urlPaths = new String[] { namespace + "/" + defaultControllerName };
    }

    return urlPaths;
}

From source file:com.github.venkateshamurthy.designpatterns.builders.TestFluentBuilders.java

/**
* Gets the file.//w  ww  .j a v a  2 s.  c o m
* 
* @param baseFolder
*            the base folder
* @param pojo
*            the pojo
* @return the file
*/
private File getFile(File baseFolder, Class<?> pojo) {
    return new File(baseFolder,
            pojo.getPackage().getName().replace('.', '/') + "/" + pojo.getSimpleName() + "Builder.java");
}

From source file:com.opensymphony.xwork2.util.finder.DefaultClassFinder.java

public DefaultClassFinder(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 ww  . j a  v a  2s .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:org.openspotlight.graph.query.AbstractGeneralQueryTest.java

/**
 * Adds the class implements interface links.
 * /*ww  w .j  a va 2  s  . c o  m*/
 * @param root the root
 * @param clazz the clazz
 * @param javaClass the java class
 */
private void addClassImplementsInterfaceLinks(final Context root, final Class<?> clazz,
        final JavaClass javaClass) {
    final Class<?>[] iFaces = clazz.getInterfaces();
    for (final Class<?> iFace : iFaces) {
        final Package iFacePack = iFace.getPackage();
        final JavaPackage javaPackage = writer.addNode(root, JavaPackage.class, iFacePack.getName());
        // javaPackage.setCaption(iFacePack.getName());
        final JavaInterface javaInterface = writer.addChildNode(javaPackage, JavaInterface.class,
                iFace.getName());
        // javaInterface.setCaption(iFace.getName());
        final ClassImplementsInterface link = writer.addLink(ClassImplementsInterface.class, javaClass,
                javaInterface);
        link.setTag(randomTag());
    }
}