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.topazproject.otm.metadata.AnnotationClassMetaFactory.java

/**
 * Creates a new ClassMetadata object.//from w ww .j a v  a  2 s  . c  om
 *
 * @param clazz the class with annotations
 *
 * @throws OtmException on an error
 */
public void create(Class<?> clazz) throws OtmException {
    // Add alias definitions from both class and package
    addAliases(clazz.getAnnotation(Aliases.class));
    if (clazz.getPackage() != null)
        addAliases(clazz.getPackage().getAnnotation(Aliases.class));

    // Add graph definitions from both class and package
    addGraphs(clazz.getAnnotation(Graphs.class));
    if (clazz.getPackage() != null)
        addGraphs(clazz.getPackage().getAnnotation(Graphs.class));

    if ((clazz.getAnnotation(View.class) != null) || (clazz.getAnnotation(SubView.class) != null))
        createView(clazz);
    else
        createEntity(clazz);
}

From source file:com.manydesigns.portofino.actions.admin.database.TablesAction.java

protected String getJavaTypeName(Class javaType) {
    if (javaType.getPackage().getName().startsWith("java.")) {
        return javaType.getSimpleName();
    } else {//  ww w  .ja v  a 2  s .  co  m
        return javaType.getName();
    }
}

From source file:com.yahoo.elide.core.EntityDictionary.java

/**
 * Return annotation from class, parents or package.
 *
 * @param recordClass the record class/*from  w  w w. j  a  va2 s  .  c  om*/
 * @param annotationClass the annotation class
 * @param <A> genericClass
 * @return the annotation
 */
public <A extends Annotation> A getAnnotation(Class<?> recordClass, Class<A> annotationClass) {
    A annotation = null;
    for (Class<?> cls = recordClass; annotation == null && cls != null; cls = cls.getSuperclass()) {
        annotation = cls.getAnnotation(annotationClass);
    }
    // no class annotation, try packages
    for (Package pkg = recordClass.getPackage(); annotation == null
            && pkg != null; pkg = getParentPackage(pkg)) {
        annotation = pkg.getAnnotation(annotationClass);
    }
    return annotation;
}

From source file:org.jboss.test.selenium.AbstractSeleniumTestCase.java

/**
 * Loads properties from specified resource file in context of specified
 * class' package.//from  www. j a va  2 s. c o m
 * 
 * @param tClass
 *            named resource will be searched in context of this class
 * @param name
 *            name of resource contained in current class' package
 * @return loaded properties
 * @throws IllegalStateException
 *             if an error occurred when reading resource file
 */
