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.core.schema.SchemaClassResolver.java

public void addResourceClass(Class<?> iClass) {
    // ADD A NEW CLASS
    String name = iClass.getSimpleName();
    String currentPath = classLocations.get(name);
    String iPackagePrefix = iClass.getPackage().getName() + ".";
    if (currentPath != null) {
        // ALREADY EXISTS
        if (currentPath.equals(iPackagePrefix))
            // SAME PATH: PROBABLY THE JAR WAS SETTED MULTIPLE TIMES
            log.warn("[SchemaClassResolver.addResourceClass] Warning: found the class " + name
                    + " defined twice in the classpath and they point to the same package " + iPackagePrefix
                    + " Assure you have only one class to avoid alignment problems.");
        else//from   www  .  ja  va2s . com
            // ALREADY EXISTS
            log.warn("[SchemaClassResolver.addResourceClass] Found the class " + name
                    + " defined twice. Ignore current package " + iPackagePrefix + " Use the first one found: "
                    + currentPath);
    } else {
        if (log.isDebugEnabled())
            log.debug("[SchemaClassResolver.addResourceClass] > Loading class: " + name + " using the package: "
                    + iPackagePrefix);

        classLocations.put(name, iPackagePrefix);

        // WAKE UP LISTENERS ON THE NEW CLASS FOUND
        List<ClassLoaderListener> listeners = Controller.getInstance().getListeners(ClassLoaderListener.class);
        if (listeners != null) {
            for (ClassLoaderListener listener : listeners) {
                // INVOKE THE LISTENER
                listener.onClassLoading(iClass);
            }
        }
    }
}

From source file:org.gvnix.support.MessageBundleUtilsImpl.java

/**
 * Copy properties associated with the given class to the message bundle of
 * given language./*from   www.  j  a v  a 2  s  . c om*/
 * <p/>
 * Note that properties to add are taken from messages[_xx].properties files
 * and added to messages[_xx].properties in the destination project.
 * <p/>
 * <strong>This method doesn't check if messages[_xx].properties file exist
 * in the add-on invoking it</strong>
 * 
 * @param language Language locale as string (en, es, ca, ...)
 * @param invokingClass Class of the Add-on invoking this method. It's
 *        needed in order to load local resources
 * @param propFileOperations
 * @param projectOperations
 * @param fileManager
 */
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addPropertiesToMessageBundle(String language, Class invokingClass,
        PropFileOperations propFileOperations, ProjectOperations projectOperations, FileManager fileManager) {
    Properties properties = new Properties();
    LogicalPath webappPath = getWebProjectUtils().getWebappPath(projectOperations);

    String sourcePropertyFile = "/".concat(invokingClass.getPackage().getName()).replace('.', '/');

    // Take "en" as default language
    String targetFilePath = "/WEB-INF/i18n/messages.properties";
    String targetFile = projectOperations.getPathResolver().getIdentifier(webappPath, targetFilePath);

    try {
        if (language.equals("en")) {
            sourcePropertyFile = sourcePropertyFile.concat("/messages.properties");
            properties.load(invokingClass.getResourceAsStream(sourcePropertyFile));
        } else {
            targetFilePath = "/WEB-INF/i18n/messages_".concat(language).concat(".properties");
            targetFile = projectOperations.getPathResolver().getIdentifier(webappPath, targetFilePath);

            sourcePropertyFile = sourcePropertyFile.concat("/messages_".concat(language).concat(".properties"));
            properties.load(invokingClass.getResourceAsStream(sourcePropertyFile));
        }

        if (fileManager.exists(targetFile)) {
            propFileOperations.addProperties(webappPath, targetFilePath,
                    new HashMap<String, String>((Map) properties), true, true);
        } else {
            LOGGER.warning(targetFile.concat(" file doesn't exist in project."));
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE,
                "Message properties for language \"".concat(language).concat("\" can't be loaded"));
    }
}

From source file:org.apache.streams.plugins.StreamsScalaSourceGenerator.java

