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.opengamma.financial.generator.AbstractPortfolioGeneratorTool.java

private AbstractPortfolioGeneratorTool getInstance(final Class<?> clazz, final String security) {
    if (!AbstractPortfolioGeneratorTool.class.isAssignableFrom(clazz)) {
        throw new OpenGammaRuntimeException("Couldn't find generator tool class for " + security);
    }/*from  ww  w .java  2s. c  o m*/
    try {
        final String className;
        final int i = security.indexOf('.');
        if (i < 0) {
            className = clazz.getPackage().getName() + "." + security + "PortfolioGeneratorTool";
        } else {
            className = security;
        }
        final Class<?> instanceClass;
        try {
            s_logger.debug("Trying class {}", className);
            instanceClass = Class.forName(className);
        } catch (final ClassNotFoundException e) {
            return getInstance(clazz.getSuperclass(), security);
        }
        s_logger.info("Loading {}", className);
        final AbstractPortfolioGeneratorTool tool = (AbstractPortfolioGeneratorTool) instanceClass
                .newInstance();
        tool.setContext(getClassContext(), this);
        return tool;
    } catch (final Exception e) {
        throw new OpenGammaRuntimeException("Couldn't create generator tool instance for " + security, e);
    }
}

From source file:com.fmguler.ven.QueryGenerator.java

/**
 * Generates update query for the specified object
 * @param object the object to generate update query for
 * @return the update SQL query/*from ww w .  j  av a  2  s.  c  o  m*/
 */
public String generateUpdateQuery(Object object) throws VenException {
    BeanWrapper wr = new BeanWrapperImpl(object);
    String objectName = Convert.toSimpleName(object.getClass().getName());
    String tableName = Convert.toDB(objectName);
    PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();

    StringBuffer query = new StringBuffer("update " + tableName + " set ");
    for (int i = 0; i < pdArr.length; i++) {
        Class fieldClass = pdArr[i].getPropertyType(); //field class
        String columnName = Convert.toDB(pdArr[i].getName()); //column name
        String fieldName = pdArr[i].getName(); //field name
        if (dbClasses.contains(fieldClass)) { //direct database field (Integer,String,Date, etc)
            query.append(columnName.equals("order") ? "\"order\"" : columnName).append("=:").append(fieldName);
            query.append(",");
        }
        if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) { //object
            query.append(columnName).append("_id=:").append(fieldName).append(".id");
            query.append(",");
        }
    }
    query.deleteCharAt(query.length() - 1);
    query.append(" where id = :id ;");
    return query.toString();
}

From source file:com.kjt.service.common.SoafwTesterMojo.java

private StringBuffer createTestJHeadByClass(Class cls) {
    StringBuffer jHeadBuf = new StringBuffer();

    jHeadBuf.append("package " + cls.getPackage().getName() + "; \n");
    jHeadBuf.append("\n");
    jHeadBuf.append("import org.junit.Test;\n");
    jHeadBuf.append("import org.junit.runner.RunWith;\n");
    jHeadBuf.append("import org.springframework.test.context.ContextConfiguration;\n");
    jHeadBuf.append("import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\n\n");
    jHeadBuf.append("import com.kjt.service.common.annotation.SoaFwTest;\n");
    jHeadBuf.append("@RunWith(SpringJUnit4ClassRunner.class)\n");
    String name = project.getName();
    String suffix = "dao";
    if (name.endsWith("-common")) {
        suffix = "common";
    } else if (name.endsWith("-config")) {
        suffix = "config";
    } else if (name.endsWith("-cache")) {
        suffix = "cache";
    } else if (name.endsWith("-dao")) {
        suffix = "dao";
    } else if (name.endsWith("-mq")) {
        suffix = "mq";
    } else if (name.endsWith("-rpc")) {
        suffix = "rpc";
    } else if (name.endsWith("-job")) {
        suffix = "job";
    } else if (name.endsWith("-web")) {
        suffix = "dubbo";
    } else if (name.endsWith("-domain") || name.endsWith("-service") || name.endsWith("-service-impl")) {
        suffix = "service";
    }/*from w  w w  . ja v  a 2  s .  c om*/

    jHeadBuf.append("@ContextConfiguration( locations = { \"classpath*:/META-INF/config/spring/spring-" + suffix
            + ".xml\"})\n");

    jHeadBuf.append("public class " + cls.getSimpleName() + "Test {\n");
    return jHeadBuf;
}

