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.jasig.ssp.TestUtils.java

/**
 * Load and parse a JSON file based on the testClass and file.
 * //from w ww.j av a 2s .  com
 * <p>
 * JSON file must not contain any line breaks or new line characters.
 * 
 * <p>
 * For example, if testClass is
 * <code>org.jasig.mygps.business.StudentIntakeFormManagerTest</code> and
 * file is <code>studentintakeform_empty.json</code>, this method will
 * attempt to load the file
 * <code>org/jasig/mygps/business/studentintakeform_empty.json</code>.
 * 
 * @param testClass
 *            Testing class, used for resource loading based on the
 *            concatenated namespace and file name, via {link
 *            Class#getResourceAsStream(String)}. Required.
 * @param file
 *            the JSON file to load, relative to the namespace of the
 *            calling testClass. Required.
 * @param TOClass
 *            Required; serializes the JSON to this transfer object class.
 *            If the JSON can not be serialized to this class, an exception
 *            will be thrown.
 * @return Transfer object equivalent of the JSON file contents
 * @exception JsonParseException
 *                if test file could not be parsed
 * @exception JsonMappingException
 *                if test file could not be mapped
 * @exception IOException
 *                if test file could not be loaded, or missing/empty file
 */
public static <T, TO, TS> TO loadJson(@NotNull final Class<TS> testClass, @NotNull final String file,
        @NotNull final Class<TO> TOClass) throws JsonParseException, JsonMappingException, IOException {
    if (!StringUtils.isNotBlank(file)) {
        throw new IOException("Missing file parameter.");
    }

    assertNotNull("Test suite class can not be null.", testClass);
    assertNotNull("Transfer object class can not be null.", TOClass);

    // Load file
    try {
        final InputStreamReader is = new InputStreamReader(testClass.getResourceAsStream(file));

        final BufferedReader in = new BufferedReader(is);

        final String json = in.readLine();
        LOGGER.debug("Test class {} loaded the following JSON: {}", testClass.getName() + " with file " + file,
                json);

        final TO obj = objectMapper.readValue(json, TOClass);

        if (in != null) {
            in.close();
        }

        if (is != null) {
            is.close();
        }

        assertNotNull("File data could not be parsed from " + file, obj);

        return obj;
    } catch (final NullPointerException exc) { // NOPMD NPE is in library
        throw new IOException("Could not load the specified file "
                + testClass.getPackage().getName().replace('.', '/') + "/" + file, exc);
    } catch (final UnrecognizedPropertyException exc) {
        throw new JsonMappingException(
                "JSON fields did not match transfer object class properties. See exception cause for erroneous field names.",
                exc);
    }
}

From source file:org.atemsource.atem.impl.pojo.ScannedPojoEntityTypeRepository.java

protected boolean isAvailable(Class clazz) {
    // TODO package is null for enum types and inner types?
    return (entityClass == null || entityClass.isAssignableFrom(clazz)) && (includedPackage == null
            || (clazz.getPackage() != null && clazz.getPackage().getName().startsWith(includedPackage)));
}

From source file:com.neocotic.bloggaer.common.LocatorHelper.java

/**
 * Retrieves the {@code class} name of the POJO implementation.
 * /*ww  w  .jav  a2s. c o m*/
 * @param cls
 *            the {@code class} whose target {@code class} name is to be retrieved
 * @param packageName
 *            the name of the sub-package to be appended to the package name of the target {@code class}
 * @param prefix
 *            the {@code String} to be prepended to the name of the target {@code class}
 * @param suffix
 *            the {@code String} to be appended to the name of the target {@code class}
 * @return The name of the implementation {@code class}.
 * @throws NullPointerException
 *             If {@code cls} is {@code null}.
 */
public <T extends I> String getImplementationClassName(Class<T> cls, String packageName, String prefix,
        String suffix) {
    logger.entering(new Object[] { cls, packageName, prefix, suffix });

    StringBuilder buffer = new StringBuilder();
    buffer.append(cls.getPackage().getName());
    buffer.append(ClassUtils.PACKAGE_SEPARATOR);
    if (packageName != null) {
        buffer.append(packageName);
        buffer.append(ClassUtils.PACKAGE_SEPARATOR);
    }
    if (prefix != null)
        buffer.append(prefix);
    buffer.append(cls.getSimpleName());
    if (suffix != null)
        buffer.append(suffix);
    String className = buffer.toString();

    logger.exiting(className);
    return className;
}

From source file:org.wso2.msf4j.spring.MSF4JSpringApplication.java

/**
 * This will add a given service class to the running instnace with given base path.
 *
 * @param configurableApplicationContext ConfigurableApplicationContext of running app
 * @param serviceClass Service class//from w ww  . j a va2 s .c  o  m
 * @param basePath Base path teh servuce get registered
 */