private String renderClass(Class<?> pojoClass) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("package ");
    stringBuffer.append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala"));
    stringBuffer.append(LS);/*from  w  w  w  . j  av  a 2 s  .com*/
    stringBuffer
            .append("import org.apache.commons.lang.builder.{HashCodeBuilder, EqualsBuilder, ToStringBuilder}");
    stringBuffer.append(LS);
    stringBuffer.append("class ").append(pojoClass.getSimpleName());
    stringBuffer.append(" (");

    Set<Field> fields = ReflectionUtils.getAllFields(pojoClass);
    appendFields(stringBuffer, fields, "var", ",");

    stringBuffer.append(")");
    stringBuffer.append(" extends ").append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala"))
            .append(".traits.").append(pojoClass.getSimpleName());
    stringBuffer.append(" with Serializable ");
    stringBuffer.append("{ ");
    stringBuffer.append(LS);
    stringBuffer.append("override def equals(obj: Any) = obj match { ");
    stringBuffer.append(LS);
    stringBuffer.append("  case other: ");
    stringBuffer.append(pojoClass.getSimpleName());
    stringBuffer.append(" => other.getClass == getClass && EqualsBuilder.reflectionEquals(this,obj)");
    stringBuffer.append(LS);
    stringBuffer.append("  case _ => false");
    stringBuffer.append(LS);
    stringBuffer.append("}");
    stringBuffer.append(LS);
    stringBuffer.append("override def hashCode = new HashCodeBuilder().hashCode");
    stringBuffer.append(LS);
    stringBuffer.append("}");

    return stringBuffer.toString();
}

From source file:name.ikysil.beanpathdsl.codegen.Context.java

private boolean isExcluded(Class<?> clazz) {
    if (clazz.isPrimitive() || clazz.isAnonymousClass() || clazz.isLocalClass() || clazz.isInterface()
            || clazz.isSynthetic() || clazz.isEnum() || !Modifier.isPublic(clazz.getModifiers())
            || (clazz.getPackage() == null)) {
        return true;
    }//from  www .j  a va  2s  .  co m
    IncludedClass includedConfig = includedClasses.get(clazz);
    if (includedConfig != null) {
        return false;
    }
    ExcludedClass excludedConfig = excludedClasses.get(clazz);
    if (excludedConfig != null) {
        return true;
    }
    for (ExcludedPackage excludedPackage : excludedPackages) {
        if (excludedPackage.match(clazz.getPackage())) {
            return true;
        }
    }
    return false;
}

From source file:org.getobjects.appserver.products.JoProductInfo.java

protected Class primaryLoadCode(WOApplication _app) {
    ClassLoader cl = this.classLoader();
    if (cl == null) {
        log.error("did not find class loader for product: " + this);
        return null;
    }//  w w w .  ja  v a 2  s. c o  m

    /* find/load product class */

    Class cls = null;
    try {
        cls = cl.loadClass(this.fqn + ".WOFramework");
    } catch (ClassNotFoundException e) {
    }

    /* hack for main package */
    if (cls == null && _app != null) {
        Class appCls = _app.getClass();
        if (this.fqn.equals(appCls.getPackage().getName()))
            cls = appCls;
    }

    if (cls == null)
        log.warn("did not find product class: " + this.fqn);

    return cls;
}

From source file:net.zcarioca.zcommons.config.source.spi.FilesystemConfigurationSourceServiceProvider.java

private File getConfigurationFileInSubDirs(File confDir, Class<?> referenceClass, Pattern pattern) {
    String path = referenceClass.getPackage().getName().replaceAll("\\.", File.separator);

    File filePath = new File(confDir, path);
    if (!filePath.isDirectory()) {
        if (logger.isDebugEnabled())
            logger.debug(format("Could not find directory %s", filePath));
        return null;
    }/*from   w  ww  .j  a v a2  s . co m*/

    return getFromPattern(filePath, pattern);
}

From source file:org.trpr.platform.integration.impl.xml.XMLTranscoderImpl.java

/**
 * Interface method implementation. Note that the package name specified should contain JAXB compatible generated classes/artifacts.
 * @see XMLTranscoder#unmarshal(String, Class)
 *//*from w  w w  . j  a v  a2s.  co  m*/
@SuppressWarnings("unchecked")
public <T> T unmarshal(String xml, Class<T> clazz) throws XMLDataException {
    StringReader stringReader = new StringReader(xml);
    try {
        if (this.getUnmarshaller() == this.defaultUnmarshaller) {
            // the default unmarshaller is not initialized with the context path. Initialize it by calling suitable methods
            this.defaultUnmarshaller.setContextPath(clazz.getPackage().getName());
            this.defaultUnmarshaller.afterPropertiesSet();
        }
        return (T) this.getUnmarshaller().unmarshal(new StreamSource(stringReader));
    } catch (Exception e) {
        throw new XMLDataException(
                "Error unmarshalling XML. XML:packageName is " + xml + ":" + clazz.getPackage().getName(), e);
    } finally {
        stringReader.close();
    }
}

