List of usage examples for java.lang Package getName
public String getName()
From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java
private Class getObjectFactoryClassUncached(Package pkg) { try {// w w w.ja v a2 s. c o m return Class.forName(pkg.getName() + ".ObjectFactory"); } catch (ClassNotFoundException e) { throw new IllegalArgumentException( "Cannot find object factory class in package " + pkg.getName() + ": " + e.getMessage(), e); } }
From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java
/** * Determine imports for the given bundle. Based on the user settings, this * method will consider only the the test hierarchy until the testing * framework is found or all classes available inside the test bundle. <p/> * Note that split packages are not supported. * /*from ww w .j a v a 2s.c o m*/ * @return */ private String[] determineImports() { boolean useTestClassOnly = false; // no jar entry present, bail out. if (jarEntries == null || jarEntries.isEmpty()) { logger.debug("No test jar content detected, generating bundle imports from the test class"); useTestClassOnly = true; } else if (createManifestOnlyFromTestClass()) { logger.info("Using the test class for generating bundle imports"); useTestClassOnly = true; } else logger.info("Using all classes in the jar for the generation of bundle imports"); // className, class resource Map entries; if (useTestClassOnly) { entries = new LinkedHashMap(4); // get current class (test class that bootstraps the OSGi infrastructure) Class<?> clazz = getClass(); String clazzPackage = null; String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName(); do { // consider inner classes as well List classes = new ArrayList(4); classes.add(clazz); CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes); for (Iterator iterator = classes.iterator(); iterator.hasNext();) { Class<?> classToInspect = (Class) iterator.next(); Package pkg = classToInspect.getPackage(); if (pkg != null) { clazzPackage = pkg.getName(); String classFile = ClassUtils.getClassFileName(classToInspect); entries.put(classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX), new InputStreamResource(classToInspect.getResourceAsStream(classFile))); } // handle default package else { logger.warn("Could not find package for class " + classToInspect + "; ignoring..."); } } clazz = clazz.getSuperclass(); } while (!endPackage.equals(clazzPackage)); } else entries = jarEntries; return determineImportsFor(entries); }
From source file:de.lmu.ifi.dbs.jfeaturelib.utils.Extractor.java
/** * Prints the supports capabilities of the feature descriptors and prints the string to System.out. *//*from ww w.java 2 s . co m*/ private void listFeatureDescriptorCapabilities() throws InstantiationException, IllegalAccessException, IOException, URISyntaxException { Package fdPackage = FeatureDescriptor.class.getPackage(); int offset = fdPackage.getName().length() + 1; // search for the descriptors PackageScanner<FeatureDescriptor> scanner = new PackageScanner<>(); List<Class<FeatureDescriptor>> classes = scanner.scanForClass(fdPackage, FeatureDescriptor.class); // find the longest name to make a nice output int maxNameLength = 0; for (Class<FeatureDescriptor> fd : classes) { maxNameLength = Math.max(fd.getName().length() - offset, maxNameLength); } // sort the classes by class name Collections.sort(classes, new ClassNameComparator()); // now we know the longest descriptor name - build the output string StringBuilder outString = new StringBuilder(); for (Class<FeatureDescriptor> fd : classes) { String name = fd.getName().substring(offset); outString.append(StringUtils.rightPad(name, maxNameLength)); outString.append(" : "); outString.append(fd.newInstance().supports().toString()); outString.append("\n"); } System.out.println(outString); }
From source file:com.kjt.service.common.SoafwTesterMojo.java
private String readTestSrc(String className) { BufferedReader br = null;//from w w w. j a v a 2 s . c om String test = className + "Test"; StringBuilder testSrc = new StringBuilder(); try { Class tstCls = cl.loadClass(test); Package pkg = tstCls.getPackage(); String pkgName = pkg.getName(); String relativePath = pkgName.replace(".", File.separator); String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java"; String testSrcFullPath = testBaseSrcPath + File.separator + relativePath + File.separator + tstCls.getSimpleName() + ".java"; br = new BufferedReader(new InputStreamReader(new FileInputStream(testSrcFullPath), "UTF-8")); String line = null; while ((line = br.readLine()) != null) { testSrc.append(line); testSrc.append("\n"); } } catch (Exception e) { this.getLog().error(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } this.getLog().info(testSrc); return testSrc.toString(); } }
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 ww w. ja va2s . 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:freemarker.ext.dump.BaseDumpDirective.java
private String getReturnTypeName(Method method) { Class<?> cls = method.getReturnType(); Package pkg = cls.getPackage(); if (pkg != null) { // void return type has null package String packageName = pkg.getName(); if (packageName.startsWith("java")) { return getSimpleTypeName(cls); }/* w w w.jav a 2 s . c om*/ } return cls.getName(); }
From source file:org.openspotlight.graph.query.AbstractGeneralQueryTest.java
/** * Gets the resource content. Populate graph. *///from w w w . j a v a2 s. c o m @Before public void populateGraph() throws Exception { if (!didItRun) { createStartUpHandler().call(); shutdownHandler = createShutdownHandler(); session = graphReader(); sortMode = SortMode.SORTED; final Metadata metadata = session.getMetadata(); if (metadata.getMetaNodeType(JavaType.class) != null) { return; } final Collection<Class<?>> iFaces = loadClasses("java-util-interfaces.txt"); final Collection<Class<?>> classes = loadClasses("java-util-classes.txt"); final Context context = session.getContext("queryTest"); final Package pack = java.util.Date.class.getPackage(); final JavaPackage utilJavaPackage = writer.addNode(context, JavaPackage.class, pack.getName()); // utilJavaPackage.setCaption(pack.getName()); int count = 0; final float floatValue = 0.3F; for (final Class<?> iFace : iFaces) { final JavaInterface javaInterface = writer.addChildNode(utilJavaPackage, JavaInterface.class, iFace.getName()); writer.addLink(PackageContainsType.class, utilJavaPackage, javaInterface); // javaInterface.setCaption(iFace.getName()); javaInterface.setIntValue(count); javaInterface.setDecValue(new Float(count + floatValue)); javaInterface.setBoolValue(new Boolean(true)); addJavaInterfaceHirarchyLinks(context, iFace, javaInterface); addJavaInterfaceContainsJavaMethod(iFace, javaInterface); count++; } count = 0; for (final Class<?> clazz : classes) { // context = session.createContext("queryTest2"); final JavaClass javaClass = writer.addChildNode(utilJavaPackage, JavaClass.class, clazz.getName()); writer.addLink(PackageContainsType.class, utilJavaPackage, javaClass); // javaClass.setCaption(clazz.getName()); javaClass.setIntValue(count); javaClass.setDecValue(new Float(count + floatValue)); javaClass.setBoolValue(new Boolean(false)); addJavaClassHirarchyLinks(context, clazz, javaClass); addClassImplementsInterfaceLinks(context, clazz, javaClass); addJavaClassContainsJavaClassMethod(clazz, javaClass); count++; } final JavaInnerInterface javaInnerInterface = writer.addChildNode(utilJavaPackage, JavaInnerInterface.class, java.util.Map.Entry.class.getName()); Assert.assertNotNull(javaInnerInterface); writer.flush(); } }
From source file:com.jskaleel.xml.JSONObject.java
/** * Wrap an object, if necessary. If the object is null, return the NULL * object. If it is an array or collection, wrap it in a JSONArray. If it is * a map, wrap it in a JSONObject. If it is a standard property (Double, * String, et al) then it is already wrapped. Otherwise, if it comes from * one of the java packages, turn it into a string. And if it doesn't, try * to wrap it in a JSONObject. If the wrapping fails, then null is returned. * * @param object//from ww w . j a v a 2 s .c o m * The object to wrap * @return The wrapped value */ public static Object wrap(Object object) { try { if (object == null) { return NULL; } if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String) { return object; } if (object instanceof Collection) { return new JSONArray((Collection<Object>) object); } if (object.getClass().isArray()) { return new JSONArray(object); } if (object instanceof Map) { return new JSONObject((Map<String, Object>) object); } Package objectPackage = object.getClass().getPackage(); String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null) { return object.toString(); } return new JSONObject(object); } catch (Exception exception) { return null; } }
From source file:com.tower.service.test.SoafwTesterMojo.java
/** * //from ww w . ja va 2s . c o m * @param className * */ private void appendTest(String className) { /** * ?? ?public * ?MojoExecutionException?????? */ try { Map<String, Integer> methodCnt = new HashMap<String, Integer>(); boolean hasmethod = false; Map<String, String> methodDefs = new HashMap<String, String>(); Class cls = cl.loadClass(className);// Class[] inters = cls.getInterfaces(); int len = 0; if (inters == null || (len = inters.length) == 0) { return; } for (int i = 0; i < len; i++) { Class interCls = inters[i]; this.getLog().info("@interface: " + interCls.getName()); String name = project.getName(); Method[] methods = null; if (name.endsWith("-dao")) { methods = interCls.getDeclaredMethods(); } else { methods = interCls.getMethods(); } int mlen = 0; if (methods != null && (mlen = methods.length) > 0) { StringBuffer methodBuf = new StringBuffer(); for (int m = 0; m < mlen; m++) { Method method = methods[m]; int modf = method.getModifiers(); if (modf == 1025) {// ?? hasmethod = true; /** * ??????Test ???=??+Test * ??:basedPath+File.separator * +src+File.separator+test+File.separator * +pkg+definesArray[i]+Test+.java */ if (methodCnt.containsKey(method.getName())) { methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1); } else { methodCnt.put(method.getName(), 0); } int cnt = methodCnt.get(method.getName()); addMethod(methodDefs, methodBuf, method, cnt); } } } } Class tstCls = cl.loadClass(className + "Test");// Method[] methods = tstCls.getDeclaredMethods(); len = methods == null ? 0 : methods.length; this.getLog().info("" + tstCls.getSimpleName() + "?" + len); /** * ??public */ for (int m = 0; m < len; m++) { Method method = methods[m]; SoaFwTest test = method.getAnnotation(SoaFwTest.class); if (test == null) { this.getLog() .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest"); continue; } String id = test.id(); if (methodDefs.containsKey(id)) { methodDefs.remove(id); } } if ((len = methodDefs.size()) == 0) { return; } String[] methodImpls = new String[len]; methodDefs.keySet().toArray(methodImpls); // TODO ??? StringBuilder src = new StringBuilder(); String srcs = readTestSrc(className); int index = srcs.lastIndexOf("}"); // this.getLog().info(srcs); //this.getLog().info("lastIndexOf(}):" + index); String impls = srcs.substring(0, index - 1); src.append(impls); src.append("\n"); this.getLog().info("?: " + className + "Test"); StringBuilder appends = new StringBuilder(); this.getLog().info("?"); for (int i = 0; i < len; i++) { String methodId = methodImpls[i]; String method = methodDefs.get(methodId); appends.append(method); appends.append("\n"); } src.append(appends.toString()); src.append("}"); Package pkg = tstCls.getPackage(); String pkgName = pkg.getName(); String pkgPath = pkgName.replace(".", File.separator); String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java"; String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath; write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString()); } catch (Exception e) { this.getLog().error(e); } catch (Error er) { this.getLog().error(er); } }
From source file:com.kjt.service.common.SoafwTesterMojo.java
/** * /*from w ww . ja v a 2s .c om*/ * @param className */ private void appendTest(String className) { /** * ?? ?public * ?MojoExecutionException?????? */ try { Map<String, Integer> methodCnt = new HashMap<String, Integer>(); boolean hasmethod = false; Map<String, String> methodDefs = new HashMap<String, String>(); Class cls = cl.loadClass(className);// Class[] inters = cls.getInterfaces(); int len = 0; if (inters == null || (len = inters.length) == 0) { return; } for (int i = 0; i < len; i++) { Class interCls = inters[i]; this.getLog().info("@interface: " + interCls.getName()); String name = project.getName(); Method[] methods = null; if (name.endsWith("-dao")) { methods = interCls.getDeclaredMethods(); } else { methods = interCls.getMethods(); } int mlen = 0; if (methods != null && (mlen = methods.length) > 0) { StringBuffer methodBuf = new StringBuffer(); for (int m = 0; m < mlen; m++) { Method method = methods[m]; int modf = method.getModifiers(); if (modf == 1025) {// ?? hasmethod = true; /** * ??????Test ???=??+Test * ??:basedPath+File.separator * +src+File.separator+test+File.separator * +pkg+definesArray[i]+Test+.java */ if (methodCnt.containsKey(method.getName())) { methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1); } else { methodCnt.put(method.getName(), 0); } int cnt = methodCnt.get(method.getName()); addMethod(methodDefs, methodBuf, method, cnt); } } } } Class tstCls = cl.loadClass(className + "Test");// Method[] methods = tstCls.getDeclaredMethods(); len = methods == null ? 0 : methods.length; this.getLog().info("" + tstCls.getSimpleName() + "?" + len); /** * ??public */ for (int m = 0; m < len; m++) { Method method = methods[m]; SoaFwTest test = method.getAnnotation(SoaFwTest.class); if (test == null) { this.getLog() .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest"); continue; } String id = test.id(); if (methodDefs.containsKey(id)) { methodDefs.remove(id); } } if ((len = methodDefs.size()) == 0) { return; } String[] methodImpls = new String[len]; methodDefs.keySet().toArray(methodImpls); // TODO ??? this.getLog().info("???"); StringBuilder src = new StringBuilder(); String srcs = readTestSrc(className); int index = srcs.lastIndexOf("}"); this.getLog().info(srcs); this.getLog().info("lastIndexOf(}):" + index); String impls = srcs.substring(0, index - 1); src.append(impls); src.append("\n"); StringBuilder appends = new StringBuilder(); this.getLog().info("?"); for (int i = 0; i < len; i++) { String methodId = methodImpls[i]; String method = methodDefs.get(methodId); appends.append(method); appends.append("\n"); } src.append(appends.toString()); src.append("}"); Package pkg = tstCls.getPackage(); String pkgName = pkg.getName(); String pkgPath = pkgName.replace(".", File.separator); String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java"; String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath; write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString()); } catch (Exception e) { this.getLog().error(e); } catch (Error er) { this.getLog().error(er); } }