protected <T> Properties getNamedPropertiesForClass(Class<T> tClass, String name) throws IllegalStateException {
    String propFile = tClass.getPackage().getName();
    propFile = propFile.replace('.', '/');
    propFile = String.format("%s/%s.properties", propFile, name);

    try {
        return getProperties(propFile);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

private String determineNamespaceUncached(Class<?> beanClass) {
    XmlType xmlType = beanClass.getAnnotation(XmlType.class);
    if (xmlType == null) {
        return null;
    }//from w  ww .j a va2 s.c  o  m

    String namespace = xmlType.namespace();
    if (BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) {
        XmlSchema xmlSchema = beanClass.getPackage().getAnnotation(XmlSchema.class);
        namespace = xmlSchema.namespace();
    }
    if (StringUtils.isBlank(namespace) || BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) {
        return null;
    }

    return namespace;
}

From source file:com.homesnap.engine.controller.Controller.java

/**
 * Initializes the state names with their class types in order to prevent from a wrong assigment when the {@link #set(StateName, StateValue)} method is called.
 *//*from   ww  w. ja  v a 2 s  .  co  m*/
private void initStateTypes(Class<?> clazz) {
    // Check if the controller class is known
    stateTypes = classTypes.get(clazz);
    if (stateTypes == null) {
        Class<?> superClass = clazz.getSuperclass();
        while (!Controller.class.equals(superClass)) {
            initStateTypes(superClass);
            break;
        }
        // Search the ".states" resource which defines the state types of the controller
        String pkgName = clazz.getPackage().getName().replace('.', '/');
        URL url = clazz.getClassLoader().getResource(pkgName + "/" + clazz.getSimpleName() + ".states");
        if (url == null) {
            throw new RuntimeException("Unable to find states definition file for " + clazz.getName());
        }
        // Load the definition file
        StatesReader reader = new StatesReader();
        try {
            reader.load(url.openStream());
        } catch (IOException e) {
            throw new RuntimeException("Unable to load states definition file for " + getClass().getName(), e);
        }
        stateTypes = (StateSection) reader.getControllerSection();
        classTypes.put(clazz, stateTypes);
    }
}

From source file:com.fmguler.ven.support.LiquibaseConverter.java

private void convertClass(StringBuffer liquibaseXml, Class domainClass) {
    String objectName = Convert.toSimpleName(domainClass.getName());
    String tableName = Convert.toDB(objectName);
    startTagChangeSet(liquibaseXml, author, "" + (changeSetId++));
    startTagCreateTable(liquibaseXml, schema, tableName);
    addIdColumn(liquibaseXml, tableName);
    List foreignKeyConstraints = new LinkedList();

    BeanWrapper wr = new BeanWrapperImpl(domainClass);
    PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();

    for (int i = 0; i < pdArr.length; i++) {
        Class fieldClass = pdArr[i].getPropertyType(); //field class
        String fieldName = pdArr[i].getName(); //field name
        String columnName = Convert.toDB(pdArr[i].getName()); //column name

        if (fieldName.equals("id")) {
            continue;
        }//from   ww  w .  j av a  2  s  . c o m

        //direct database class (Integer, String, Date, etc)
        if (dbClasses.keySet().contains(fieldClass)) {
            addPrimitiveColumn(liquibaseXml, columnName, ((Integer) dbClasses.get(fieldClass)).intValue());

        }

        //many to one association (object property)
        if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) {
            addPrimitiveColumn(liquibaseXml, columnName + "_id", COLUMN_TYPE_INT);

            //handle foreign key
            String referencedTableName = Convert.toDB(Convert.toSimpleName(fieldClass.getName()));
            Map fkey = new HashMap();
            fkey.put("baseTableName", tableName);
            fkey.put("baseColumnNames", columnName + "_id");
            fkey.put("referencedTableName", referencedTableName);
            if (processedTables.contains(referencedTableName))
                foreignKeyConstraints.add(fkey);
            else
                unhandledForeignKeyConstraints.add(fkey);
        }

    }
    endTagCreateTable(liquibaseXml);
    endTagChangeSet(liquibaseXml);

    //mark table as processed
    processedTables.add(tableName);
    //add fkeys waiting for this table
    notifyUnhandledForeignKeyConstraints(liquibaseXml, tableName);
    //add fkeys not waiting for this table
    Iterator it = foreignKeyConstraints.iterator();
    while (it.hasNext()) {
        Map fkey = (Map) it.next();
        addForeignKeyConstraint(liquibaseXml, fkey);
    }
}

From source file:com.netspective.commons.text.TextUtils.java

/**
 * Return the name of the given cls that is different from the relativeTo class. Basically, this chops off the
 * package name of the cls that is equivalent to that of the relativeTo class.
 *///  w ww.java  2 s. co  m
public String getRelativeClassName(Class relativeTo, Class cls) {
    String className = cls.getName();
    String relativeToPkg = relativeTo.getPackage().getName();
    if (className.startsWith(relativeToPkg))
        return className.substring(relativeToPkg.length() + 1);
    else
        return className;
}

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

private void generateRecursively(int level, String tableName, String objectPath, Class objectClass, Set joins,
        StringBuffer selectClause, StringBuffer fromClause) {
    BeanWrapper wr = new BeanWrapperImpl(objectClass);
    PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();

    for (int i = 0; i < pdArr.length; i++) {
        Class fieldClass = pdArr[i].getPropertyType(); //field class
        String fieldName = pdArr[i].getName(); //field name
        Object fieldValue = wr.getPropertyValue(fieldName);
        String columnName = Convert.toDB(pdArr[i].getName()); //column name

        //direct database class (Integer, String, Date, etc)
        if (dbClasses.contains(fieldClass)) {
            selectClause.append(tableName).append(".").append(columnName).append(" as ").append(tableName)
                    .append("_").append(columnName); //column
            selectClause.append(", ");
        }/*from w ww  . jav  a  2s  .c o m*/

        //many to one association (object property)
        if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())
                && joinsContain(joins, objectPath + "." + fieldName)) {
            String joinTableAlias = tableName + "_" + columnName; //alias for table to join since there can be multiple joins to the same table
            String joinTable = Convert.toDB(Convert.toSimpleName(fieldClass.getName())); //table to join
            fromClause.append(" left join ").append(joinTable).append(" ").append(joinTableAlias);
            fromClause.append(" on ").append(joinTableAlias).append(".id = ").append(tableName).append(".")
                    .append(columnName).append("_id");
            generateRecursively(++level, joinTableAlias, objectPath + "." + fieldName, fieldClass, joins,
                    selectClause, fromClause);
        }

        //one to many association (list property)
        if (fieldValue instanceof List && joinsContain(joins, objectPath + "." + fieldName)) {
            Class elementClass = VenList.findElementClass((List) fieldValue);
            String joinTableAlias = tableName + "_" + columnName; //alias for table to join since there can be multiple joins to the same table
            String joinTable = Convert.toDB(Convert.toSimpleName(elementClass.getName())); //table to join
            String joinField = Convert.toDB(findJoinField((List) fieldValue)); //field to join
            fromClause.append(" left join ").append(joinTable).append(" ").append(joinTableAlias);
            fromClause.append(" on ").append(joinTableAlias).append(".").append(joinField).append("_id = ")
                    .append(tableName).append(".id");
            generateRecursively(++level, joinTableAlias, objectPath + "." + fieldName, elementClass, joins,
                    selectClause, fromClause);
        }
    }
}