public void addService(ConfigurableApplicationContext configurableApplicationContext, Class serviceClass,
        String basePath) {
    ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(
            (BeanDefinitionRegistry) configurableApplicationContext);
    classPathBeanDefinitionScanner.scan(serviceClass.getPackage().getName());
    SpringMicroservicesRunner springMicroservicesRunner = configurableApplicationContext
            .getBean(SpringMicroservicesRunner.class);
    springMicroservicesRunner.deploy(basePath, configurableApplicationContext.getBean(serviceClass));
}

From source file:com.oakhole.Generate.java

/**
 * object/*from w w w  .  j  ava 2  s  .  c  o  m*/
 * @param object
 * @return
 */
private Map<String, Object> getDataModel(Class object) {
    Map<String, Object> dataModel = Maps.newHashMap();

    // Step 1: ?
    dataModel.put("author", "Oakhole");
    dataModel.put("since", "1.0");

    // Step 2: ?packageName?className?
    String packageName = object.getPackage().getName();

    // ?Entity
    packageName = packageName.substring(0, packageName.lastIndexOf("."));

    // ???
    String className = object.getName();
    className = className.substring(className.lastIndexOf(".") + 1, className.length());

    // Step 3: 
    dataModel.put("packageName", packageName);
    dataModel.put("ClassName", className);
    dataModel.put("className", StringUtils.uncapitalize(className));

    return dataModel;
}

From source file:org.silverpeas.core.test.WarBuilder.java

/**
 * Constructs a war builder for the specified test class. It will load all the resources in the
 * same packages of the specified test class.
 * @param classOfTest the class of the test for which a war archive will be build.
 * @param <U> the type of the test.
 *//*from  w  w w  .ja v a2s . c o  m*/
protected <U> WarBuilder(Class<U> classOfTest) {
    this.classOfTest = classOfTest;
    testCoreClassMavenTargetDirectoryRule = new MavenTargetDirectoryRule(WarBuilder.class);
    String resourcePath = classOfTest.getPackage().getName().replaceAll("\\.", "/");
    logInfo("Adding resources from path: " + resourcePath);
    war.addAsResource(resourcePath);
    war.addAsResource("META-INF/test-MANIFEST.MF", "META-INF/MANIFEST.MF");
}

From source file:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateSearchQueryExecutor.java

/**
 * @param request/*  w w w  .ja  v a2 s. com*/
 * @return
 * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest)
 */
@Override
public boolean process(final ChainRequest request) {
    final HibernateExecReq executionReq = new HibernateExecReq(request);

    final SearchQuery searchQuery = executionReq.getSearchQuery();
    notNull(searchQuery, "Expected SearchQuery");

    final Class<? extends PersistentEntity<?>> persistentClass = executionReq.getRootEntity();
    notNull(persistentClass, "Expected Root Entity");

    final SessionFactory sessionFactory = executionReq.getSessionFactory();
    notNull(sessionFactory, "Expected Datasource SessionFactory");

    final GenericCriteria hibernateCriteria = QueryBuilderHibernateImpl.convert(CriteriaType.CRITERIA,
            persistentClass.getPackage().getName(), sessionFactory, searchQuery);
    executionReq.setResult(hibernateCriteria);
    executionReq.setStatus("Transformed query for execution");

    return false;
}

From source file:hu.bme.mit.sette.common.tasks.TestSuiteGenerator.java

