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.evolveum.midpoint.prism.schema.SchemaRegistry.java

public PrismSchema findSchemaByCompileTimeClass(Class<?> compileTimeClass) {
    Package compileTimePackage = compileTimeClass.getPackage();
    for (SchemaDescription desc : schemaDescriptions) {
        if (compileTimePackage.equals(desc.getCompileTimeClassesPackage())) {
            PrismSchema schema = desc.getSchema();
            return schema;
        }/*ww  w  . ja  v  a2s .com*/
    }
    return null;
}

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();//from  ww  w. j  a  v a 2 s  .  c  o m
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

From source file:org.acmsl.queryj.metadata.engines.JdbcTypeManager.java

/**
 * Tries to find out the actual class of given value.
 * @param value the value.//from w  w w.  j  av  a 2  s.  c  om
 * @param <T> the class parameter.
 * @return the actual class.
 */
@SuppressWarnings("unchecked")
@NotNull
protected <T> Class<?> findOutClass(@NotNull final T value) {
    @Nullable
    Class<?> result = null;

    @NotNull
    final Class<?>[] t_aInterfaces = value.getClass().getInterfaces();

    for (@NotNull
    final Class<?> t_Interface : t_aInterfaces) {
        if (t_Interface.getPackage().getName().equals("java.sql")) {
            result = t_Interface;
            break;
        }
    }

    if (result == null) {
        result = value.getClass();
    }

    return result;
}

From source file:org.pentaho.di.core.plugins.BasePluginType.java

/**
 * Handle an annotated plugin/*ww w .  j av  a  2 s  . c o  m*/
 *
 * @param clazz
 *          The class to use
 * @param annotation
 *          The annotation to get information from
 * @param libraries
 *          The libraries to add
 * @param nativePluginType
 *          Is this a native plugin?
 * @param pluginFolder
 *          The plugin folder to use
 * @throws KettlePluginException
 */
@Override
public void handlePluginAnnotation(Class<?> clazz, java.lang.annotation.Annotation annotation,
        List<String> libraries, boolean nativePluginType, URL pluginFolder) throws KettlePluginException {

    String idList = extractID(annotation);
    if (Const.isEmpty(idList)) {
        throw new KettlePluginException("No ID specified for plugin with class: " + clazz.getName());
    }

    // Only one ID for now
    String[] ids = idList.split(",");

    String packageName = extractI18nPackageName(annotation);
    String altPackageName = clazz.getPackage().getName();
    String name = getTranslation(extractName(annotation), packageName, altPackageName, clazz);
    String description = getTranslation(extractDesc(annotation), packageName, altPackageName, clazz);
    String category = getTranslation(extractCategory(annotation), packageName, altPackageName, clazz);
    String imageFile = extractImageFile(annotation);
    boolean separateClassLoader = extractSeparateClassLoader(annotation);
    String documentationUrl = extractDocumentationUrl(annotation);
    String casesUrl = extractCasesUrl(annotation);
    String forumUrl = extractForumUrl(annotation);

    Map<Class<?>, String> classMap = new HashMap<Class<?>, String>();

    PluginMainClassType mainType = getClass().getAnnotation(PluginMainClassType.class);

    classMap.put(mainType.value(), clazz.getName());

    addExtraClasses(classMap, clazz, annotation);

    /*
     * PluginExtraClassTypes extraTypes = this.getClass().getAnnotation(PluginExtraClassTypes.class); if(extraTypes !=
     * null){ for(int i=0; i< extraTypes.classTypes().length; i++){ Class<?> extraClass = extraTypes.classTypes()[i]; //
     * The extra class name is stored in an annotation. // The name of the annotation is known //
     * ((RepositoryPlugin)annotation).dialogClass() String extraClassName = extraTypes.classTypes()[i].getName();
     *
     * classMap.put(extraClass, extraClassName); } }
     */

    PluginInterface plugin = new Plugin(ids, this.getClass(), mainType.value(), category, name, description,
            imageFile, separateClassLoader, nativePluginType, classMap, libraries, null, pluginFolder,
            documentationUrl, casesUrl, forumUrl);
    ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class);
    if (parentFirstAnnotation != null) {
        registry.addParentClassLoaderPatterns(plugin, parentFirstAnnotation.patterns());
    }
    registry.registerPlugin(this.getClass(), plugin);

    if (libraries != null && libraries.size() > 0) {
        LogChannel.GENERAL.logDetailed("Plugin with id [" + ids[0] + "] has " + libraries.size()
                + " libaries in its private class path");
    }
}