From source file:freemarker.ext.dump.BaseDumpDirective.java

private Map<String, Object> getObjectDump(TemplateHashModelEx model, Object object)
        throws TemplateModelException {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(Key.TYPE.toString(), object.getClass().getName());

    if (object instanceof java.lang.reflect.Method)
        return map;

    // Compile the collections of properties and methods available to the template
    SortedMap<String, Object> properties = new TreeMap<String, Object>();
    SortedMap<String, Object> methods = new TreeMap<String, Object>();

    // keys() gets only values visible to template based on the BeansWrapper used.
    // Note: if the BeansWrapper exposure level > BeansWrapper.EXPOSE_PROPERTIES_ONLY,
    // keys() returns both method and property name for any available method with no
    // parameters: e.g., both name and getName(). We are going to eliminate the latter.
    TemplateCollectionModel keys = model.keys();
    TemplateModelIterator iModel = keys.iterator();

    // Create a Set from keys so we can use the Set API.
    Set<String> keySet = new HashSet<String>();
    while (iModel.hasNext()) {
        String key = iModel.next().toString();
        keySet.add(key);//from   www.  j  a v  a 2s.  c  om
    }

    if (keySet.size() > 0) {

        Class<?> cls = object.getClass();
        Method[] classMethods = cls.getMethods();

        // Iterate through the methods rather than the keys, so that we can remove
        // some keys based on reflection on the methods. We also want to remove duplicates
        // like name/getName - we'll keep only the first form.
        for (Method method : classMethods) {

            if ("declaringClass".equals(method.getName()))
                continue;

            // Eliminate methods declared on Object
            // and other unusual places that can cause problems.
            Class<?> c = method.getDeclaringClass();

            if (c == null || c.equals(java.lang.Object.class) || c.equals(java.lang.reflect.Constructor.class)
                    || c.equals(java.lang.reflect.Field.class))
                continue;
            if (c.getPackage().getName().startsWith("sun.") || c.getPackage().getName().startsWith("java.lang")
                    || c.getPackage().getName().startsWith("java.security"))
                continue;

            // Eliminate deprecated methods
            if (method.isAnnotationPresent(Deprecated.class)) {
                continue;
            }

            // Include only methods included in keys(). This factors in visibility
            // defined by the model's BeansWrapper.                 
            String methodName = method.getName();

            Matcher matcher = PROPERTY_NAME_PATTERN.matcher(methodName);
            // If the method name starts with "get" or "is", check if it's available
            // as a property
            if (matcher.find()) {
                String propertyName = getPropertyName(methodName);

                // The method is available as a property
                if (keySet.contains(propertyName)) {
                    try {
                        TemplateModel value = model.get(propertyName);
                        properties.put(propertyName, getDump(value));
                    } catch (Throwable th) {
                        log.error("problem dumping " + propertyName + " on " + object.getClass().getName()
                                + " declared in " + c.getName(), th);
                    }
                    continue;
                }
            }

            // Else look for the entire methodName in the key set, to include
            // those that are exposed as methods rather than properties. 
            if (keySet.contains(methodName)) {
                String methodDisplayName = getMethodDisplayName(method);
                // If no arguments, invoke the method to get the result
                if (methodDisplayName.endsWith("()")) {
                    SimpleMethodModel methodModel = (SimpleMethodModel) model.get(methodName);
                    try {
                        Object result = methodModel.exec(null);
                        ObjectWrapper wrapper = getWrapper(model);
                        TemplateModel wrappedResult = wrapper.wrap(result);
                        methods.put(methodDisplayName, getDump(wrappedResult));
                    } catch (Exception e) {
                        log.error(e, e);
                    }
                    // Else display method name, parameter types, and return type
                } else {
                    String returnTypeName = getReturnTypeName(method);
                    Map<String, String> methodValue = new HashMap<String, String>();
                    if (!returnTypeName.equals("void")) {
                        methodValue.put(Key.TYPE.toString(), returnTypeName);
                    }
                    methods.put(methodDisplayName, methodValue);
                }
            }
        }
    }

    Map<String, Object> objectValue = new HashMap<String, Object>(2);
    objectValue.put(Key.PROPERTIES.toString(), properties);
    objectValue.put(Key.METHODS.toString(), methods);

    map.put(Key.VALUE.toString(), objectValue);
    return map;
}