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.dasein.cloud.terremark.Terremark.java

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

    if (pkg.equals("terremark")) {
        pkg = "";
    } else {/* w  w  w.  j  a  v a2s.c  om*/
        pkg = pkg + ".";
    }
    return Logger.getLogger("dasein.cloud.terremark.std." + pkg + getLastItem(cls.getName()));
}

From source file:org.dhatim.util.ClassUtil.java

/**
 * Get the specified resource as a stream.
 *
 * @param resourceName/* w w  w  .  j  a  va2s.co  m*/
 *            The name of the class to load.
 * @param caller
 *            The class of the caller.
 * @return The input stream for the resource or null if not found.
 */
public static InputStream getResourceAsStream(final String resourceName, final Class caller) {
    final String resource;

    if (!resourceName.startsWith("/")) {
        final Package callerPackage = caller.getPackage();
        if (callerPackage != null) {
            resource = callerPackage.getName().replace('.', '/') + '/' + resourceName;
        } else {
            resource = resourceName;
        }

        return getResourceAsStream(resource, caller.getClassLoader());
    } else {
        return getResourceAsStream(resourceName, caller.getClassLoader());
    }
}

From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java

public static <T> T loadConfiguration(InputStream inputStream, Class<? extends T> configurationClass)
        throws Exception {
    if (configurationClass == null) {
        return null;
    }//from w  ww.j av  a2s.c  o m
    Object configuration;
    String configurationPackage = configurationClass.getPackage().getName();
    JAXBContext jaxbContext = JAXBContext.newInstance(configurationPackage);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    configuration = unmarshaller.unmarshal(inputStream);
    if (!configurationClass.isInstance(configuration)) {
        logger.error("Invalid configuration: expected " + configurationClass + ", got " + configuration);
        return null;
    }
    Injections.inject(configuration, ElementsThreadLocals.getServletContext(),
            ElementsThreadLocals.getHttpServletRequest());
    if (configuration instanceof PageActionConfiguration) {
        ((PageActionConfiguration) configuration).init();
    }
    return (T) configuration;
}

From source file:edu.umich.flowfence.sandbox.ResolvedQM.java

protected static <TAnnot extends Annotation, TMember extends AnnotatedElement & Member> TAnnot getMatchingAnnotation(
        Class<TAnnot> annotClass, TMember member) {
    TAnnot annot = member.getAnnotation(annotClass);
    if (annot != null) {
        return annot;
    }//from  w w w.  jav a 2  s. c om

    Class<?> declaringClass = member.getDeclaringClass();
    annot = declaringClass.getAnnotation(annotClass);
    if (annot != null) {
        return annot;
    }

    Package declaringPackage = declaringClass.getPackage();
    annot = declaringPackage.getAnnotation(annotClass);
    if (annot != null) {
        return annot;
    }

    return null;
}

From source file:io.coala.json.JsonUtil.java