From source file:com.link_intersystems.lang.reflect.Class2.java

/**
 * The string representation of a {@link Class2}.
 *
 * <ul>//from   w w w .  j a v  a  2s . c  om
 * <li>
 * Types are represented by their canonical name. If a type is a
 * &quot;well-known&quot; type (all types in java.lang) the type's simple
 * name is used. E.g. String - java.util.List.</li>
 * <ul>
 * <li>
 * Arrays are represented by their type and appended by []. E.g. int[]
 * String[] java.beans.PropertyDescriptor[].</li>
 *
 * @param wellKnownPackages
 *            packages that are &quot;well known&quot; will not be printed
 *            in the string representation. E.g. if java.lang is defined as
 *            well known the Class2 that represents a String class will be
 *            printed just as &quot;String&quot; and not java.lang.String.
 *
 * @return a string representation of this {@link Class2};
 * @since 1.0.0.0
 */
public String toString(String... wellKnownPackages) {
    Assert.notNull("wellKnownPackages", wellKnownPackages);
    StringBuilder toStringBuilder = new StringBuilder();
    Class<?> clazz = getType();
    boolean isArray = clazz.isArray();
    if (isArray) {
        clazz = clazz.getComponentType();
    }
    Package clazzPackage = clazz.getPackage();
    String packageName = StringUtils.EMPTY;
    if (clazzPackage != null) {
        packageName = clazzPackage.getName();
    }

    boolean isWellKnownPackage = Arrays.binarySearch(wellKnownPackages, packageName) > -1;

    if (isWellKnownPackage) {
        toStringBuilder.append(clazz.getSimpleName());
    } else {
        toStringBuilder.append(clazz.getCanonicalName());
    }

    TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
    String typeParametersToString = typeParametersToString(typeParameters);
    toStringBuilder.append(typeParametersToString);

    if (isArray) {
        toStringBuilder.append("[]");
    }
    return toStringBuilder.toString();
}

From source file:com.evolveum.midpoint.repo.sql.query.definition.ClassDefinitionParser.java

private Definition createDefinition(QName jaxbName, Class jaxbType, String jpaName, AnnotatedElement object) {
    Class jpaType = (object instanceof Class) ? (Class) object : ((Method) object).getReturnType();

    Definition definition;/*from   ww w .j  a v a 2s  . co  m*/
    if (ObjectReference.class.isAssignableFrom(jpaType)) {
        ReferenceDefinition refDef = new ReferenceDefinition(jaxbName, jaxbType, jpaName, jpaType);
        definition = updateReferenceDefinition(refDef, object);
    } else if (RAssignmentExtension.class.isAssignableFrom(jpaType)) {
        definition = new AnyDefinition(jaxbName, jaxbType, jpaName, jpaType);
    } else if (Set.class.isAssignableFrom(jpaType)) {
        CollectionDefinition collDef = new CollectionDefinition(jaxbName, jaxbType, jpaName, jpaType);
        updateCollectionDefinition(collDef, object, null, null);
        definition = collDef;
    } else if (isEntity(object)) {
        EntityDefinition entityDef = new EntityDefinition(jaxbName, jaxbType, jpaName, jpaType);
        if ("com.evolveum.midpoint.repo.sql.data.common.embedded".equals(jpaType.getPackage().getName())) {
            updateEntityDefinition(entityDef);
        }
        definition = entityDef;
    } else {
        PropertyDefinition propDef = new PropertyDefinition(jaxbName, jaxbType, jpaName, jpaType);
        definition = updatePropertyDefinition(propDef, object);
    }

    return definition;
}

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

