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:com.appspresso.api.AxLog.java

private static String getTagName(Class<?> klass) {
    if (klass == null) {
        return DEF_TAG;
    }/*w w w  . j  a va  2 s. c o  m*/
    StringBuilder result = new StringBuilder(MAX_TAG_LEN);
    String className = klass.getSimpleName();
    result.append(className);
    String packageName = klass.getPackage().getName();
    for (String token : packageName.split(".")) {
        if (className.length() > MAX_TAG_LEN) {
            result.insert(0, "..");
            break;
        }
        result.insert(0, token.charAt(0)).insert(0, '.');
    }
    return result.toString();
}

From source file:org.cellprofiler.preferences.CellProfilerPreferences.java

/**
 * Add an override to the override list.
 * @param c//from  www  .j  a v a 2 s  . com
 * @param key
 * @param value
 */
private static void addOverride(Class<?> c, String key, String value) {
    String path = "/" + c.getPackage().getName().replace(".", "/");
    String prefKey = c.getSimpleName() + "." + key;
    PreferenceOverride override = new PreferenceOverride(path, prefKey, value);
    overrides.add(override);
}

From source file:org.seedstack.seed.core.utils.SeedReflectionUtils.java

/**
 * Check if the class clazz has the annotation annotationClass up in the hierarchy.
 *
 * @param clazz           The class to search from.
 * @param annotationClass The annotation class to search.
 * @return true if annotation is present, false otherwise.
 */// w ww .  j  a va  2  s  . com
public static boolean hasAnnotationDeep(Class<?> clazz, Class<? extends Annotation> annotationClass) {

    if (clazz.equals(annotationClass)) {
        return true;
    }

    for (Annotation anno : clazz.getAnnotations()) {
        Class<? extends Annotation> annoClass = anno.annotationType();
        if (!annoClass.getPackage().getName().startsWith(JAVA_LANG)
                && hasAnnotationDeep(annoClass, annotationClass)) {
            return true;
        }
    }

    return false;
}

From source file:ch.entwine.weblounge.common.impl.util.TemplateUtils.java

/**
 * Loads the resource identified by concatenating the package name from
 * <code>clazz</code> and <code>path</code> from the classpath.
 * /*  ww w.  j a  va  2s  . c o  m*/
 * @param path
 *          the path relative to the package name of <code>clazz</code>
 * @param clazz
 *          the class
 * @param language
 *          the requested language
 * @param site
 *          the associated site
 * @return the resource
 */
