List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:com.googlecode.jsonschema2pojo.integration.config.CustomAnnotatorIT.java
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void customAnnotatorIsAbleToAddCustomAnnotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "none", // turn off core annotations "customAnnotator", DeprecatingAnnotator.class.getName())); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue())); }
From source file:org.jsonschema2pojo.integration.PropertiesIT.java
@Test @SuppressWarnings("rawtypes") public void wordDelimitersCausesCamelCase() throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile( "/schema/properties/propertiesWithWordDelimiters.json", "com.example", config("usePrimitives", true, "propertyWordDelimiters", "_ -")); Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit"); Object instance = generatedType.newInstance(); new PropertyDescriptor("propertyWithUnderscores", generatedType).getWriteMethod().invoke(instance, "a_b_c"); new PropertyDescriptor("propertyWithHyphens", generatedType).getWriteMethod().invoke(instance, "a-b-c"); new PropertyDescriptor("propertyWithMixedDelimiters", generatedType).getWriteMethod().invoke(instance, "a b_c-d"); JsonNode jsonified = mapper.valueToTree(instance); assertThat(jsonified.has("property_with_underscores"), is(true)); assertThat(jsonified.has("property-with-hyphens"), is(true)); assertThat(jsonified.has("property_with mixed-delimiters"), is(true)); }
From source file:hudson.jbpm.model.TaskInstanceWrapper.java
public Object getForm() { TaskInstance ti = getTaskInstance(); try {/* ww w . j a v a2s . c o m*/ ClassLoader processClassLoader = ProcessClassLoaderCache.INSTANCE .getClassLoader(ti.getProcessInstance().getProcessDefinition()); String formClass = (String) ti.getVariableLocally("form"); if (formClass == null) { return new Form(ti); } else { Class<?> cl = processClassLoader.loadClass(formClass); return cl.getConstructor(TaskInstance.class).newInstance(ti); } } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:generate.MapGenerateAction.java
@Override public String execute() { String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles"; try {/*from ww w .j a v a 2 s .c om*/ File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName()); FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate); } catch (Throwable t) { System.out.println("E1: " + t.getMessage()); return ERROR; } try { List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile()); StringBuilder text = new StringBuilder(); for (String s : temp_text) { text.append(s); } concept_map.setInput_text(text.toString()); } catch (IOException e) { //e.printStackTrace(); System.out.println("E2: " + e.getMessage()); return ERROR; } String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0]; temp_filename = temp_filename.trim(); try { String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar " + file_path + " " + temp_filename; System.out.println(temp); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; System.out.println(args[0]); System.out.println(args[1]); try { mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException e) { System.out.println("This is the exception: " + e.getTargetException().toString()); } } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E3: " + e.getMessage()); return ERROR; } try { String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar " + file_path + " " + temp_filename; System.out.println(temp2); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E4: " + e.getMessage()); return ERROR; } String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/" + temp_filename + "_OllieOutput.txt\""; String[] finalCommand; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; System.out.println("CMD: " + cmd); try { //ProcessBuilder builder = new ProcessBuilder(finalCommand); //builder.redirectErrorStream(true); //Process process = builder.start(); Process process = Runtime.getRuntime().exec(finalCommand); int exitVal = process.waitFor(); System.out.println("Process exitValue2: " + exitVal); } catch (Throwable t) { System.out.println("E5: " + t.getMessage()); return ERROR; } cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py"; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; try { //Process process = Runtime.getRuntime().exec(finalCommand); ProcessBuilder builder = new ProcessBuilder(finalCommand); // builder.redirectErrorStream(true); Process process = builder.start(); int exitVal = process.waitFor(); System.out.println("Process exitValue3: " + exitVal); } catch (Throwable t) { System.out.println("E6: " + t.getMessage()); return ERROR; } try { List<String> temp_text_1 = FileUtils .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json")); StringBuilder text_1 = new StringBuilder(); for (String s : temp_text_1) { text_1.append(s); } concept_map.setOutput_text(text_1.toString()); } catch (IOException e) { System.out.println("E7: " + e.getMessage()); return ERROR; } Random rand = new Random(); int unique_id = rand.nextInt(99999999); System.out.println("Going In DB"); try { MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); BasicDBObject document = new BasicDBObject(); document.append("InputText", concept_map.getInput_text()); document.append("OutputText", concept_map.getOutput_text()); document.append("ChapterName", concept_map.getChapter_name()); document.append("ChapterNumber", concept_map.getChapter_number()); document.append("SectionName", concept_map.getSection_name()); document.append("SectionNumber", concept_map.getSection_number()); document.append("UniqueID", Integer.toString(unique_id)); collection.insert(document); //collection.save(document); } catch (MongoException e) { System.out.println("E8: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("E9"); return ERROR; } System.out.println("Out DB"); return SUCCESS; }
From source file:ch.entwine.weblounge.common.impl.site.ModuleImpl.java
/** * Initializes this module from an XML node that was generated using * {@link #toXml()}./*from w ww.j av a 2s . c o m*/ * * @param config * the module node * @param xpathProcessor * xpath processor to use * @throws IllegalStateException * if the module cannot be parsed * @see #toXml() */ @SuppressWarnings("unchecked") public static Module fromXml(Node config, XPath xpathProcessor) throws IllegalStateException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // identifier String identifier = XPathHelper.valueOf(config, "@id", xpathProcessor); if (identifier == null) throw new IllegalStateException("Unable to create module without identifier"); // class Module module = null; String className = XPathHelper.valueOf(config, "m:class", xpathProcessor); if (className != null) { try { Class<? extends Module> c = (Class<? extends Module>) classLoader.loadClass(className); module = c.newInstance(); module.setIdentifier(identifier); } catch (ClassNotFoundException e) { throw new IllegalStateException( "Implementation " + className + " for module '" + identifier + "' not found", e); } catch (InstantiationException e) { throw new IllegalStateException( "Error instantiating impelementation " + className + " for module '" + identifier + "'", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Access violation instantiating implementation " + className + " for module '" + identifier + "'", e); } catch (Throwable t) { throw new IllegalStateException( "Error loading implementation " + className + " for module '" + identifier + "'", t); } } else { module = new ModuleImpl(); module.setIdentifier(identifier); } // Check if module is enabled Boolean enabled = Boolean.valueOf(XPathHelper.valueOf(config, "m:enable", xpathProcessor)); module.setEnabled(enabled); // name String name = XPathHelper.valueOf(config, "m:name", xpathProcessor); module.setName(name); // pagelets NodeList pageletNodes = XPathHelper.selectList(config, "m:pagelets/m:pagelet", xpathProcessor); for (int i = 0; i < pageletNodes.getLength(); i++) { PageletRenderer pagelet = PageletRendererImpl.fromXml(pageletNodes.item(i), xpathProcessor); module.addRenderer(pagelet); } // actions NodeList actionNodes = XPathHelper.selectList(config, "m:actions/m:action", xpathProcessor); for (int i = 0; i < actionNodes.getLength(); i++) { module.addAction(ActionSupport.fromXml(actionNodes.item(i), xpathProcessor)); } // image styles NodeList imagestyleNodes = XPathHelper.selectList(config, "m:imagestyles/m:imagestyle", xpathProcessor); for (int i = 0; i < imagestyleNodes.getLength(); i++) { module.addImageStyle(ImageStyleImpl.fromXml(imagestyleNodes.item(i), xpathProcessor)); } // jobs NodeList jobNodes = XPathHelper.selectList(config, "m:jobs/m:job", xpathProcessor); for (int i = 0; i < jobNodes.getLength(); i++) { module.addJob(QuartzJob.fromXml(jobNodes.item(i), xpathProcessor)); } // options Node optionsNode = XPathHelper.select(config, "m:options", xpathProcessor); OptionsHelper.fromXml(optionsNode, module, xpathProcessor); return module; }
From source file:cz.lbenda.common.ClassLoaderHelper.java
@SuppressWarnings("unchecked") public static List<String> instancesOfClass(Class clazz, List<String> libs, boolean abstractClass, boolean interf) { List<String> classNames = new ArrayList<>(); ClassLoader clr = createClassLoader(libs, false); List<String> result = new ArrayList<>(); libs.forEach(lib -> {/*from w ww. ja v a 2s .c o m*/ try (ZipFile file = new ZipFile(lib)) { file.stream().forEach(entry -> { if (entry.getName().equals("META-INF/services/" + clazz.getName())) { try { String string = IOUtils.toString(file.getInputStream(entry)); String[] lines = string.split("\n"); for (String line : lines) { result.add(line.trim()); } } catch (IOException e) { throw new RuntimeException(e); } } else if (entry.getName().endsWith(".class")) { String className = entry.getName().substring(0, entry.getName().length() - 6).replace("/", "."); classNames.add(className); } }); } catch (IOException e) { throw new RuntimeException(e); } }); classNames.forEach(cc -> { try { Class cla = clr.loadClass(cc); if ((interf || !cla.isInterface()) && (abstractClass || !Modifier.isAbstract(cla.getModifiers())) && clazz.isAssignableFrom(cla)) { if (!result.contains(cc)) { result.add(cc); } } } catch (ClassNotFoundException | NoClassDefFoundError e) { /* It's common to try to create class which haven't class which need*/ } }); return result; }
From source file:com.ocpsoft.pretty.faces.el.resolver.CDIBeanNameResolver.java
public boolean init(ServletContext servletContext, ClassLoader classLoader) { // catch reflection exceptions try {// w w w .ja v a2 s.c om // get BeanManager class and getBeans() method Class<?> beanManagerClass = classLoader.loadClass(BEAN_MANAGER_CLASS); getBeansMethod = beanManagerClass.getMethod(GET_BEANS_METHOD, Type.class, Annotation[].class); // get Bean class and getName() method Class<?> beanClass = classLoader.loadClass(BEAN_CLASS); getNameMethod = beanClass.getMethod(GET_NAME_METHOD); } catch (ClassNotFoundException e) { // happens in environments without CDI if (log.isDebugEnabled()) { log.debug("BeanManager or Bean class not found. CDI resolver has been disabled."); } return false; } catch (NoSuchMethodException e) { // should never happen, because methods are defined in the CDI spec log.warn("Cannot find BeanManager.getBeans() or Bean.getName() method", e); return false; } catch (SecurityException e) { log.warn("Unable to init resolver due to security restrictions", e); return false; } // try to find in ServletContext first beanManager = getBeanManagerFromServletContext(servletContext); // try standard JNDI name if (beanManager == null) { beanManager = getBeanManagerFromJNDI(BEAN_MANAGER_JNDI); } // try special Tomcat JNDI name if (beanManager == null) { beanManager = getBeanManagerFromJNDI(BEAN_MANAGER_JNDI_TOMCAT); } // No BeanManager? Abort here if (beanManager == null) { // log this on debug level because the user may not use CDI at all if (log.isDebugEnabled()) { log.debug("BeanManager cannot be found! CDI resolver gets disabled!"); } return false; } if (log.isDebugEnabled()) { log.debug("CDI environment detected. Enabling bean name resolving via BeanManager."); } return true; }
From source file:fr.inria.atlanmod.neoemf.graph.blueprints.datastore.BlueprintsPersistenceBackendFactory.java
@Override public BlueprintsPersistenceBackend createPersistentBackend(File file, Map<?, ?> options) throws InvalidDataStoreException { BlueprintsPersistenceBackend graphDB = null; PropertiesConfiguration neoConfig = null; PropertiesConfiguration configuration = null; try {// w w w . j a v a 2 s. c o m // Try to load previous configurations Path path = Paths.get(file.getAbsolutePath()).resolve(CONFIG_FILE); try { configuration = new PropertiesConfiguration(path.toFile()); } catch (ConfigurationException e) { throw new InvalidDataStoreException(e); } // Initialize value if the config file has just been created if (!configuration.containsKey(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)) { configuration.setProperty(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE, BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE_DEFAULT); } else if (options.containsKey(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)) { // The file already existed, check that the issued options // are not conflictive String savedGraphType = configuration .getString(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE); String issuedGraphType = options.get(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE) .toString(); if (!savedGraphType.equals(issuedGraphType)) { NeoLogger.log(NeoLogger.SEVERITY_ERROR, "Unable to create graph as type " + issuedGraphType + ", expected graph type was " + savedGraphType + ")"); throw new InvalidDataStoreException("Unable to create graph as type " + issuedGraphType + ", expected graph type was " + savedGraphType + ")"); } } // Copy the options to the configuration for (Entry<?, ?> e : options.entrySet()) { configuration.setProperty(e.getKey().toString(), e.getValue().toString()); } // Check we have a valid graph type, it is needed to get the // graph name String graphType = configuration.getString(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE); if (graphType == null) { throw new InvalidDataStoreException("Graph type is undefined for " + file.getAbsolutePath()); } String[] segments = graphType.split("\\."); if (segments.length >= 2) { String graphName = segments[segments.length - 2]; String upperCaseGraphName = Character.toUpperCase(graphName.charAt(0)) + graphName.substring(1); String configClassQualifiedName = MessageFormat.format( "fr.inria.atlanmod.neoemf.graph.blueprints.{0}.config.Blueprints{1}Config", graphName, upperCaseGraphName); try { ClassLoader classLoader = BlueprintsPersistenceBackendFactory.class.getClassLoader(); Class<?> configClass = classLoader.loadClass(configClassQualifiedName); Field configClassInstanceField = configClass.getField("eINSTANCE"); AbstractBlueprintsConfig configClassInstance = (AbstractBlueprintsConfig) configClassInstanceField .get(configClass); Method configMethod = configClass.getMethod("putDefaultConfiguration", Configuration.class, File.class); configMethod.invoke(configClassInstance, configuration, file); Method setGlobalSettingsMethod = configClass.getMethod("setGlobalSettings"); setGlobalSettingsMethod.invoke(configClassInstance); } catch (ClassNotFoundException e1) { NeoLogger.log(NeoLogger.SEVERITY_WARNING, "Unable to find the configuration class " + configClassQualifiedName); e1.printStackTrace(); } catch (NoSuchFieldException e2) { NeoLogger.log(NeoLogger.SEVERITY_WARNING, MessageFormat.format( "Unable to find the static field eINSTANCE in class Blueprints{0}Config", upperCaseGraphName)); e2.printStackTrace(); } catch (NoSuchMethodException e3) { NeoLogger.log(NeoLogger.SEVERITY_ERROR, MessageFormat.format( "Unable to find configuration methods in class Blueprints{0}Config", upperCaseGraphName)); e3.printStackTrace(); } catch (InvocationTargetException e4) { NeoLogger.log(NeoLogger.SEVERITY_ERROR, MessageFormat.format( "An error occured during the exection of a configuration method", upperCaseGraphName)); e4.printStackTrace(); } catch (IllegalAccessException e5) { NeoLogger.log(NeoLogger.SEVERITY_ERROR, MessageFormat.format( "An error occured during the exection of a configuration method", upperCaseGraphName)); e5.printStackTrace(); } } else { NeoLogger.log(NeoLogger.SEVERITY_WARNING, "Unable to compute graph type name from " + graphType); } Graph baseGraph = null; try { baseGraph = GraphFactory.open(configuration); } catch (RuntimeException e) { throw new InvalidDataStoreException(e); } if (baseGraph instanceof KeyIndexableGraph) { graphDB = new BlueprintsPersistenceBackend((KeyIndexableGraph) baseGraph); } else { NeoLogger.log(NeoLogger.SEVERITY_ERROR, "Graph type " + file.getAbsolutePath() + " does not support Key Indices"); throw new InvalidDataStoreException( "Graph type " + file.getAbsolutePath() + " does not support Key Indices"); } // Save the neoconfig file Path neoConfigPath = Paths.get(file.getAbsolutePath()).resolve(NEO_CONFIG_FILE); try { neoConfig = new PropertiesConfiguration(neoConfigPath.toFile()); } catch (ConfigurationException e) { throw new InvalidDataStoreException(e); } if (!neoConfig.containsKey(BACKEND_PROPERTY)) { neoConfig.setProperty(BACKEND_PROPERTY, BLUEPRINTS_BACKEND); } } finally { if (configuration != null) { try { configuration.save(); } catch (ConfigurationException e) { // Unable to save configuration, supposedly it's a minor error, // so we log it without rising an exception NeoLogger.log(NeoLogger.SEVERITY_ERROR, e); } } if (neoConfig != null) { try { neoConfig.save(); } catch (ConfigurationException e) { NeoLogger.log(NeoLogger.SEVERITY_ERROR, e); } } } return graphDB; }
From source file:net.contextfw.web.application.internal.classloading.ReloadingClassLoaderTest.java
@Test public void Load_Classes() throws ClassNotFoundException { conf = conf.add(//from w ww .ja va2 s . co m RELOADABLE_CLASSES.includedPackage("net.contextfw.web.application.internal.classloading", false)) .add(RELOADABLE_CLASSES.excludedClass(NonReloadable.class)); InternalDevelopmentTools tools = new DevelopmentToolsImpl(conf); final MutableBoolean classesReloaded = new MutableBoolean(false); final MutableBoolean resourcesReloaded = new MutableBoolean(false); tools.addListener(new DevelopmentModeListener() { @Override public void resourcesReloaded() { resourcesReloaded.setValue(true); } @Override public void classesReloaded(ClassLoader classLoader) { classesReloaded.setValue(true); } }); ClassLoader classLoader = tools.reloadClasses(); tools.reloadResources(); assertTrue(classesReloaded.booleanValue()); assertTrue(resourcesReloaded.booleanValue()); Class<?> reloadable = classLoader .loadClass("net.contextfw.web.application.internal.classloading.Reloadable"); Class<?> nonReloadable = classLoader .loadClass("net.contextfw.web.application.internal.classloading.NonReloadable"); assertEquals(NonReloadable.class, nonReloadable); assertNotSame(Reloadable.class, reloadable); assertEquals(String.class, classLoader.loadClass("java.lang.String")); }
From source file:com.helpinput.spring.refresher.SessiontRefresher.java
@SuppressWarnings("unchecked") ManagedList<Object> getManageList(DefaultListableBeanFactory dlbf, PropertyValue oldPropertyValue) { Set<String> oldClasses = null; if (oldPropertyValue != null) { Object value = oldPropertyValue.getValue(); if (value != null && value instanceof ManagedList) { ManagedList<Object> real = (ManagedList<Object>) value; oldClasses = new HashSet<>(real.size() >>> 1); ClassLoader parentClassLoader = ClassUtils.getDefaultClassLoader(); for (Object object : real) { TypedStringValue typedStringValue = (TypedStringValue) object; String className = typedStringValue.getValue(); try { parentClassLoader.loadClass(className); oldClasses.add(className); } catch (ClassNotFoundException e) { }/*from w ww. j a v a2 s. c om*/ } } } int oldClassSize = (Utils.hasLength(oldClasses) ? oldClasses.size() : 0); Map<String, Object> beans = dlbf.getBeansWithAnnotation(Entity.class); HashSet<String> totalClasses = new HashSet<>(beans.size() + oldClassSize); if (oldClassSize > 0) { totalClasses.addAll(oldClasses); } for (Object entity : beans.values()) { String clzName = entity.getClass().getName(); if (!totalClasses.contains(clzName)) { totalClasses.add(clzName); } } ManagedList<Object> list = new ManagedList<>(totalClasses.size()); for (String clzName : totalClasses) { TypedStringValue typedStringValue = new TypedStringValue(clzName); list.add(typedStringValue); } return list; }