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:hu.bme.mit.sette.tools.catg.CatgGenerator.java

private void createGeneratedFiles() throws IOException {
    // generate main() for each snippet
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO enhance message
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }//from w w  w  .ja  v  a 2  s  . c om

        snippetLoop: for (Snippet snippet : container.getSnippets().values()) {
            Method method = snippet.getMethod();
            Class<?> javaClass = method.getDeclaringClass();
            Class<?>[] parameterTypes = method.getParameterTypes();

            // generate main()
            JavaClassWithMain main = new JavaClassWithMain();
            main.setPackageName(javaClass.getPackage().getName());
            main.setClassName(javaClass.getSimpleName() + '_' + method.getName());

            main.imports().add(javaClass.getName());
            main.imports().add("catg.CATG");

            String[] paramNames = new String[parameterTypes.length];
            List<String> createVariableLines = new ArrayList<>(parameterTypes.length);
            List<String> sysoutVariableLines = new ArrayList<>(parameterTypes.length);

            int i = 0;
            for (Class<?> parameterType : parameterTypes) {
                String paramName = "param" + (i + 1);
                String varType = CatgGenerator.getTypeString(parameterType);
                String catgRead = CatgGenerator.createCatgRead(parameterType);

                if (varType == null || catgRead == null) {
                    // TODO make better
                    System.err.println("Method has an unsupported parameter type: " + parameterType.getName()
                            + " (method: " + method.getName() + ")");
                    continue snippetLoop;
                }

                paramNames[i] = paramName;
                // e.g.: int param1 = CATG.readInt(0);
                createVariableLines.add(String.format("%s %s = %s;", varType, paramName, catgRead));
                // e.g.: System.out.println("  int param1 = " + param1);
                sysoutVariableLines.add(String.format("System.out.println(\"  %s %s = \" + %s);", varType,
                        paramName, paramName));
                i++;
            }

            main.codeLines().addAll(createVariableLines);

            main.codeLines().add("");

            main.codeLines().add(String.format("System.out.println(\"%s#%s\");", javaClass.getSimpleName(),
                    method.getName()));
            main.codeLines().addAll(sysoutVariableLines);

            String functionCall = String.format("%s.%s(%s)", javaClass.getSimpleName(), method.getName(),
                    StringUtils.join(paramNames, ", "));

            Class<?> returnType = method.getReturnType();

            if (Void.TYPE.equals(returnType) || Void.class.equals(returnType)) {
                // void return type
                main.codeLines().add(functionCall + ';');
                main.codeLines().add("System.out.println(\"  result: void\");");
            } else {
                // non-void return type
                main.codeLines().add("System.out.println(\"  result: \" + " + functionCall + ");");
            }

            // save files
            String relativePath = JavaFileUtils.packageNameToFilename(main.getFullClassName());
            String relativePathMain = relativePath + '.' + JavaFileUtils.JAVA_SOURCE_EXTENSION;

            File targetMainFile = new File(getRunnerProjectSettings().getGeneratedDirectory(),
                    relativePathMain);
            FileUtils.forceMkdir(targetMainFile.getParentFile());
            FileUtils.write(targetMainFile, main.generateJavaCode().toString());
        }
    }
}

From source file:thewebsemantic.Bean2RDF.java

/**
 * Adds definitions of superclasses.// w  w  w .j  av a  2  s .com
 * 
 * @param cls - Java class (which is mapped)
 * @param owlClass - resource in which the Java class is mapped
 * @return OWL class
 */
private Resource addSuperClasses(Class<?> cls, OntClass owlClass) {

    if (HibernateProxy.class.isAssignableFrom(cls))
        return addSuperClasses(cls.getSuperclass(), owlClass);

    Class<?> superClass = cls.getSuperclass();
    Class<?>[] interfaces = cls.getInterfaces();
    try {
        if (superClass.getPackage().equals(cls.getPackage())) {
            OntClass owlSuperClass = (OntClass) getOWLClass(superClass);
            applyAnnotations(superClass, owlSuperClass);
            owlClass.addSuperClass(owlSuperClass);
            addSuperClasses(superClass, owlSuperClass);
        }
        for (Class<?> interfaceCls : interfaces) {
            if (interfaceCls.getPackage().equals(cls.getPackage())) {
                OntClass owlSuperClass = (OntClass) getOWLClass(interfaceCls);
                applyAnnotations(interfaceCls, owlSuperClass);
                owlClass.addSuperClass(owlSuperClass);
            }
        }
    } catch (Exception e) {
        // nothing, just continue
    }

    return owlClass;
}