public static String load(String path, Class<?> clazz, Language language, Site site) {
    if (path == null)
        throw new IllegalArgumentException("path cannot be null");
    if (clazz == null)
        throw new IllegalArgumentException("clazz cannot be null");

    String pkg = null;
    if (!path.startsWith("/"))
        pkg = "/" + clazz.getPackage().getName().replace('.', '/');

    // Try to find the template in any of the usual languages
    InputStream is = null;
    String[] templates = null;
    if (site != null)
        templates = LanguageUtils.getLanguageVariants(path, language, site.getDefaultLanguage());
    else
        templates = LanguageUtils.getLanguageVariants(path, language);
    for (String template : templates) {
        String pathToTemplate = pkg != null ? UrlUtils.concat(pkg, template) : template;
        is = clazz.getResourceAsStream(pathToTemplate);
        if (is != null) {
            path = template;
            break;
        }
    }

    // If is is still null, then the template doesn't exist.
    if (is == null) {
        logger.error("Template " + path + " not found in any language");
        return null;
    }

    // Load the template
    InputStreamReader isr = null;
    StringBuffer buf = new StringBuffer();
    try {
        logger.debug("Loading " + path);
        isr = new InputStreamReader(is, Charset.forName("UTF-8"));
        char[] chars = new char[1024];
        int count = 0;
        while ((count = isr.read(chars)) > 0) {
            for (int i = 0; i < count; i++)
                buf.append(chars[i]);
        }
        return buf.toString();
    } catch (Throwable t) {
        logger.warn("Error reading " + path + ": " + t.getMessage());
    } finally {
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
    logger.debug("Template " + path + " loaded");
    return null;
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSWebFaultHandler.java

/**
 * Get the fault bean class for the specified fault class.  This method assumes that the fault class
 * doesn't conform to the JAXWS pattern.
 *
 * @param faultClass The fault class.//  ww  w.  j  a v  a  2 s . c  o m
 * @return The fault bean class, or null if it wasn't found.
 */
public static Class getFaultBeanClass(Class<? extends Throwable> faultClass) {
    String faultBeanClassName;
    WebFault webFaultInfo = faultClass.getAnnotation(WebFault.class);
    if ((webFaultInfo != null) && (webFaultInfo.faultBean() != null)
            && (webFaultInfo.faultBean().length() > 0)) {
        faultBeanClassName = webFaultInfo.faultBean();
    } else {
        StringBuilder builder = new StringBuilder();
        Package pckg = faultClass.getPackage();
        if ((pckg != null) && (!"".equals(pckg.getName()))) {
            builder.append(pckg.getName()).append(".");
        }
        builder.append("jaxws.");
        builder.append(faultClass.getSimpleName()).append("Bean");
        faultBeanClassName = builder.toString();
    }

    Class faultBeanClass = null;
    try {
        faultBeanClass = ClassLoaderUtils.loadClass(faultBeanClassName, faultClass);
    } catch (NullPointerException npe) {
        //fall through.  treat the same as a class not found...
    } catch (ClassNotFoundException e) {
        //fall through.  treat it as a runtime exception...
    }
    return faultBeanClass;
}

From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java

/**
 * ?java//  w  w w  . j av  a2  s .com
 *
 * @param field
 * @return
 */
public static boolean isJavaClass(Field field) {
    Class<?> fieldType = field.getType();
    boolean isBaseClass = false;
    if (fieldType.isArray()) {
        isBaseClass = false;
    } else if (fieldType.isPrimitive() || fieldType.getPackage() == null
            || "java.lang".equals(fieldType.getPackage().getName())
            || "java.math".equals(fieldType.getPackage().getName())
            || "java.sql".equals(fieldType.getPackage().getName())
            || "java.time".equals(fieldType.getPackage().getName())
            || "java.util".equals(fieldType.getPackage().getName())) {
        isBaseClass = true;
    }
    return isBaseClass;
}

From source file:com.shigengyu.hyperion.cache.WorkflowStateCacheLoader.java

private static final StateOwner getStateOwner(Class<? extends WorkflowState> workflowStateClass) {

    // Try get annotation on class
    StateOwner stateOwner = workflowStateClass.getAnnotation(StateOwner.class);

    // Try get annotation on declaring class
    Class<?> declaringClass = workflowStateClass;
    while (stateOwner == null && (declaringClass = declaringClass.getDeclaringClass()) != null) {
        stateOwner = declaringClass.getAnnotation(StateOwner.class);
    }// w w w .  j a  v a  2 s  .c  om

    // Try get annotation on package
    if (stateOwner == null) {
        stateOwner = workflowStateClass.getPackage().getAnnotation(StateOwner.class);
    }

    return stateOwner;
}

From source file:org.jnetstream.protocol.ProtocolRegistry.java

/**
 * @param protocol/* w  w  w. j av a  2s.  c om*/
 */
private static void fillInFromClassInfo(DefaultProtocolEntry entry, Protocol protocol) {
    Class<? extends Protocol> c = protocol.getClass();
    if (c.isEnum() == false) {
        return;
    }

    Enum<?> constant = null;
    for (Enum<?> e : (Enum[]) c.getEnumConstants()) {
        if (e == protocol) {
            constant = e;
        }
    }

    Package pkg = c.getPackage();
    String suite = c.getSimpleName();
    String name = constant.name();
    String headeri = pkg.getName() + "." + name;
    String headerc = pkg.getName() + "." + name + "Header";
    String headercdc = pkg.getName() + "." + name + "Codec";

    // System.out.printf("suite=%s,\n name=%s,\n headeri=%s,\n headerc=%s\n",
    // suite, name, headeri, headerc);

    entry.setSuite(suite);
    entry.setName(name);
    try {

        entry.setProtocolClass((Class<? extends Header>) Class.forName(headeri));
    } catch (Exception e) {
        logger.warn("missing header: " + headeri);
        logger.debug(e);
    }

    try {
        entry.setCodec((Class<HeaderCodec<? extends Header>>) Class.forName(headercdc));

        HeaderCodec<? extends Header> codec = entry.getCodecClass().newInstance();
        entry.setCodec(codec);

    } catch (Exception e) {
        logger.warn("missing  codec: " + headercdc);
        logger.debug(e);
    }
}

From source file:com.github.magicsky.sya.checkers.TestSourceReader.java

/**
 * Returns an array of StringBuilder objects for each comment section found preceding the named
 * test in the source code./*w  ww . j av a2  s .  com*/
 *
 * @param srcRoot     the directory inside the bundle containing the packages
 * @param clazz       the name of the class containing the test
 * @param testName    the name of the test
 * @param numSections the number of comment sections preceding the named test to return.
 *                    Pass zero to get all available sections.
 * @return an array of StringBuilder objects for each comment section found preceding the named
 * test in the source code.
 * @throws IOException
 */
public static StringBuilder[] getContentsForTest(String srcRoot, Class clazz, final String testName,
        int numSections) throws IOException {
    // Walk up the class inheritance chain until we find the test method.
    try {
        while (clazz.getMethod(testName).getDeclaringClass() != clazz) {
            clazz = clazz.getSuperclass();
        }
    } catch (SecurityException e) {
        Assert.fail(e.getMessage());
    } catch (NoSuchMethodException e) {
        Assert.fail(e.getMessage());
    }

    while (true) {
        // Find and open the .java file for the class clazz.
        String fqn = clazz.getName().replace('.', '/');
        fqn = fqn.indexOf("$") == -1 ? fqn : fqn.substring(0, fqn.indexOf("$"));
        String classFile = fqn + ".java";
        InputStream in;
        Class superclass = clazz.getSuperclass();
        try {
            in = FileUtils.openInputStream(new File(srcRoot + '/' + classFile));
        } catch (IOException e) {
            if (superclass == null || !superclass.getPackage().equals(clazz.getPackage())) {
                throw e;
            }
            clazz = superclass;
            continue;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        try {
            // Read the java file collecting comments until we encounter the test method.
            List<StringBuilder> contents = new ArrayList<StringBuilder>();
            StringBuilder content = new StringBuilder();
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                line = line.replaceFirst("^\\s*", ""); // Replace leading whitespace, preserve trailing
                if (line.startsWith("//")) {
                    content.append(line.substring(2) + "\n");
                } else {
                    if (!line.startsWith("@") && content.length() > 0) {
                        contents.add(content);
                        if (numSections > 0 && contents.size() == numSections + 1)
                            contents.remove(0);
                        content = new StringBuilder();
                    }
                    if (line.length() > 0 && !contents.isEmpty()) {
                        int idx = line.indexOf(testName);
                        if (idx != -1
                                && !Character.isJavaIdentifierPart(line.charAt(idx + testName.length()))) {
                            return contents.toArray(new StringBuilder[contents.size()]);
                        }
                        if (!line.startsWith("@")) {
                            contents.clear();
                        }
                    }
                }
            }
        } finally {
            br.close();
        }

        if (superclass == null || !superclass.getPackage().equals(clazz.getPackage())) {
            throw new IOException("Test data not found for " + clazz.getName() + "." + testName);
        }
        clazz = superclass;
    }
}

From source file:com.haulmont.cuba.core.config.ConfigUtil.java

/**
 * Get the prefix associated with a configuration interface.
 * If the interface has an enclosing class, the
 * fully-qualified name of that class is used, or else the name of the
 * package containing the interface. In either of the latter two
 * cases, a '.' is appended to the name.
 *
 * @param configInterface The configuration interface.
 * @return The interface prefix./* w w  w.ja v a2 s.co m*/
 */
public static String getPropertyPrefix(Class<?> configInterface) {
    // Foo -> ""
    // foo.Bar -> "foo."
    // foo.Bar$Baz -> "foo.Bar."
    Class<?> enclosingClass = configInterface.getEnclosingClass();
    if (enclosingClass != null) {
        return enclosingClass.getName() + '.';
    } else {
        Package pkg = configInterface.getPackage();
        if (pkg != null) {
            return pkg.getName() + '.';
        } else {
            return "";
        }
    }
}