From source file:io.swagger.jaxrs.config.BeanConfig.java

public Set<Class<?>> classes() {
    ConfigurationBuilder config = new ConfigurationBuilder();
    Set<String> acceptablePackages = new HashSet<String>();

    boolean allowAllPackages = false;

    if (resourcePackage != null && !"".equals(resourcePackage)) {
        String[] parts = resourcePackage.split(",");
        for (String pkg : parts) {
            if (!"".equals(pkg)) {
                acceptablePackages.add(pkg);
                config.addUrls(ClasspathHelper.forPackage(pkg));
            }/*www.  j  a v  a  2s .c om*/
        }
    } else {
        allowAllPackages = true;
    }

    config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());

    final Reflections reflections = new Reflections(config);
    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(javax.ws.rs.Path.class);
    classes.addAll(reflections.getTypesAnnotatedWith(SwaggerDefinition.class));

    Set<Class<?>> output = new HashSet<Class<?>>();
    for (Class<?> cls : classes) {
        if (allowAllPackages) {
            output.add(cls);
        } else {
            for (String pkg : acceptablePackages) {
                if (cls.getPackage().getName().startsWith(pkg)) {
                    output.add(cls);
                }
            }
        }
    }
    return output;
}

From source file:org.dasein.cloud.aws.AWSCloud.java

static public Logger getLogger(Class<?> cls) {
    String pkg = getLastItem(cls.getPackage().getName());

    if (pkg.equals("aws")) {
        pkg = "";
    } else {//from  w  w  w  .ja  v  a2  s  .  c  o  m
        pkg = pkg + ".";
    }
    return Logger.getLogger("dasein.cloud.aws.std." + pkg + getLastItem(cls.getName()));
}

From source file:atg.tools.dynunit.nucleus.NucleusUtils.java

/**
 * A convenience method for returning the configpath for a test.
 * pConfigDirectory is the top level name to be used for the configpath.
 * Returns a file in the baseConfigDirectory (or baseConfigDirectory +
 * "data") subdirectory of the the passed in class's location.<P>
 * <p/>/*from   w ww  .ja va2  s. c  o  m*/
 * The directory location is calculated as (in psuedo-code):
 * <code>
 * (classRelativeTo's package location) + "/" + (pConfigDirectory or "data") + "/config"
 * </code>
 *
 * @param classRelativeTo
 *         the class whose package the config/data
 *         (or baseConfigDirectory/data) should be relative in.
 * @param baseConfigDirectory
 *         the base configuration directory If null,
 *         uses "config".
 * @param createDirectory
 *         whether to create the config/data subdirectory if
 *         it does not exist.
 *
 * @return The calculated configuration path.
 */
public static File getConfigPath(Class classRelativeTo, String baseConfigDirectory, boolean createDirectory) {
    Map<String, File> baseConfigToFile = configPath.get(classRelativeTo);
    if (baseConfigToFile == null) {
        baseConfigToFile = new ConcurrentHashMap<String, File>();
        configPath.put(classRelativeTo, baseConfigToFile);
    }

    File fileFound = baseConfigToFile.get(baseConfigDirectory);

    if (!baseConfigToFile.containsKey(baseConfigDirectory)) {
        String configdirname = "config";
        String packageName = StringUtils.replaceChars(classRelativeTo.getPackage().getName(), '.', '/');
        if (baseConfigDirectory != null) {
            configdirname = baseConfigDirectory;
        }

        String configFolder = packageName + "/data/" + configdirname;
        URL dataURL = classRelativeTo.getClassLoader().getResource(configFolder);

        // Mkdir
        if (dataURL == null) {
            URL root = classRelativeTo.getClassLoader().getResource(packageName);

            File f = null;
            if (root != null) {
                f = new File(root.getFile());
            }
            File f2 = new File(f, "/data/" + configdirname);
            if (createDirectory) {
                f2.mkdirs();
            }
            dataURL = NucleusUtils.class.getClassLoader().getResource(configFolder);
            if (dataURL == null) {
                System.err.println("Warning: Could not find resource \"" + configFolder + "\" in CLASSPATH");
            }
        }
        if (dataURL != null) {// check if this URL is contained within a jar file
            // if so, extract to a temp dir, otherwise just return
            // the directory
            fileFound = extractJarDataURL(dataURL);
            baseConfigToFile.put(baseConfigDirectory, fileFound);
        }
    }
    if (fileFound != null) {
        System.setProperty("atg.configpath", fileFound.getAbsolutePath());
    }
    return fileFound;
}