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.tangram.components.editor.EditingHandler.java

@LinkAction("/list")
public TargetDescriptor list(@ActionParameter(PARAMETER_CLASS_NAME) String typeName, HttpServletRequest request,
        HttpServletResponse response) {//from   w w w . j  a va  2 s  .com
    LOG.info("list() listing instances of type '{}'", typeName);
    if (request.getAttribute(Constants.ATTRIBUTE_ADMIN_USER) == null) {
        throw new RuntimeException("User may not edit");
    } // if
    Collection<Class<? extends Content>> classes = getMutableBeanFactory().getClasses();
    Class<? extends Content> cls = null;
    // take first one of classes available
    if (!classes.isEmpty()) {
        cls = classes.iterator().next();
    } // if
      // try to take class from provided classes
    if (StringUtils.isNotBlank(typeName)) {
        for (Class<? extends Content> c : classes) {
            if (c.getName().equals(typeName)) {
                cls = c;
            } // if
        } // for
    } // if

    List<? extends Content> contents = Collections.emptyList();
    if (cls != null) {
        contents = beanFactory.listBeansOfExactClass(cls);
        try {
            Collections.sort(contents);
        } catch (Exception e) {
            LOG.error("list() error while sorting", e);
        } // try/catch
    } // if
    response.setContentType("text/html; charset=UTF-8");
    request.setAttribute(Constants.THIS, contents);
    request.setAttribute(Constants.ATTRIBUTE_REQUEST, request);
    request.setAttribute(Constants.ATTRIBUTE_RESPONSE, response);
    request.setAttribute("classes", classes);
    request.setAttribute("canDelete", deleteMethodEnabled);
    request.setAttribute("prefix", Utils.getUriPrefix(request));
    if (cls != null) {
        Class<? extends Object> designClass = (cls.getName().indexOf('$') < 0) ? cls : cls.getSuperclass();
        request.setAttribute("designClass", designClass);
        request.setAttribute("designClassPackage", designClass.getPackage());
    } // if
    return new TargetDescriptor(contents, "tangramEditorList" + getVariant(request), null);
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * @param list//from   w w  w  .jav  a2  s.  c  o  m
 * @param pkg
 */
private static void checkClasses(List<Class> list, String pkg) {
    // The installed classfinder or directory search may inadvertently add too many 
    // classes.  This rountine is a 'double check' to make sure that the classes
    // are acceptable.
    for (int i = 0; i < list.size();) {
        Class cls = list.get(i);
        if (!cls.isInterface()
                && (cls.isEnum() || getAnnotation(cls, XmlType.class) != null
                        || ClassUtils.getDefaultPublicConstructor(cls) != null)
                && !ClassUtils.isJAXWSClass(cls) && !isSkipClass(cls)
                && cls.getPackage().getName().equals(pkg)) {
            i++; // Acceptable class
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Removing class " + cls + " from consideration because it is not in package " + pkg
                        + " or is an interface or does not have a public constructor or is" + " a jaxws class");
            }
            list.remove(i);
        }
    }
}

From source file:org.tangram.components.editor.EditingHandler.java

@LinkAction("/edit/id_(.*)")
public TargetDescriptor edit(@LinkPart(1) String id, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    LOG.info("edit() editing {}", id);
    if (request.getAttribute(Constants.ATTRIBUTE_ADMIN_USER) == null) {
        throw new Exception("User may not edit");
    } // if//from   w ww  . j  a v  a 2 s . c o  m
    response.setContentType("text/html; charset=UTF-8");
    Content content = beanFactory.getBean(id);
    if (content == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "no content with id " + id + " in repository.");
        return null;
    } // if
    if (content instanceof CodeResource) {
        CodeResource code = (CodeResource) content;
        request.setAttribute("compilationErrors",
                classRepository.getCompilationErrors().get(code.getAnnotation()));
    } // if
    request.setAttribute("beanFactory", getMutableBeanFactory());
    request.setAttribute("propertyConverter", propertyConverter);
    request.setAttribute("classes", getMutableBeanFactory().getClasses());
    request.setAttribute("prefix", Utils.getUriPrefix(request));
    Class<? extends Content> cls = content.getClass();
    String note = getOrmNote(cls);
    Class<? extends Object> designClass = getDesignClass(cls);
    request.setAttribute("note", note);
    request.setAttribute("contentClass", cls);
    request.setAttribute("designClass", designClass);
    request.setAttribute("designClassPackage", designClass.getPackage());

    return new TargetDescriptor(content, "edit" + getVariant(request), null);
}