public void generate() throws Exception {
    if (!RunnerProjectUtils.getRunnerLogFile(getRunnerProjectSettings()).exists()) {
        throw new SetteGeneralException("Run the tool on the runner project first (and then parse)");
    }/*from   w w  w .  j  a  v  a 2  s.  c  o  m*/

    File testsDir = getRunnerProjectSettings().getTestsDirectory();
    if (testsDir.exists()) {
        System.out.println("Removing tests dir");
        FileUtils.forceDelete(testsDir);
    }

    FileUtils.forceMkdir(testsDir);

    Serializer serializer = new Persister(new AnnotationStrategy());

    // foreach containers
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        // skip container with higher java version than supported
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO error handling
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }

        // foreach snippets
        for (Snippet snippet : container.getSnippets().values()) {
            File inputsXmlFile = RunnerProjectUtils.getSnippetInputsFile(getRunnerProjectSettings(), snippet);

            if (!inputsXmlFile.exists()) {
                System.err.println("Missing: " + inputsXmlFile);
                continue;
            }

            // save current class loader
            ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

            // set snippet project class loader
            Thread.currentThread().setContextClassLoader(getSnippetProject().getClassLoader());

            // read data
            SnippetInputsXml inputsXml = serializer.read(SnippetInputsXml.class, inputsXmlFile);

            // set back the original class loader
            Thread.currentThread().setContextClassLoader(originalClassLoader);

            if (inputsXml.getResultType() != ResultType.S && inputsXml.getResultType() != ResultType.C
                    && inputsXml.getResultType() != ResultType.NC) {
                // skip!
                continue;
            }

            if (inputsXml.getGeneratedInputs().size() == 0) {
                System.err.println("No inputs: " + inputsXmlFile);
            }

            Class<?> javaClass = container.getJavaClass();
            Package pkg = javaClass.getPackage();
            Method method = snippet.getMethod();

            StringBuilder java = new StringBuilder();

            String classSimpleName = javaClass.getSimpleName() + '_' + method.getName() + "_Tests";
            String className = pkg.getName() + "." + classSimpleName;

            java.append("package ").append(pkg.getName()).append(";\n");
            java.append("\n");
            java.append("import junit.framework.TestCase;\n");
            java.append("import ").append(container.getJavaClass().getName()).append(";\n");
            java.append("\n");
            java.append("public final class ").append(classSimpleName).append(" extends TestCase {\n");

            int i = 0;
            for (InputElement inputElement : inputsXml.getGeneratedInputs()) {
                i++;

                java.append("    public void test_").append(i).append("() throws Exception {\n");

                // heap
                if (StringUtils.isNotBlank(inputElement.getHeap())) {
                    for (String heapLine : inputElement.getHeap().split("\\r?\\n")) {
                        java.append("        ").append(heapLine).append('\n');
                    }

                    java.append("        \n");
                }

                // try-catch for exception if any expected
                if (inputElement.getExpected() != null) {
                    java.append("        try {\n");
                    java.append("            ");

                    appendMethodCall(java, javaClass, method, inputElement);
                    java.append("            fail();\n");
                    java.append("        } catch (").append(inputElement.getExpected()).append(" e) {\n");
                    java.append("        }\n");
                } else {
                    java.append("        ");
                    appendMethodCall(java, javaClass, method, inputElement);
                }

                java.append("    }\n\n");
            }

            java.append("}\n");

            File testsFile = new File(testsDir, JavaFileUtils.classNameToSourceFilename(className));
            FileUtils.write(testsFile, java.toString());

            // import junit.framework.TestCase;
            // import
            // hu.bme.mit.sette.snippets._1_basic.B2_conditionals.B2a_IfElse;
            //
            // public final class B2a_IfElse_oneParamInt_Tests extends
            // TestCase {
            // public void test_1() {
            // B2a_IfElse.oneParamInt(1);
            // }
            //
            // public void test_2() {
            // B2a_IfElse.oneParamInt(0);
            // }
            //
            // public void test_3() {
            // B2a_IfElse.oneParamInt(-1);
            // }
            //
            // public void test_4() {
            // B2a_IfElse.oneParamInt(12345);
            // }
            // }

        }
    }

}

From source file:org.apache.streams.plugins.StreamsScalaSourceGenerator.java

private String renderTrait(Class<?> pojoClass) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("package ");
    stringBuffer.append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala"));
    stringBuffer.append(".traits");
    stringBuffer.append(LS);/*from   w ww . jav a  2  s  . c  o  m*/
    stringBuffer.append("trait ").append(pojoClass.getSimpleName());
    stringBuffer.append(" extends Serializable");
    stringBuffer.append(" {");

    Set<Field> fields = ReflectionUtils.getAllFields(pojoClass);
    appendFields(stringBuffer, fields, "def", ";");

    stringBuffer.append("}");

    return stringBuffer.toString();
}

From source file:org.apache.streams.plugins.StreamsScalaSourceGenerator.java

private String renderCase(Class<?> pojoClass) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("package ");
    stringBuffer.append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala"));
    stringBuffer.append(LS);//w  w  w. j a  v  a 2  s . c o m
    stringBuffer.append("case class " + pojoClass.getSimpleName());
    stringBuffer.append("(");
    Set<Field> fields = ReflectionUtils.getAllFields(pojoClass);
    appendFields(stringBuffer, fields, "var", ",");
    stringBuffer.append(")");
    if (pojoClass.getSuperclass() != null && !pojoClass.getSuperclass().equals(java.lang.Object.class)) {
        stringBuffer.append(
                " extends " + pojoClass.getSuperclass().getPackage().getName().replace(".pojo.json", ".scala")
                        + ".traits." + pojoClass.getSuperclass().getSimpleName());
    }
    stringBuffer.append(LS);

    return stringBuffer.toString();
}