From source file:com.evolveum.midpoint.web.security.MidPointApplication.java

private void mountFiles(String path, Class<?> clazz) {
    try {//w w w  . ja v  a2  s . com
        List<Resource> list = new ArrayList<>();
        String packagePath = clazz.getPackage().getName().replace('.', '/');

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] res = resolver.getResources("classpath:" + packagePath + "/*.png");
        if (res != null) {
            list.addAll(Arrays.asList(res));
        }
        res = resolver.getResources("classpath:" + packagePath + "/*.gif");
        if (res != null) {
            list.addAll(Arrays.asList(res));
        }

        for (Resource resource : list) {
            URI uri = resource.getURI();
            File file = new File(uri.toString());
            mountResource(path + "/" + file.getName(), new SharedResourceReference(clazz, file.getName()));
        }
    } catch (Exception ex) {
        LoggingUtils.logException(LOGGER, "Couldn't mount files", ex);
    }
}

From source file:org.fusesource.hawtjni.generator.HawtJNI.java

@SuppressWarnings("unchecked")
private void collectMatchingClasses(ClassFinder finder, Class annotation, LinkedHashSet<Class<?>> collector) {
    List<Class> annotated = finder.findAnnotatedClasses(annotation);
    for (Class<?> clazz : annotated) {
        if (packages.isEmpty()) {
            collector.add(clazz);/*from  w w w.j a va  2  s .  co m*/
        } else {
            if (packages.contains(clazz.getPackage().getName())) {
                collector.add(clazz);
            }
        }
    }
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

/**
 * Loads the set of input properties for the specified operation.
 *
 * @param op The operation.//from  w  w  w  .  j av a  2s .  co  m
 * @return The input properties, or null if none were found.
 */
protected OperationBeanInfo getRequestInfo(OperationInfo op) throws XFireFault {
    Method method = op.getMethod();
    Class ei = method.getDeclaringClass();
    Package pckg = ei.getPackage();
    SOAPBinding.ParameterStyle paramStyle = SOAPBinding.ParameterStyle.WRAPPED;
    if (method.isAnnotationPresent(SOAPBinding.class)) {
        SOAPBinding annotation = method.getAnnotation(SOAPBinding.class);
        paramStyle = annotation.parameterStyle();
    } else if (ei.isAnnotationPresent(SOAPBinding.class)) {
        SOAPBinding annotation = ((SOAPBinding) ei.getAnnotation(SOAPBinding.class));
        paramStyle = annotation.parameterStyle();
    }

    boolean schemaValidate = method.isAnnotationPresent(SchemaValidate.class)
            || ei.isAnnotationPresent(SchemaValidate.class) || pckg.isAnnotationPresent(SchemaValidate.class);

    if (paramStyle == SOAPBinding.ParameterStyle.BARE) {
        //return a bare operation info.
        //it's not necessarily the first parameter type! there could be a header or OUT parameter...
        int paramIndex;
        WebParam annotation = null;
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if (parameterAnnotations.length == 0) {
            throw new IllegalStateException("A BARE web service must have input parameters.");
        }

        PARAM_ANNOTATIONS: for (paramIndex = 0; paramIndex < parameterAnnotations.length; paramIndex++) {
            Annotation[] annotations = parameterAnnotations[paramIndex];
            for (Annotation candidate : annotations) {
                if (candidate instanceof WebParam && !((WebParam) candidate).header()) {
                    WebParam.Mode mode = ((WebParam) candidate).mode();
                    switch (mode) {
                    case OUT:
                    case INOUT:
                        annotation = (WebParam) candidate;
                        break PARAM_ANNOTATIONS;
                    }
                }
            }
        }

        if (annotation == null) {
            paramIndex = 0;
        }

        return new OperationBeanInfo(method.getParameterTypes()[paramIndex], null, op.getInputMessage(),
                schemaValidate);
    } else {
        String requestWrapperClassName;
        RequestWrapper requestWrapperInfo = method.getAnnotation(RequestWrapper.class);
        if ((requestWrapperInfo != null) && (requestWrapperInfo.className() != null)
                && (requestWrapperInfo.className().length() > 0)) {
            requestWrapperClassName = requestWrapperInfo.className();
        } else {
            StringBuilder builder = new StringBuilder(pckg == null ? "" : pckg.getName());
            if (builder.length() > 0) {
                builder.append(".");
            }

            builder.append("jaxws.");

            String methodName = method.getName();
            builder.append(capitalize(methodName));
            requestWrapperClassName = builder.toString();
        }

        Class wrapperClass;
        try {
            wrapperClass = ClassLoaderUtils.loadClass(requestWrapperClassName, getClass());
        } catch (ClassNotFoundException e) {
            LOG.error("Unabled to find request wrapper class " + requestWrapperClassName + "... Operation "
                    + op.getQName() + " will not be able to recieve...");
            return null;
        }

        return new OperationBeanInfo(wrapperClass, loadOrderedProperties(wrapperClass), op.getInputMessage(),
                schemaValidate);
    }

}

From source file:net.sourceforge.vulcan.web.struts.forms.PluginConfigForm.java

private boolean isPrimitive(Class<?> cls) {
    if (cls.isPrimitive()) {
        return true;
    } else if ("java.lang".equals(cls.getPackage().getName())) {
        return true;
    } else if (Date.class.isAssignableFrom(cls)) {
        return true;
    }//from   www.  j a va  2 s  .  c  om

    return false;
}

From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java

@Override
protected Set<Class> findActions() {
    Set<Class> classes = new HashSet<Class>();

    final ApplicationContext ac = this.applicationContext;
    String[] beanNames = ac.getBeanDefinitionNames();
    for (String beanName : beanNames) {

        // don't care for the bean itself right now, just it's class
        Class beanClass = ac.getType(beanName);

        // first of all, check for the @Controller annotation...
        // then, if it's inside the right package (base controllers package)
        if (beanClass.isAnnotationPresent(Controller.class)
                && beanClass.getPackage().getName().startsWith(this.packageLocatorsBasePackage)) {
            // we must warn in case of a singleton scoped controller
            if (ac.isSingleton(beanName)) {
                LOG.warn(""); // TODO
            }/*from  ww  w. j  a v  a  2s  .  com*/
            classes.add(beanClass);
        }

    }
    return classes;
}

From source file:de.crowdcode.kissmda.maven.plugin.KissMdaMojo.java

private Class<? extends AbstractModule> getGuiceModule(final Set<Class<? extends AbstractModule>> guiceModules,
        final Class<? extends Transformer> transformerClazz) throws MojoExecutionException {
    Class<? extends AbstractModule> currentGuiceModuleClazz = null;
    for (Class<? extends AbstractModule> guiceModuleClazz : guiceModules) {
        // Check the package
        String transformerPackageName = transformerClazz.getPackage().getName();
        String guiceModulePackageName = guiceModuleClazz.getPackage().getName();
        if (guiceModulePackageName.equalsIgnoreCase(transformerPackageName)) {
            String guiceModuleNameWithoutModule = StringUtils.replace(guiceModuleClazz.getName(), MODULE_SUFFIX,
                    "");
            String transformerNameWithoutTransformer = StringUtils.replace(transformerClazz.getName(),
                    TRANSFORMER_SUFFIX, "");
            if (guiceModuleNameWithoutModule.equals(transformerNameWithoutTransformer)) {
                currentGuiceModuleClazz = guiceModuleClazz;
                logger.info("Start the transformation with following Guice Module: "
                        + currentGuiceModuleClazz.getName());
                break;
            }/*from   w ww  . j  a v  a  2s.  co m*/
        }
    }

    if (currentGuiceModuleClazz == null) {
        // No module found at all, error
        throw new MojoExecutionException(ERROR_GUICE_SAME_PACKAGE_NOT_FOUND);
    }

    return currentGuiceModuleClazz;
}

From source file:org.atricore.idbus.kernel.main.util.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {// ww w  .  j av a  2  s .  c o  m
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(
                                "An IOException error was thrown when trying to read the jar file.");
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:org.getobjects.appserver.products.GoProductInfo.java

protected Class primaryLoadCode(final WOApplication _app) {
    final ClassLoader cl = this.classLoader();
    if (cl == null) {
        log.error("did not find class loader for product: " + this);
        return null;
    }/*from   ww w.  j  av  a  2  s  .  co m*/

    /* find/load product class */

    Class cls = null;
    try {
        cls = cl.loadClass(this.fqn + ".WOFramework");
    } catch (ClassNotFoundException e) {
    }

    /* hack for main package */
    if (cls == null && _app != null) {
        Class appCls = _app.getClass();
        if (this.fqn.equals(appCls.getPackage().getName()))
            cls = appCls;
    }

    if (cls == null)
        log.warn("did not find product class: " + this.fqn);

    return cls;
}