From source file:ch.unil.genescore.main.PascalSettings.java

/** Dump all settings to a file (ugly format without comments) */
public void dumpSettingsToFile() {

    FileExport writer = new FileExport(Pascal.log, new File(outputDirectory_, "settingsDump.txt"));
    try {//  w w w .j  a  v a2 s .c o  m
        Class<?> cls = Class.forName("ch.unil.genescore.main.Settings");
        System.out.println("Class found = " + cls.getName());
        System.out.println("Package = " + cls.getPackage());
        Field f[] = cls.getFields();
        for (int i = 0; i < f.length; i++) {
            String result = String.format("%s\t%s", f[i].getName(), f[i].get(null));
            writer.println(result);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }
}

From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java

public ClassFinder(List<Class> classes) {
    this.classLoaderInterface = null;
    List<Info> infos = new ArrayList<Info>();
    List<Package> packages = new ArrayList<Package>();
    for (Class clazz : classes) {

        Package aPackage = clazz.getPackage();
        if (aPackage != null && !packages.contains(aPackage)) {
            infos.add(new PackageInfo(aPackage));
            packages.add(aPackage);//  ww w  .ja va 2  s  . c  o  m
        }

        ClassInfo classInfo = new ClassInfo(clazz);
        infos.add(classInfo);
        classInfos.put(classInfo.getName(), classInfo);
        for (Method method : clazz.getDeclaredMethods()) {
            infos.add(new MethodInfo(classInfo, method));
        }

        for (Constructor constructor : clazz.getConstructors()) {
            infos.add(new MethodInfo(classInfo, constructor));
        }

        for (Field field : clazz.getDeclaredFields()) {
            infos.add(new FieldInfo(classInfo, field));
        }
    }

    for (Info info : infos) {
        for (AnnotationInfo annotation : info.getAnnotations()) {
            List<Info> annotationInfos = getAnnotationInfos(annotation.getName());
            annotationInfos.add(info);
        }
    }
}

From source file:org.guzz.builder.JPA2AnnotationsBuilder.java

/**
 * Only retrieve {@link SequenceGenerator} and {@link TableGenerator} in the type declaration.
 *//*from   w ww. j  av  a  2  s  .c  o  m*/
public static void parseForIdGenerators(final Map idGenerators, Class domainCls) throws ClassNotFoundException {
    javax.persistence.Entity pe = (javax.persistence.Entity) domainCls
            .getAnnotation(javax.persistence.Entity.class);
    javax.persistence.MappedSuperclass pm = (javax.persistence.MappedSuperclass) domainCls
            .getAnnotation(javax.persistence.MappedSuperclass.class);

    if (pe == null && pm == null) {
        log.debug("Parsing for id generator ends at class:" + domainCls.getName());
        return;
    }

    //parse the super class first, then add/replace it from the subclass.
    Class superCls = domainCls.getSuperclass();
    if (superCls != null && superCls.isAnnotationPresent(javax.persistence.MappedSuperclass.class)) {
        parseForIdGenerators(idGenerators, superCls);
    }

    //parse for this class.
    SequenceGenerator psg = (SequenceGenerator) domainCls.getAnnotation(SequenceGenerator.class);
    TableGenerator tsg = (TableGenerator) domainCls.getAnnotation(TableGenerator.class);

    GenericGenerator[] ggs = new GenericGenerator[0];

    //add @GenericGenerators
    if (domainCls.getPackage().isAnnotationPresent(GenericGenerators.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                ((GenericGenerators) domainCls.getPackage().getAnnotation(GenericGenerators.class)).value());
    }
    if (domainCls.isAnnotationPresent(GenericGenerators.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                ((GenericGenerators) domainCls.getAnnotation(GenericGenerators.class)).value());
    }

    //add @GenericGenerator
    if (domainCls.getPackage().isAnnotationPresent(GenericGenerator.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                (GenericGenerator) domainCls.getPackage().getAnnotation(GenericGenerator.class));
    }
    if (domainCls.isAnnotationPresent(GenericGenerator.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                (GenericGenerator) domainCls.getAnnotation(GenericGenerator.class));
    }

    if (psg != null) {
        String name = psg.name();
        if (idGenerators.get(name) != null && log.isDebugEnabled()) {
            log.debug("override @Id annotation:[" + idGenerators.get(name)
                    + "] with @SequenceGenerator, name is:" + name);
        }

        idGenerators.put(name, psg);
    }

    if (tsg != null) {
        String name = tsg.name();
        if (idGenerators.get(name) != null && log.isDebugEnabled()) {
            log.debug("override @Id annotation:[" + idGenerators.get(name) + "] with @TableGenerator, name is:"
                    + name);
        }

        idGenerators.put(name, tsg);
    }

    if (ggs.length > 0) {
        for (GenericGenerator gg : ggs) {
            String name = gg.name();
            if (idGenerators.get(name) != null && log.isDebugEnabled()) {
                log.debug("override @Id annotation:[" + idGenerators.get(name)
                        + "] with @GenericGenerator, name is:" + name);
            }

            idGenerators.put(name, gg);
        }
    }
}

From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java

public boolean isJaxbClass(Class<?> clazz) {
    if (clazz == null) {
        throw new IllegalArgumentException("No class, no fun");
    }/*from w w w  .ja va2 s .  c om*/
    if (clazz.getPackage() == null) {
        // No package: this is most likely a primitive type and definitely
        // not a JAXB class
        return false;
    }
    for (Package jaxbPackage : getSchemaRegistry().getCompileTimePackages()) {
        if (jaxbPackage.equals(clazz.getPackage())) {
            return true;
        }
    }
    return false;
}

From source file:blue.lapis.pore.converter.wrapper.WrapperConverterTest.java

private Object create() {
    Class<?> base = interfaces.get(0);

    if (!base.isInterface() && Modifier.isFinal(base.getModifiers())) {
        if (base == Location.class) {
            return new Location(mock(Extent.class), 0, 0, 0);
        }//from   w ww  .j  av a  2 s  .c  o  m
    }

    Object mock;
    if (interfaces.size() == 1) {
        mock = mock(base);
    } else {
        mock = mock(base, withSettings().extraInterfaces(
                interfaces.subList(1, interfaces.size()).toArray(new Class<?>[interfaces.size() - 1])));
    }
    // o.b.BlockState's subclasses break this test because of incongruencies between SpongeAPI and Bukkit
    // this code basically assures that a NullPointerException won't be thrown while converting
    if (base.getPackage().getName().startsWith("org.spongepowered.api.block.tileentity")) {
        Location loc = new Location(mock(Extent.class), 0, 0, 0);
        BlockState state = mock(BlockState.class);
        when(loc.getBlock()).thenReturn(state);
        when(((TileEntity) mock).getLocation()).thenReturn(loc);
        when(((TileEntity) mock).getBlock()).thenReturn(state);
    }
    return mock;
}

From source file:org.apache.struts2.config.ClasspathPackageProvider.java

/**
 * Create a default action mapping for a class instance.
 *
 * The namespace annotation is honored, if found, otherwise
 * the Java package is converted into the namespace
 * by changing the dots (".") to slashes ("/").
 *
 * @param cls Action or POJO instance to process
 * @param pkgs List of packages that were scanned for Actions
 */// www  .  j  a  v a  2  s.  co m
protected void processActionClass(Class<?> cls, String[] pkgs) {
    String name = cls.getName();
    String actionPackage = cls.getPackage().getName();
    String actionNamespace = null;
    String actionName = null;

    org.apache.struts2.config.Action actionAnn = (org.apache.struts2.config.Action) cls
            .getAnnotation(org.apache.struts2.config.Action.class);
    if (actionAnn != null) {
        actionName = actionAnn.name();
        if (actionAnn.namespace().equals(org.apache.struts2.config.Action.DEFAULT_NAMESPACE)) {
            actionNamespace = "";
        } else {
            actionNamespace = actionAnn.namespace();
        }
    } else {
        for (String pkg : pkgs) {
            if (name.startsWith(pkg)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("ClasspathPackageProvider: Processing class " + name);
                }
                name = name.substring(pkg.length() + 1);

                actionNamespace = "";
                actionName = name;
                int pos = name.lastIndexOf('.');
                if (pos > -1) {
                    actionNamespace = "/" + name.substring(0, pos).replace('.', '/');
                    actionName = name.substring(pos + 1);
                }
                break;
            }
        }
        // Truncate Action suffix if found
        if (actionName.endsWith(getClassSuffix())) {
            actionName = actionName.substring(0, actionName.length() - getClassSuffix().length());
        }

        // Force initial letter of action to lowercase, if desired
        if ((forceLowerCase) && (actionName.length() > 1)) {
            int lowerPos = actionName.lastIndexOf('/') + 1;
            StringBuilder sb = new StringBuilder();
            sb.append(actionName.substring(0, lowerPos));
            sb.append(Character.toLowerCase(actionName.charAt(lowerPos)));
            sb.append(actionName.substring(lowerPos + 1));
            actionName = sb.toString();
        }
    }

    PackageConfig.Builder pkgConfig = loadPackageConfig(actionNamespace, actionPackage, cls);

    // In case the package changed due to namespace annotation processing
    if (!actionPackage.equals(pkgConfig.getName())) {
        actionPackage = pkgConfig.getName();
    }

    List<PackageConfig> parents = findAllParentPackages(cls);
    if (parents.size() > 0) {
        pkgConfig.addParents(parents);

        // Try to guess the namespace from the first package
        PackageConfig firstParent = parents.get(0);
        if (StringUtils.isEmpty(pkgConfig.getNamespace())
                && StringUtils.isNotEmpty(firstParent.getNamespace())) {
            pkgConfig.namespace(firstParent.getNamespace());
        }
    }

    ResultTypeConfig defaultResultType = packageLoader.getDefaultResultType(pkgConfig);
    ActionConfig actionConfig = new ActionConfig.Builder(actionPackage, actionName, cls.getName())
            .addResultConfigs(new ResultMap<String, ResultConfig>(cls, actionName, defaultResultType)).build();
    pkgConfig.addActionConfig(actionName, actionConfig);
}

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

/**
 * Generates insert query for the specified object
 * @param object the object to generate insert query for
 * @return the insert SQL query/*from   w w w . jav  a2 s.  c om*/
 */
public String generateInsertQuery(Object object) {
    BeanWrapper wr = new BeanWrapperImpl(object);
    String objectName = Convert.toSimpleName(object.getClass().getName());
    String tableName = Convert.toDB(objectName);
    PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();

    //generate insert query
    StringBuffer query = new StringBuffer("insert into " + tableName + "(");
    StringBuffer values = new StringBuffer(" values(");
    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 (fieldName.equals("id")) continue; //remove if it does not break the sequence
        if (dbClasses.contains(fieldClass)) { //direct database field (Integer,String,Date, etc)
            query.append(columnName.equals("order") ? "\"order\"" : columnName);
            query.append(",");
            values.append(":").append(fieldName);
            values.append(",");
        }
        if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) { //object
            query.append(Convert.toDB(fieldName)).append("_id");
            query.append(",");
            values.append(":").append(fieldName).append(".id");
            values.append(",");
        }
    }
    query.deleteCharAt(query.length() - 1);
    query.append(")");
    values.deleteCharAt(values.length() - 1);
    values.append(");");
    query.append(values);

    return query.toString();
}