List of usage examples for java.lang ClassLoader getSystemClassLoader
@CallerSensitive public static ClassLoader getSystemClassLoader()
From source file:no.abmu.abmstatistikk.annualstatistic.util.KostaReportGeneratorH2.java
public KostaReportGeneratorH2() throws IOException, IllegalAccessException { Properties properties = new Properties(); String hibFile = System.getProperty(HIB_FILE_KEY, "conf/hibernate/hibernate.properties"); properties.load(//from ww w. j ava 2s. c om ClassLoader.getSystemClassLoader().getResourceAsStream("conf/hibernate/hibernate.properties")); // properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream(hibFile)); dialect = (String) properties.get(HIB_DIALECT_KEY); if (dialect == null) { throw new IllegalAccessException("The file " + hibFile + " had no key " + HIB_DIALECT_KEY); } System.getProperties().setProperty("applicationContextConfig", "conf/spring/application-context.xml"); System.getProperties().setProperty("config_locs_cp", "conf/spring/appContext-util.xml," + "conf/spring/appContext-configuration.xml," + "conf/spring/appContext-db-dataLayer.xml," + "conf/spring/appContext-service-orgRegister.xml," + "conf/spring/appContext-service-annualStatistic.xml," + "conf/spring/appContext-service-user.xml"); /* + "conf/spring/appContext-security.xml" */ System.getProperties().setProperty("config_locs", ""); ApplicationContextLoaderH2.getInstance().init(); ApplicationContext context = ApplicationContextLoaderH2.getInstance().getApplicationContext(); annualStatisticService = (AnnualStatisticService) ApplicationContextLoaderH2.getInstance() .getApplicationContext().getBean("AnnualStatisticService"); organisationUnitService = (OrganisationUnitService) ApplicationContextLoaderH2.getInstance() .getApplicationContext().getBean("organisationUnitService"); }
From source file:com.web.server.JarDeployer.java
/** * This method implements the jar deployer which configures the executor services. * Frequently monitors the deploy directory and configures the executor services map * once the jar is deployed in deploy directory and reconfigures if the jar is modified and * placed in the deploy directory.// w w w . jav a2 s .c o m */ public void run() { StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(scanDirectory.split(";")[0]); File[] files = file.listFiles(); CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".jar")) { String filePath = files[i].getAbsolutePath(); FileObject jarFile = null; try { jarFile = fsManager.resolveFile("jar:" + filePath); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar")); WebClassLoader customClassLoader = null; try { URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); try { customClassLoader = new WebClassLoader(urls); System.out.println(customClassLoader.geturlS()); new WebServer().addURL(new URL("file:/" + files[i].getAbsolutePath()), customClassLoader); CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList(); getUsersJars(new File(libDir), jarList); for (String jarFilePath : jarList) new WebServer().addURL(new URL("file:/" + jarFilePath.replace("\\", "/")), customClassLoader); System.out.println("deploy=" + customClassLoader.geturlS()); this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader); jarsDeployed.add(files[i].getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(urlClassLoaderMap); getChildren(jarFile, classList); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { Class executorServiceClass = customClassLoader.loadClass(classwithpackage); //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!executorServiceClass.isInterface()) { Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); System.out.println(remoteCall.servicename().trim()); try { //for(int count=0;count<500;count++){ RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject((Remote) executorServiceClass.newInstance(), 2004); registry.rebind(remoteCall.servicename().trim(), reminterface); //} } catch (Exception ex) { ex.printStackTrace(); } } } } } Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); //System.out.println("method="+executorServiceAnnot.servicename()); //System.out.println("method info="+executorServiceInfo); //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ClassLoaderUtil.closeClassLoader(customClassLoader); try { jarFile.close(); } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fsManager.closeFileSystem(jarFile.getFileSystem()); } } fsManager.close(); fsManager = new StandardFileSystemManager(); try { DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap, jarsDeployed); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); jarFileListener.setFm(fm); FileObject listendir = null; String[] dirsToScan = scanDirectory.split(";"); try { FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(3000); fm.start(); //fsManager.close(); }
From source file:com.app.server.JarDeployer.java
/** * This method implements the jar deployer which configures the executor services. * Frequently monitors the deploy directory and configures the executor services map * once the jar is deployed in deploy directory and reconfigures if the jar is modified and * placed in the deploy directory.// w ww . java 2 s.c om */ public void run() { StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(scanDirectory.split(";")[0]); File[] files = file.listFiles(); CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".jar")) { String filePath = files[i].getAbsolutePath(); FileObject jarFile = null; try { jarFile = fsManager.resolveFile("jar:" + filePath); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar")); WebClassLoader customClassLoader = null; try { URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); try { customClassLoader = new WebClassLoader(urls); log.info(customClassLoader.geturlS()); customClassLoader.addURL(new URL("file:/" + files[i].getAbsolutePath())); CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList(); getUsersJars(new File(libDir), jarList); for (String jarFilePath : jarList) customClassLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/"))); log.info("deploy=" + customClassLoader.geturlS()); this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader); jarsDeployed.add(files[i].getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info(urlClassLoaderMap); getChildren(jarFile, classList); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); log.info("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { Class executorServiceClass = customClassLoader.loadClass(classwithpackage); //log.info("executor class in ExecutorServicesConstruct"+executorServiceClass); //log.info(); if (!executorServiceClass.isInterface()) { Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); log.info(remoteCall.servicename().trim()); try { //for(int count=0;count<500;count++){ RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject((Remote) executorServiceClass.newInstance(), 2004); registry.rebind(remoteCall.servicename().trim(), reminterface); //} } catch (Exception ex) { ex.printStackTrace(); } } } } } Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); //log.info("method="+executorServiceAnnot.servicename()); //log.info("method info="+executorServiceInfo); //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ClassLoaderUtil.closeClassLoader(customClassLoader); try { jarFile.close(); } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fsManager.closeFileSystem(jarFile.getFileSystem()); } } fsManager.close(); fsManager = new StandardFileSystemManager(); try { DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap, jarsDeployed); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); jarFileListener.setFm(fm); FileObject listendir = null; String[] dirsToScan = scanDirectory.split(";"); try { FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(3000); fm.start(); //fsManager.close(); }
From source file:ffx.Main.java
/** * Print out help for the command line version of Force Field X. */// w w w .ja v a 2s .c o m private static void commandLineInterfaceHelp() { logger.info(" usage: ffxc [-D<property=value>] <command> [-options] <PDB|XYZ>"); logger.info("\n where commands include:\n"); ClassLoader classLoader = ClassLoader.getSystemClassLoader(); classLoader.getResource("List all scripts"); logger.info("\n For help on a spcific command: ffxc command -h\n"); System.exit(0); }
From source file:net.sourceforge.mavenhippo.ClassPathBeanFinder.java
private List<Class<? extends HippoBean>> getAnnotatedClasses(String beansAnnotatedClassesParam) throws IOException, SAXException, ParserConfigurationException, MojoExecutionException { List<Class<? extends HippoBean>> annotatedClasses; if (beansAnnotatedClassesParam.startsWith("classpath*:")) { ClasspathResourceScanner scanner; scanner = MetadataReaderClasspathResourceScanner.newInstance(projectClassloader); String[] split = StringUtils.split(beansAnnotatedClassesParam, ", \t\r\n"); List<String> packages = new ArrayList<String>(); packages.addAll(Arrays.asList(split)); packages.add("classpath*:org/hippoecm/hst/content/beans/standard/**/*.class"); Thread.currentThread().setContextClassLoader(projectClassloader); annotatedClasses = ObjectConverterUtils.getAnnotatedClasses(scanner, projectClassloader, packages.toArray(new String[0])); } else {//from w w w. ja v a 2 s . com URL xmlConfURL = ClassLoader.getSystemClassLoader().getResource(beansAnnotatedClassesParam); if (xmlConfURL == null) { throw new MojoExecutionException(BEANS_ANNOTATED_CLASSES_CONF_PARAM_ERROR_MSG); } annotatedClasses = ObjectConverterUtils.getAnnotatedClasses(xmlConfURL); } return annotatedClasses; }
From source file:ch.jamiete.hilda.plugins.PluginManager.java
private boolean loadPlugin(final PluginData data) { if (this.isLoaded(data)) { return true; }/*w w w. j a v a2s.c o m*/ try { final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); final Class<URLClassLoader> sysclass = URLClassLoader.class; final Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class }); method.setAccessible(true); method.invoke(sysloader, new Object[] { data.pluginFile.toURI().toURL() }); final Class<?> mainClass = Class.forName(data.mainClass); if (mainClass != null) { if (!HildaPlugin.class.isAssignableFrom(mainClass)) { Hilda.getLogger().severe("Could not load plugin " + data.getName() + " because its main class did not implement HildaPlugin!"); return false; } final HildaPlugin newPlugin = (HildaPlugin) mainClass.getConstructor(Hilda.class) .newInstance(this.hilda); final Field pluginDataField = HildaPlugin.class.getDeclaredField("pluginData"); pluginDataField.setAccessible(true); pluginDataField.set(newPlugin, data); this.plugins.add(newPlugin); try { newPlugin.onLoad(); } catch (final Exception e) { Hilda.getLogger().log(Level.WARNING, "Encountered exception when calling load method of plugin " + data.name + ". It may not have properly loaded and may cause errors.", e); } Hilda.getLogger().info("Loaded plugin " + data.name); return true; } } catch (final Exception ex) { Hilda.getLogger().log(Level.WARNING, "Encountered exception when loading plugin " + data.name, ex); } return false; }
From source file:com.flexoodb.FlexManager.java
public FlexManager(String conf) throws Exception { XMLConfiguration config = new XMLConfiguration(); config.setDelimiterParsingDisabled(true); String dbimplementation = null; if (conf == null) { byte[] b = FlexUtils .getBytesFromInputStream(this.getClass().getClassLoader().getResourceAsStream("flexoodb.xml")); if (b != null) { config.load(new ByteArrayInputStream(b)); dbimplementation = config.getString("flexoodb[@engine]"); }//w w w . j a va2 s. c o m } else { config.load(conf); dbimplementation = config.getString("flexoodb[@engine]"); } // use the default impl if (dbimplementation == null) { dbimplementation = "com.flexoodb.engines.FlexJAXBDBDataEngine"; } //_flexdb = (FlexDataInterface) Class.forName(dbimplementation).newInstance(); _flexdb = (FlexDataInterface) ClassLoader.getSystemClassLoader().loadClass((dbimplementation)) .newInstance(); _flexdb.initialize(config); }
From source file:org.apache.drill.exec.expr.fn.registry.LocalFunctionRegistry.java
/** * Validates all functions, present in jars. * Will throw {@link FunctionValidationException} if: * <ol>/*from w w w .j a v a 2s . c o m*/ * <li>Jar with the same name has been already registered.</li> * <li>Conflicting function with the similar signature is found.</li> * <li>Aggregating function is not deterministic.</li> *</ol> * @param jarName jar name to be validated * @param scanResult scan of all classes present in jar * @return list of validated function signatures */ public List<String> validate(String jarName, ScanResult scanResult) { List<String> functions = Lists.newArrayList(); FunctionConverter converter = new FunctionConverter(); List<AnnotatedClassDescriptor> providerClasses = scanResult.getAnnotatedClasses(); if (registryHolder.containsJar(jarName)) { throw new JarValidationException( String.format("Jar with %s name has been already registered", jarName)); } final ListMultimap<String, String> allFuncWithSignatures = registryHolder.getAllFunctionsWithSignatures(); for (AnnotatedClassDescriptor func : providerClasses) { DrillFuncHolder holder = converter.getHolder(func, ClassLoader.getSystemClassLoader()); if (holder != null) { String functionInput = holder.getInputParameters(); String[] names = holder.getRegisteredNames(); for (String name : names) { String functionName = name.toLowerCase(); String functionSignature = String.format(functionSignaturePattern, functionName, functionInput); if (allFuncWithSignatures.get(functionName).contains(functionSignature)) { throw new FunctionValidationException(String.format("Found duplicated function in %s: %s", registryHolder.getJarNameByFunctionSignature(functionName, functionSignature), functionSignature)); } else if (holder.isAggregating() && !holder.isDeterministic()) { throw new FunctionValidationException(String .format("Aggregate functions must be deterministic: %s", func.getClassName())); } else { functions.add(functionSignature); allFuncWithSignatures.put(functionName, functionSignature); } } } else { logger.warn("Unable to initialize function for class {}", func.getClassName()); } } return functions; }
From source file:org.tros.torgo.Main.java
public static void loadIcon(Window frame) { try {/*from ww w . j a va2s. c o m*/ java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader() .getResources(IMAGE_ICON_CLASS_PATH); ImageIcon ico = new ImageIcon(resources.nextElement()); frame.setIconImage(ico.getImage()); } catch (IOException ex) { org.tros.utils.logging.Logging.getLogFactory().getLogger(Main.class).warn(null, ex); } }
From source file:com.mapd.parser.server.CalciteDirect.java
public CalciteReturn process(String user, String passwd, String catalog, String sqlText, boolean legacySyntax, boolean isExplain) { MAPDLOGGER.debug(user + " " + " " + catalog + " '" + sqlText + "' " + legacySyntax + "' " + isExplain); long timer = System.currentTimeMillis(); callCount++;//from w w w. j a v a 2s.com MapDParser parser; try { parser = (MapDParser) parserPool.borrowObject(); } catch (Exception ex) { String msg = "Could not get Parse Item from pool: " + ex.getMessage(); MAPDLOGGER.error(msg); return new CalciteReturn("ERROR-- " + msg, System.currentTimeMillis() - timer, true); } MapDUser mapDUser = new MapDUser(user, passwd, catalog, mapDPort); //TODO MAT must fix so catalog can be scanned MAPDLOGGER.debug("process was called User: " + user + " Catalog: " + catalog + " sql: " + sqlText); // remove last charcter if it is a ; if (sqlText.charAt(sqlText.length() - 1) == ';') { sqlText = sqlText.substring(0, sqlText.length() - 1); } String relAlgebra; try { if (Thread.currentThread().getContextClassLoader() == null) { ClassLoader cl = ClassLoader.getSystemClassLoader(); Thread.currentThread().setContextClassLoader(cl); } relAlgebra = parser.getRelAlgebra(sqlText, legacySyntax, mapDUser, isExplain); MAPDLOGGER.debug("After get relalgebra"); } catch (SqlParseException ex) { String msg = "Parse failed: " + ex.getPos() + ", " + ex.getMessage(); MAPDLOGGER.error(msg); return new CalciteReturn("ERROR-- " + msg, System.currentTimeMillis() - timer, true); } catch (CalciteContextException ex) { String msg = "Validate failed: " + ex.getMessage(); MAPDLOGGER.error(msg); return new CalciteReturn("ERROR-- " + msg, System.currentTimeMillis() - timer, true); } catch (Exception ex) { String msg = "Exception occurred: " + ex.getMessage(); ex.printStackTrace(); //MAPDLOGGER.error(msg); return new CalciteReturn("ERROR-- " + msg, System.currentTimeMillis() - timer, true); } finally { try { // put parser object back in pool for others to use MAPDLOGGER.debug("Returning object to pool"); parserPool.returnObject(parser); } catch (Exception ex) { String msg = "Could not return parse object: " + ex.getMessage(); MAPDLOGGER.error(msg); return new CalciteReturn("ERROR-- " + msg, System.currentTimeMillis() - timer, true); } } MAPDLOGGER.debug("About to return good result"); return new CalciteReturn(relAlgebra, System.currentTimeMillis() - timer, false); }