From source file:org.openspotlight.graph.query.AbstractGeneralQueryTest.java

/**
 * Adds the java class hirarchy links./*from  www . ja v a2s  .  c om*/
 * 
 * @param root the root
 * @param clazz the clazz
 * @param javaClass the java class
 */
private void addJavaClassHirarchyLinks(final Context root, final Class<?> clazz, final JavaClass javaClass) {
    final Class<?> superClass = clazz.getSuperclass();
    if (superClass != null) {
        final Package classPack = clazz.getPackage();
        final JavaPackage javaPackage = writer.addNode(root, JavaPackage.class, classPack.getName());
        // javaPackage.setCaption(classPack.getName());
        final JavaClass superJavaClass = writer.addChildNode(javaPackage, JavaClass.class,
                superClass.getName());
        writer.addLink(PackageContainsType.class, javaPackage, superJavaClass);
        writer.addLink(JavaClassHierarchy.class, javaClass, superJavaClass);
        addJavaClassHirarchyLinks(root, superClass, superJavaClass);
    }
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Returns the package path of a class./*  w ww.j a v  a2  s . c o m*/
 * 
 * @param clasz
 *            Class to determine the path for - Cannot be <code>null</code>.
 * 
 * @return Package path for the class.
 */
public static String getPackagePath(final Class clasz) {
    checkNotNull("clasz", clasz);
    return clasz.getPackage().getName().replace('.', '/');
}

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

private Object getReferencedObject(ClassLoader storageClassLoader, Session session,
        ComplexTypeMetadata referencedType, Object referencedIdValue) {
    Class<?> referencedClass;
    try {/*w  w  w  .j  a  v  a2s  .  c  om*/
        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;
            // 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 if (referencedIdValue instanceof Serializable) {
            // 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, (Serializable) referencedIdValue);
                if (sessionObject == null) {
                    throw new ValidateException("Invalid foreign key: [" + referencedClass.getName() + "#" //$NON-NLS-1$//$NON-NLS-2$
                            + (Serializable) referencedIdValue + "] doesn't exist."); //$NON-NLS-1$
                } else {
                    return sessionObject;
                }
            } else {
                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:com.anrisoftware.propertiesutils.ContextProperties.java

/**
 * Sets the context and the properties./*from  w w w  .  j  av  a 2s  .co m*/
 * 
 * @param context
 *            an {@link Object} that is used as the context.
 * 
 * @param parentProperties
 *            the {@link Properties} that are returned.
 */
public ContextProperties(Class<?> context, Properties parentProperties) {
    this(context.getPackage().getName(), parentProperties);
}

From source file:com.medallia.spider.SpiderServlet.java

/** @return the name of the package where task classes are assumed to be */
private String findTaskPackage(Class<? extends SpiderServlet> clazz) {
    Class<?> p = clazz;
    while (p.getSuperclass() != getServletParent())
        p = p.getSuperclass();//from  w w  w  . j ava2 s. com

    return p.getPackage().getName() + ".st.";
}

From source file:org.apereo.portal.utils.ResourceLoader.java

/**
 * Finds a resource with a given name.  This is a convenience method for accessing a resource
 * from a channel or from the uPortal framework.  If a well-formed URL is passed in,
 * this method will use that URL unchanged to find the resource.
 * If the URL is not well-formed, this method will look for
 * the desired resource relative to the classpath.
 * If the resource name starts with "/", it is unchanged. Otherwise, the package name
 * of the requesting class is prepended to the resource name.
 * @param requestingClass the java.lang.Class object of the class that is attempting to load the resource
 * @param resource a String describing the full or partial URL of the resource to load
 * @return a URL identifying the requested resource
 * @throws ResourceMissingException/*w  ww . j  a  va2s  .c o m*/
 */
public static URL getResourceAsURL(Class<?> requestingClass, String resource) throws ResourceMissingException {
    final Tuple<Class<?>, String> cacheKey = new Tuple<Class<?>, String>(requestingClass, resource);

    //Look for a cached URL 
    final Map<Tuple<Class<?>, String>, URL> resourceUrlCache = ResourceLoader.resourceUrlCache;
    URL resourceURL = resourceUrlCache != null ? resourceUrlCache.get(cacheKey) : null;
    if (resourceURL != null) {
        return resourceURL;
    }

    //Look for a failed lookup
    final Map<Tuple<Class<?>, String>, ResourceMissingException> resourceUrlNotFoundCache = ResourceLoader.resourceUrlNotFoundCache;
    ResourceMissingException exception = resourceUrlNotFoundCache != null
            ? resourceUrlNotFoundCache.get(cacheKey)
            : null;
    if (exception != null) {
        throw new ResourceMissingException(exception);
    }

    try {
        resourceURL = new URL(resource);
    } catch (MalformedURLException murle) {
        // URL is invalid, now try to load from classpath
        resourceURL = requestingClass.getResource(resource);

        if (resourceURL == null) {
            String resourceRelativeToClasspath = null;
            if (resource.startsWith("/"))
                resourceRelativeToClasspath = resource;
            else
                resourceRelativeToClasspath = '/' + requestingClass.getPackage().getName().replace('.', '/')
                        + '/' + resource;
            exception = new ResourceMissingException(resource, resourceRelativeToClasspath,
                    "Resource not found in classpath: " + resourceRelativeToClasspath);
            if (resourceUrlNotFoundCache != null) {
                resourceUrlNotFoundCache.put(cacheKey, exception);
            }
            throw new ResourceMissingException(exception);
        }
    }

    if (resourceUrlCache != null) {
        resourceUrlCache.put(cacheKey, resourceURL);
    }
    return resourceURL;
}

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

public void scanAnnotatedElements() {
    Map<Class<?>, ExcludeClass> excludeClassesConfiguration = scanForAnnotation(ExcludeClass.class);
    for (Map.Entry<Class<?>, ExcludeClass> entry : excludeClassesConfiguration.entrySet()) {
        Class<?> clazz = entry.getKey();
        ExcludeClass config = entry.getValue();
        excludedClasses.put(clazz, new ExcludedClass(clazz, config));
    }//from w ww.  j  a  v  a2s  .c  o  m
    Map<Class<?>, ExcludePackage> excludePackagesConfiguration = scanForAnnotation(ExcludePackage.class);
    for (Map.Entry<Class<?>, ExcludePackage> entry : excludePackagesConfiguration.entrySet()) {
        Class<?> clazz = entry.getKey();
        ExcludePackage config = entry.getValue();
        if (clazz.getPackage() != null) {
            excludedPackages.add(new ExcludedPackage(clazz.getPackage(), config));
        }
    }
    Map<Class<?>, IncludeClass> includeClassesConfiguration = scanForAnnotation(IncludeClass.class);
    for (Map.Entry<Class<?>, IncludeClass> entry : includeClassesConfiguration.entrySet()) {
        Class<?> clazz = entry.getKey();
        IncludeClass config = entry.getValue();
        includedClasses.put(clazz, new IncludedClass(clazz, config));
    }
    Map<Class<?>, ScanPackage> includePackagesConfiguration = scanForAnnotation(ScanPackage.class);
    for (Map.Entry<Class<?>, ScanPackage> entry : includePackagesConfiguration.entrySet()) {
        Class<?> clazz = entry.getKey();
        ScanPackage config = entry.getValue();
        if (clazz.getPackage() != null) {
            scannedPackages.add(new ScannedPackage(clazz.getPackage(), config));
        }
    }
    Map<Class<?>, name.ikysil.beanpathdsl.core.annotations.Configuration> configurations = scanForAnnotation(
            name.ikysil.beanpathdsl.core.annotations.Configuration.class);
    for (Map.Entry<Class<?>, name.ikysil.beanpathdsl.core.annotations.Configuration> entry : configurations
            .entrySet()) {
        Class<?> clazz = entry.getKey();
        includedClasses.put(clazz, new IncludedClass(clazz));
    }
    Map<Class<?>, Navigator> knownNavigatorsConfiguration = scanForAnnotation(Navigator.class);
    for (Map.Entry<Class<?>, Navigator> entry : knownNavigatorsConfiguration.entrySet()) {
        Class<?> navigatorClass = entry.getKey();
        Navigator navigator = entry.getValue();
        Class<?> navigatedClass = navigator.value();
        knownNavigators.put(navigatedClass, new Navigated(navigator, navigatorClass));
    }
}