/**
 * @param om the {@link ObjectMapper} used to parse/deserialize/unmarshal
 * @param type the {@link Class} to register
 * @param imports the {@link Properties} instances for default values, etc.
 * @return//ww  w .ja  v a2s .  c  o  m
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Class<T> checkRegistered(final ObjectMapper om, final Class<T> type,
        final Properties... imports) {
    synchronized (JSON_REGISTRATION_CACHE) {
        if (type.isPrimitive())
            return type;
        Set<Class<?>> cache = JSON_REGISTRATION_CACHE.computeIfAbsent(om, key -> new HashSet<>());
        if (type.getPackage() == Object.class.getPackage() || type.getPackage() == Collection.class.getPackage()
                || type.isPrimitive()
                // assume java.lang.* and java.util.* are already mapped
                || TreeNode.class.isAssignableFrom(type) || cache.contains(type))
            return type;

        // use Class.forName(String) ?
        // see http://stackoverflow.com/a/9130560

        //         LOG.trace( "Register JSON conversion of type: {}", type    );
        if (type.isAnnotationPresent(BeanProxy.class)) {
            //            if( !type.isInterface() )
            //               return Thrower.throwNew( IllegalArgumentException.class,
            //                     "@{} must target an interface, but annotates: {}",
            //                     BeanProxy.class.getSimpleName(), type );

            DynaBean.registerType(om, type, imports);
            checkRegisteredMembers(om, type, imports);
            // LOG.trace("Registered Dynabean de/serializer for: " + type);
        } else if (Wrapper.class.isAssignableFrom(type)) {
            Wrapper.Util.registerType(om, (Class<? extends Wrapper>) type);
            checkRegisteredMembers(om, type, imports);
            // LOG.trace("Registered Wrapper de/serializer for: " + type);
        }
        // else
        // LOG.trace("Assume default de/serializer for: " + type);

        cache.add(type);

        return type;
    }
}

From source file:org.dasein.cloud.terremark.Terremark.java

static public Logger getWireLogger(Class<?> cls) {
    return Logger.getLogger("dasein.cloud.terremark.wire." + getLastItem(cls.getPackage().getName()) + "."
            + getLastItem(cls.getName()));
}

From source file:IntrospectionUtil.java

protected static Field findInheritedField(Package pack, Class clazz, String fieldName, Class fieldType,
        boolean strictType) throws NoSuchFieldException {
    if (clazz == null)
        throw new NoSuchFieldException("No class");
    if (fieldName == null)
        throw new NoSuchFieldException("No field name");
    try {//from   w  ww.  j  av a2 s. c o m
        Field field = clazz.getDeclaredField(fieldName);
        if (isInheritable(pack, field) && isTypeCompatible(fieldType, field.getType(), strictType))
            return field;
        else
            return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType,
                    strictType);
    } catch (NoSuchFieldException e) {
        return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType, strictType);
    }
}

From source file:org.openrepose.commons.config.parser.jaxb.JaxbConfigurationParser.java

/**
 * Creates a jaxb parser for a specific classloader.
 * Throws up the JAXB exception so that things know they have to handle it.
 * Moved from a "factory" class that was just a collection of static methods
 *
 * @param configurationClass/*from  w w w  .  ja  v  a2s.  c  o  m*/
 * @param xsdStreamSource
 * @param loader
 * @param <T>
 * @return
 * @throws javax.xml.bind.JAXBException
 */
public static <T> JaxbConfigurationParser<T> getXmlConfigurationParser(Class<T> configurationClass,
        URL xsdStreamSource, ClassLoader loader) throws JAXBException {
    if (xsdStreamSource == null) {
        LOG.warn("Creating a JAXB Parser Pool without any schema to validate for {}", configurationClass);
        if (LOG.isDebugEnabled()) {
            Exception tracer = new Exception("Repose Devs might care about this trace");
            LOG.debug("Logging the current stack to find where a parser pool is created without a validator",
                    tracer);
        }
    }
    final JAXBContext context = JAXBContext.newInstance(configurationClass.getPackage().getName(), loader);
    return new JaxbConfigurationParser<>(configurationClass, context, xsdStreamSource);
}

From source file:com.bfd.harpc.common.configure.PathUtils.java

/**
 * ??URL?class/*from  ww  w  . j av  a2 s.co m*/
 * <p>
 * <b>NOTE:</b><br />
 * warfile:/path/my-app/calsses/ <br />
 * jarfile:/path/my-app/my-app.jar.
 * 
 * @return URL
 */
public static URL getCodeLocation(Class<?> clazz) {
    URL codeLocation = null;
    // If CodeSource didn't work, Class.getResource
    // instead.
    URL r = clazz.getResource("");
    synchronized (r) {
        String s = r.toString();
        Pattern jrare = Pattern.compile("jar:\\s?(.*)!/.*");
        Matcher m = jrare.matcher(s);
        if (m.find()) { // the code is run from a jar file.
            s = m.group(1);
        } else {
            String p = clazz.getPackage().getName().replace('.', '/');
            s = s.substring(0, s.lastIndexOf(p));
        }
        try {
            codeLocation = new URL(s);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
    return codeLocation;
}

From source file:org.assertj.assertions.generator.util.ClassUtil.java

/**
 * Gets the simple name of the class but, unlike {@link Class#getSimpleName()}, it includes the name of the outer
 * class when <code>clazz</code> is an inner class.
 *
 * @param clazz//from   w w  w  .  j a  va 2  s  . c  om
 * @return
 */
public static String getSimpleNameWithOuterClass(Class<?> clazz) {
    if (isNotNestedClass(clazz)) {
        return clazz.getSimpleName();
    }
    String nestedClassName = null;
    nestedClassName = clazz.getName();
    nestedClassName = nestedClassName.substring(clazz.getPackage().getName().length() + 1);
    nestedClassName = nestedClassName.replace('$', '.');
    return nestedClassName;
}