protected void mapRecursively(ResultSet rs, Set columns, String tableName, Class objectClass, List parentList) {
    try {//  w w  w . j  a  v a2s  .c om
        if (!columns.contains(tableName + "_id"))
            return; //this object does not exist in the columns
        Object id = rs.getObject(tableName + "_id");
        if (id == null)
            return; //this object exists in the columns but null, probably because of left join

        //create bean wrapper for the object class
        BeanWrapperImpl wr = new BeanWrapperImpl(objectClass); //already caches class introspection (CachedIntrospectionResults.forClass())
        wr.setPropertyValue("id", id); //set the id property
        Object object = wr.getWrappedInstance();
        boolean map = true;

        //check if this object exists in the parent list (since SQL joins are cartesian products, do not create new object if this row is just the same as previous)
        for (Iterator it = parentList.iterator(); it.hasNext();) {
            Object objectInList = (Object) it.next();
            if (objectIdEquals(objectInList, id)) {
                wr.setWrappedInstance(objectInList); //already exists in the list, use that instance
                map = false; // and do not map again
                break;
            }
        }
        if (map)
            parentList.add(object); //could not find in the parent list, add the new object

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

            //database class (primitive property)
            if (map && dbClasses.contains(fieldClass)) {
                if (columns.contains(columnName)) {
                    if (debug)
                        System.out.println(">>field is found: " + columnName);
                    wr.setPropertyValue(pd.getName(), rs.getObject(columnName));
                } else {
                    if (debug)
                        System.out.println("--field not found: " + columnName);
                }
                continue; //if this is a primitive property, it cannot be an object or list
            }

            //many to one association (object property)
            if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) {
                if (columns.contains(columnName + "_id")) {
                    if (debug)
                        System.out.println(">>object is found " + columnName);
                    List list = new ArrayList(1); //we know there will be single result
                    if (!map)
                        list.add(fieldValue); //otherwise we cannot catch one to many assc. (lists) of many to one (object) assc.
                    mapRecursively(rs, columns, columnName, fieldClass, list);
                    if (list.size() > 0)
                        wr.setPropertyValue(pd.getName(), list.get(0));
                } else {
                    if (debug)
                        System.out.println("--object not found: " + columnName);
                }
            }

            //one to many association (list property)
            if (fieldValue instanceof List) { //Note: here recurring row's list property is mapped and add to parent's list
                if (columns.contains(columnName + "_id")) {
                    Class elementClass = VenList.findElementClass((List) fieldValue);
                    if (debug)
                        System.out.println(">>list is found " + columnName);
                    mapRecursively(rs, columns, columnName, elementClass, (List) fieldValue);
                } else {
                    if (debug)
                        System.out.println("--list not found: " + columnName);
                }
            }
        }
    } catch (Exception ex) {
        System.out.println("Ven - error while mapping row, table: " + tableName + " object class: "
                + objectClass + " error: " + ex.getMessage());
        if (debug) {
            ex.printStackTrace();
        }
    }
}

From source file:de.taimos.dvalin.interconnect.model.maven.MetaModelHelper.java

private EnumMemberDef createEMD(String name, Class<?> clazz, String comment, boolean required) {
    EnumMemberDef emd = new EnumMemberDef();
    emd.setComment(comment);//from   w ww. j a  va2  s . c o  m
    emd.setJavaTransientFlag(Boolean.FALSE);
    emd.setJsonTransientFlag(Boolean.FALSE);
    emd.setName(name);
    emd.setOrderTransient(Boolean.FALSE);
    emd.setRequired(required);
    emd.setClazz(clazz.getSimpleName());
    emd.setPkgName(clazz.getPackage().getName());
    return emd;
}

From source file:io.apiman.manager.api.es.EsMarshallingTest.java

/**
 * Fabricates a new instance of the given bean type.  Uses reflection to figure
 * out all the fields and assign generated values for each.
 *//*  w w w.j  a  v a  2 s.  c o m*/
