List of usage examples for java.lang ClassLoader getSystemClassLoader
@CallerSensitive public static ClassLoader getSystemClassLoader()
From source file:architecture.common.util.L10NUtils.java
/** * key ? ? ?? ?? ?? Localizer ? .//from www. ja v a 2s. c om * * @param key * @param locale * @param classloader * @return * @throws MissingResourceException */ public static Localizer getLocalizer(String key, Locale locale, ClassLoader classloader) throws MissingResourceException { Locale localeToUse = locale; String keyToUse = key; ClassLoader cl = classloader; if (keyToUse == null) throw new NullPointerException("No key name provided"); if (localeToUse == null) localeToUse = Locale.getDefault(); if (cl != null) { Localizer localizer = L10NUtils.SINGLETON.getLocalizerBundle(key, locale, cl); if (localizer != null) return localizer; } cl = L10NUtils.class.getClassLoader(); if (cl == null) cl = ClassLoader.getSystemClassLoader(); if (cl == null) { if (log.isDebugEnabled()) log.debug("no system classs loader"); cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { if (log.isDebugEnabled()) log.debug("no context class loader"); } else if (log.isDebugEnabled()) log.debug("Using context class loader"); } Localizer localizer = L10NUtils.SINGLETON.getLocalizerBundle(key, locale, cl); if (localizer == null) { ClassLoader clToUse = Thread.currentThread().getContextClassLoader(); localizer = L10NUtils.SINGLETON.getLocalizerBundle(key, locale, clToUse); if (localizer == null) throw new MissingResourceException((new StringBuilder()).append("Can't locate bundle for class '") .append(key).append("'").toString(), key, ""); } return localizer; }
From source file:org.apache.tez.client.TestTezClientUtils.java
/** * *///from w w w. j a v a2s . c om @Test(timeout = 10000) public void validateSetTezJarLocalResourcesDefinedExistingDirectory() throws Exception { URL[] cp = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs(); StringBuffer buffer = new StringBuffer(); for (URL url : cp) { buffer.append(url.toExternalForm()); buffer.append(","); } TezConfiguration conf = new TezConfiguration(); conf.set(TezConfiguration.TEZ_LIB_URIS, buffer.toString()); Credentials credentials = new Credentials(); Map<String, LocalResource> localizedMap = new HashMap<String, LocalResource>(); boolean usingArchive = TezClientUtils.setupTezJarsLocalResources(conf, credentials, localizedMap); Assert.assertFalse(usingArchive); Set<String> resourceNames = localizedMap.keySet(); for (URL url : cp) { File file = FileUtils.toFile(url); if (file.isDirectory()) { String[] firList = file.list(); for (String fileNme : firList) { File innerFile = new File(file, fileNme); if (!innerFile.isDirectory()) { assertTrue(resourceNames.contains(innerFile.getName())); } // not supporting deep hierarchies } } else { assertTrue(resourceNames.contains(file.getName())); } } }
From source file:org.kuali.ext.mm.web.listener.StandaloneInitializeListener.java
/** * ServletContextListener interface implementation that schedules the start of the lifecycle */// ww w . java2s.co m public void contextInitialized(ServletContextEvent sce) { long startInit = System.currentTimeMillis(); try { Properties p = new Properties(); p.load(getClass().getClassLoader().getResourceAsStream(DEFAULT_LOG4J_CONFIG)); PropertyConfigurator.configure(p); } catch (Exception e) { throw new WorkflowRuntimeException(e); } LOG.info("Initializing Organization Of Interest..."); sce.getServletContext().setAttribute("Constants", new JSTLConstants(KEWConstants.class)); List<String> configLocations = new ArrayList<String>(); String additionalConfigLocations = System.getProperty(KEWConstants.ADDITIONAL_CONFIG_LOCATIONS_PARAM); if (!StringUtils.isBlank(additionalConfigLocations)) { String[] additionalConfigLocationArray = additionalConfigLocations.split(","); for (String additionalConfigLocation : additionalConfigLocationArray) { configLocations.add(additionalConfigLocation); } } String bootstrapSpringBeans = DEFAULT_SPRING_BEANS; if (!StringUtils.isBlank(System.getProperty(KEWConstants.BOOTSTRAP_SPRING_FILE))) { bootstrapSpringBeans = System.getProperty(KEWConstants.BOOTSTRAP_SPRING_FILE); } else if (!StringUtils .isBlank(sce.getServletContext().getInitParameter(KEWConstants.BOOTSTRAP_SPRING_FILE))) { String bootstrapSpringInitParam = sce.getServletContext() .getInitParameter(KEWConstants.BOOTSTRAP_SPRING_FILE); // if the value comes through as ${bootstrap.spring.beans}, we ignore it if (!DEFAULT_SPRING_BEANS_REPLACEMENT_VALUE.equals(bootstrapSpringInitParam)) { bootstrapSpringBeans = bootstrapSpringInitParam; LOG.info("Found bootstrap Spring Beans file defined in servlet context: " + bootstrapSpringBeans); } } try { String basePath = findBasePath(sce.getServletContext()); Properties baseProps = new Properties(); baseProps.putAll(getContextParameters(sce.getServletContext())); baseProps.putAll(System.getProperties()); baseProps.setProperty(RICE_BASE, basePath); // HACK: need to determine best way to do this... // if the additional config locations property is empty then we need // to explicitly set it so that if we use it in a root config // a value (an empty value) can be found, and the config parser // won't blow up because "additional.config.locations" property // cannot be resolved // An alternative to doing this at the application/module level would // be to push this functionality down into the Rice ConfigFactoryBean // e.g., by writing a simple ResourceFactoryBean that would conditionally // expose the resource, and then plugging the Resource into the ConfigFactoryBean // However, currently, the ConfigFactoryBean operates on String locations, not // Resources. Spring can coerce string <value>s into Resources, but not vice-versa if (StringUtils.isEmpty(additionalConfigLocations)) { baseProps.setProperty(KEWConstants.ADDITIONAL_CONFIG_LOCATIONS_PARAM, ""); } SimpleConfig config = new SimpleConfig(baseProps); config.parseConfig(); ConfigContext.init(config); URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs(); StringBuffer classpath = new StringBuffer("Classpath is:\n"); for (URL clp : urls) { classpath.append(clp.getFile() + ";"); } LOG.info(classpath.toString()); context = new ClassPathXmlApplicationContext(bootstrapSpringBeans); context.start(); if (shouldExecuteMessageFetcher()) { // execute the MessageFetcher to grab any messages that were being processed // when the system shut down originally MessageFetcher messageFetcher = new MessageFetcher((Integer) null); KSBServiceLocator.getThreadPool().execute(messageFetcher); } } catch (Exception e) { LOG.fatal("Organization of Interest startup failed!", e); throw new RuntimeException("Startup failed. Exiting.", e); } long endInit = System.currentTimeMillis(); LOG.info("...Organization of Interest successfully initialized, startup took " + (endInit - startInit) + " ms."); }
From source file:org.apache.ranger.tagsync.process.TagSyncConfig.java
public static String getResourceFileName(String path) { String ret = null;/*w w w .j ava2 s .c om*/ if (StringUtils.isNotBlank(path)) { File f = new File(path); if (f.exists() && f.isFile() && f.canRead()) { ret = path; } else { URL fileURL = TagSyncConfig.class.getResource(path); if (fileURL == null) { if (!path.startsWith("/")) { fileURL = TagSyncConfig.class.getResource("/" + path); } } if (fileURL == null) { fileURL = ClassLoader.getSystemClassLoader().getResource(path); if (fileURL == null) { if (!path.startsWith("/")) { fileURL = ClassLoader.getSystemClassLoader().getResource("/" + path); } } } if (fileURL != null) { try { ret = fileURL.getFile(); } catch (Exception exception) { LOG.error(path + " is not a file", exception); } } else { LOG.warn("URL not found for " + path + " or no privilege for reading file " + path); } } } return ret; }
From source file:org.ploin.pmf.impl.PropertiesLoader.java
/** * //w ww . ja va 2s . co m * @param name * @return */ private Properties loadProperties(String name) throws MailFactoryException { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) loader = ClassLoader.getSystemClassLoader(); InputStream in = loader.getResourceAsStream(name); Properties result = new Properties(); result.load(in); return result; } catch (Exception e) { throw new MailFactoryException("Error trying to load properties " + name); } }
From source file:json.JsonUI.java
public void enviandoEmail() { Properties login = new Properties(); String properties = "json/login.properties"; try {/* w w w .ja v a2 s .c o m*/ InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(properties); login.load(stream); } catch (IOException ex) { System.out.println("Erro: " + ex.getMessage()); } String username = login.getProperty("hotmail.username"); String password = login.getProperty("hotmail.password"); try { Email email = new SimpleEmail(); email.setHostName("smtp.live.com"); email.setSmtpPort(587); email.setStartTLSRequired(true); email.setAuthenticator(new DefaultAuthenticator(username, password)); email.setFrom(username); email.setSubject(assuntoEmail.getText()); email.setMsg(jTextAreaMsgEmail.getText()); email.addTo(emailDestino.getText()); email.setDebug(true); email.send(); aviso.setText("Mensagem enviada."); } catch (EmailException ex) { System.out.println("Erro: " + ex.getMessage()); } }
From source file:com.silverpeas.bootstrap.SilverpeasContextBootStrapper.java
/** * Loads all the JAR libraries available in the SILVERPEAS_HOME/repository/lib directory by using * our own classloader so that we avoid JBoss loads them with its its asshole VFS. *///from w ww .j a v a 2 s .c o m private static void loadExternalJarLibraries() { String libPath = System.getenv("SILVERPEAS_HOME") + separatorChar + "repository" + separatorChar + "lib"; File libDir = new File(libPath); File[] jars = libDir.listFiles(); URL[] jarURLs = new URL[jars.length]; try { for (int i = 0; i < jars.length; i++) { jarURLs[i] = jars[i].toURI().toURL(); } addURLs(jarURLs); String[] classNames = GeneralPropertiesManager.getString(CLASSES_TO_LOAD).split(","); for (String className : classNames) { try { Class aClass = ClassLoader.getSystemClassLoader().loadClass(className); Class<? extends Provider> jceProvider = aClass.asSubclass(Provider.class); Security.insertProviderAt(jceProvider.newInstance(), 0); } catch (Throwable t) { Logger.getLogger(SilverpeasContextBootStrapper.class.getSimpleName()).log(Level.SEVERE, t.getMessage(), t); } } } catch (Exception ex) { Logger.getLogger(SilverpeasContextBootStrapper.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(), ex); } }
From source file:org.edits.Edits.java
private void execute(CommandLine script) throws Exception { String annString = "org.edits.LuceneTokenizer"; if (script.hasOption(ANNOTATOR)) annString = script.getOptionValue(ANNOTATOR); EditsTextAnnotator annotator = (EditsTextAnnotator) ClassLoader.getSystemClassLoader().loadClass(annString) .newInstance();/*from w ww. ja v a 2s . co m*/ String output = script.getOptionValue(OUTPUT); if (output != null) { File f = new File(output); if (f.exists() && !script.hasOption(OVERWRITE)) throw new Exception("The file in which you want to output decisions already exists"); } String serialize = script.getOptionValue(SERIALIZE); if (serialize != null) { File f = new File(serialize); if (f.exists() && !script.hasOption(OVERWRITE)) throw new Exception("The file in which you want to serialize the model already exists"); } EntailmentEngine engine; if (script.hasOption(MODEL)) { EntailmentEngineModel model = (EntailmentEngineModel) FileTools.read(script.getOptionValue(MODEL)); engine = model.getEngine(); if (!script.hasOption(TEST)) { System.out.println(); System.out.println("=== Performance On Training ===\n"); System.out.println(model.getStatistics()); return; } } else { engine = createEngine(script); List<String> files = FileTools.inputFiles(script.getArgs()); List<EntailmentPair> all = input(files).getPair(); List<AnnotatedEntailmentPair> ps = EntailmentCorpus.annotate(annotator, all); EvaluationStatistics stats = engine.train(ps); if (serialize != null) saveModel(annString, output, engine, stats); System.out.println("=== Performance On Training ===\n"); System.out.println(stats); } if (!script.hasOption(TEST)) return; ObjectFactory f = new ObjectFactory(); EntailmentCorpus c = (EntailmentCorpus) f.load(script.getOptionValue(TEST)); c.annotate(annotator); EvaluationStatistics stats = null; ThreadExecutor mte = null; if (output != null) { Target<EvaluationResult> result = new FileTarget<EvaluationResult>(output); mte = new ThreadExecutor(engine, result); mte.run(c.getAnnotated()); result.close(); } else { mte = new ThreadExecutor(engine, false); mte.run(c.getAnnotated()); } stats = mte.statistics(); System.out.println("=== Performance On Test ===\n"); System.out.println(stats); }
From source file:com.cedarsoft.codegen.AbstractGenerator.java
@Nonnull public ClassLoader getDefaultClassLoader() { ClassLoader defaultClassLoader = getClass().getClassLoader(); if (defaultClassLoader == null) { defaultClassLoader = ClassLoader.getSystemClassLoader(); }//from www .j a va2 s .c o m return defaultClassLoader; }
From source file:org.danilopianini.io.FileUtilities.java
/** * This method loads an Image from the file system. * /*from www. ja va2 s . co m*/ * @param path * the path of the file to read * @return the loaded image */ public static Image loadImage(final String path) { final ClassLoader loader = ClassLoader.getSystemClassLoader(); final URL fileLocation = loader.getResource(path); final Image img = Toolkit.getDefaultToolkit().getImage(fileLocation); if (img != null) { return img; } return Toolkit.getDefaultToolkit().getImage(fileLocation); }