private static <T> T createBean(Class<T> beanClass) throws InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
    T bean = beanClass.newInstance();
    Map<String, String> beanProps = BeanUtils.describe(bean);
    for (String key : beanProps.keySet()) {
        try {
            Field declaredField = beanClass.getDeclaredField(key);
            Class<?> fieldType = declaredField.getType();
            if (fieldType == String.class) {
                BeanUtils.setProperty(bean, key, StringUtils.upperCase(key));
            } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                BeanUtils.setProperty(bean, key, Boolean.TRUE);
            } else if (fieldType == Date.class) {
                BeanUtils.setProperty(bean, key, new Date(1));
            } else if (fieldType == Long.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 17L);
            } else if (fieldType == Integer.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 11);
            } else if (fieldType == Set.class) {
                // Initialize to a linked hash set so that order is maintained.
                BeanUtils.setProperty(bean, key, new LinkedHashSet());

                Type genericType = declaredField.getGenericType();
                String typeName = genericType.getTypeName();
                String typeClassName = typeName.substring(14, typeName.length() - 1);
                Class<?> typeClass = Class.forName(typeClassName);
                Set collection = (Set) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(bean, key);
                populateSet(collection, typeClass);
            } else if (fieldType == Map.class) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                map.put("KEY-1", "VALUE-1");
                map.put("KEY-2", "VALUE-2");
                BeanUtils.setProperty(bean, key, map);
            } else if (fieldType.isEnum()) {
                BeanUtils.setProperty(bean, key, fieldType.getEnumConstants()[0]);
            } else if (fieldType.getPackage() != null
                    && fieldType.getPackage().getName().startsWith("io.apiman.manager.api.beans")) {
                Object childBean = createBean(fieldType);
                BeanUtils.setProperty(bean, key, childBean);
            } else {
                throw new IllegalAccessException(
                        "Failed to handle property named [" + key + "] type: " + fieldType.getSimpleName());
            }
            //            String capKey = StringUtils.capitalize(key);
            //            System.out.println(key);;
        } catch (NoSuchFieldException e) {
            // Skip it - there is not really a bean property with this name!
        }
    }
    return bean;
}

From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java

/**
 * Writes the Builder interface source file for each of the pojo class that
 * has setter methods.<br>/*from  w w  w  .  jav  a2 s  .  co m*/
 * <b>Note:It is important to look at the method's return list of classes
 * that could not be built for {@link Builder} </b>
 * 
 * @param pojoClasses
 *            is a set of pojo classes for each of which a {@link Builder}
 *            interface would be fabricated to a source folder.
 * @return a list of class objects which could not be used for building
 *         {@link Builder} interface
 * @throws NotFoundException
 *             when CtClass / Class is not found
 * @throws CannotCompileException
 *             when non-compilable statements are added
 * @throws IOException
 *             when during io errors
 */
public List<Class<?>> writeInterface(final Class<?>... pojoClasses)
        throws NotFoundException, CannotCompileException, IOException {
    if (pojoClasses.length == 0) {
        throw new IllegalArgumentException(
                "The Parameters to this method must be an array of valid public class objects");
    }
    final List<Class<?>> failedList = new ArrayList<>();
    for (final Class<?> thisPojoClass : pojoClasses) {
        if (isNotAPublicClass(thisPojoClass)) {
            throw new IllegalArgumentException(
                    "The Builders can only be created for a valid public class objects:"
                            + thisPojoClass.getName());
        }
        final Set<CtMethod> writableMethods = getWritableMethods(thisPojoClass);
        final Set<Method> writableNormalMethods = getWritableNormalMethods(thisPojoClass);
        if (writableMethods.isEmpty()) {
            failedList.add(thisPojoClass);
        } else {
            final String interfaceName = String.format("%s.%sBuilder", thisPojoClass.getPackage().getName(),
                    thisPojoClass.getSimpleName());
            final CtClass pojoBuilderInterface = ctPool.makeInterface(interfaceName, fluentBuilderClass);
            addMethodsToBuilder(pojoBuilderInterface, writableMethods);
            JCodeModel cm = new JCodeModel();
            try {
                JClass bl = new JCodeModel()._class(Builder.class.getName(), ClassType.INTERFACE)
                        .narrow(thisPojoClass);
                JDefinedClass cl = cm._class(interfaceName, ClassType.INTERFACE)._extends(bl);
                Class<?> builderClass = ctPool.toClass(pojoBuilderInterface);
                for (Method m : writableNormalMethods) {
                    JMethod jm = cl.method(Modifier.PUBLIC, builderClass, m.getName());
                    for (int i = 0; i < m.getParameterTypes().length; i++) {
                        jm.param(m.getParameterTypes()[i], "arg" + i++);
                    }
                }
                sourceFolderRoot.mkdirs();
                cm.build(sourceFolderRoot);
            } catch (Exception e) {
                throw new IOException(e);
            }
        }
    }
    return failedList;
}