List of usage examples for java.lang ClassLoader getResource
public URL getResource(String name)
From source file:com.puppycrawl.tools.checkstyle.api.LocalizedMessageTest.java
@Test public void testBundleReloadUrlNotNull() throws IOException { ClassLoader classloader = mock(ClassLoader.class); final URLConnection mockConnection = Mockito.mock(URLConnection.class); when(mockConnection.getInputStream()).thenReturn(new ByteArrayInputStream(EMPTY_BYTE_ARRAY)); URL url = getMockUrl(mockConnection); String resource = "com/puppycrawl/tools/checkstyle/checks/coding/messages_en.properties"; when(classloader.getResource(resource)).thenReturn(url); LocalizedMessage.UTF8Control control = new LocalizedMessage.UTF8Control(); control.newBundle("com.puppycrawl.tools.checkstyle.checks.coding.messages", Locale.ENGLISH, "java.class", classloader, true);/*w w w. j a v a 2 s . c o m*/ }
From source file:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java
/** * ?xmldocument/*from www .j a v a2 s.c om*/ * @param resPath * @return */ private Document prepareDoc(final String resPath) { ClassLoader clsLoader = this.getClass().getClassLoader(); URL url = clsLoader.getResource(resPath); InputStream dsInput = null; try { if (url != null) { dsInput = url.openStream(); } } catch (IOException e1) { e1.printStackTrace(); } Document doc = null; if (dsInput != null) { try { doc = new SAXReader().read(dsInput); } catch (DocumentException e) { e.printStackTrace(); } } else { doc = DocumentHelper.createDocument(); } SimpleDateFormat dateFormat = new SimpleDateFormat(); doc.addComment("Auto created by AutoTest, " + dateFormat.format(new Date())); SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext(); simpleNamespaceContext.addNamespace("ns", "http://datasource.surenpi.com"); XPath xpath = new DefaultXPath("/ns:dataSources"); xpath.setNamespaceContext(simpleNamespaceContext); //? Element dataSourcesEle = (Element) xpath.selectSingleNode(doc); if (dataSourcesEle == null) { String prefix = "suren"; dataSourcesEle = doc.addElement(prefix + ":dataSources"); dataSourcesEle.addNamespace(prefix, "http://datasource.surenpi.com"); dataSourcesEle.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); dataSourcesEle.addAttribute("xsi:schemaLocation", "http://datasource.surenpi.com " + "http://surenpi.com/schema/datasource/autotest.web.framework.datasource.xsd "); } return doc; }
From source file:com.twitter.pig.backend.hadoop.executionengine.tez.TezExecutionEngine.java
@SuppressWarnings("deprecation") private void init(Properties properties) throws ExecException { //First set the ssh socket factory setSSHFactory();// www.j a v a2 s. c o m String cluster = null; String nameNode = null; // We need to build a configuration object first in the manner described below // and then get back a properties object to inspect the JOB_TRACKER_LOCATION // and FILE_SYSTEM_LOCATION. The reason to do this is if we looked only at // the existing properties object, we may not get the right settings. So we want // to read the configurations in the order specified below and only then look // for JOB_TRACKER_LOCATION and FILE_SYSTEM_LOCATION. // Hadoop by default specifies two resources, loaded in-order from the classpath: // 1. hadoop-default.xml : Read-only defaults for hadoop. // 2. hadoop-site.xml: Site-specific configuration for a given hadoop installation. // Now add the settings from "properties" object to override any existing properties // All of the above is accomplished in the method call below JobConf jc = null; if (this.pigContext.getExecType() == ExecType.TEZ) { // Check existence of user provided configs String isHadoopConfigsOverriden = properties.getProperty("pig.use.overriden.hadoop.configs"); if (isHadoopConfigsOverriden != null && isHadoopConfigsOverriden.equals("true")) { jc = new JobConf(ConfigurationUtil.toConfiguration(properties)); } else { // Check existence of hadoop-site.xml or core-site.xml in classpath // if user provided confs are not being used Configuration testConf = new Configuration(); ClassLoader cl = testConf.getClassLoader(); URL hadoop_site = cl.getResource(HADOOP_SITE); URL core_site = cl.getResource(CORE_SITE); if (hadoop_site == null && core_site == null) { throw new ExecException( "Cannot find hadoop configurations in classpath (neither hadoop-site.xml nor core-site.xml was found in the classpath)." + " If you plan to use local mode, please put -x local option in command line", 4010); } jc = new JobConf(); } jc.addResource("pig-cluster-hadoop-site.xml"); jc.addResource(YARN_SITE); /* // Trick to invoke static initializer of DistributedFileSystem to add hdfs-default.xml // into configuration new DistributedFileSystem(); */ //the method below alters the properties object by overriding the //hadoop properties with the values from properties and recomputing //the properties recomputeProperties(jc, properties); } else { // If we are running in local mode we dont read the hadoop conf file if (properties.getProperty("mapreduce.framework.name") == null) { properties.setProperty("mapreduce.framework.name", "local"); } properties.setProperty(JOB_TRACKER_LOCATION, LOCAL); properties.setProperty(FILE_SYSTEM_LOCATION, "file:///"); properties.setProperty(ALTERNATIVE_FILE_SYSTEM_LOCATION, "file:///"); jc = new JobConf(false); jc.addResource("core-default.xml"); jc.addResource("mapred-default.xml"); jc.addResource("yarn-default.xml"); recomputeProperties(jc, properties); } cluster = jc.get(JOB_TRACKER_LOCATION); nameNode = jc.get(FILE_SYSTEM_LOCATION); if (nameNode == null) nameNode = (String) pigContext.getProperties().get(ALTERNATIVE_FILE_SYSTEM_LOCATION); if (cluster != null && cluster.length() > 0) { if (!cluster.contains(":") && !cluster.equalsIgnoreCase(LOCAL)) { cluster = cluster + ":50020"; } properties.setProperty(JOB_TRACKER_LOCATION, cluster); } if (nameNode != null && nameNode.length() > 0) { if (!nameNode.contains(":") && !nameNode.equalsIgnoreCase(LOCAL)) { nameNode = nameNode + ":8020"; } properties.setProperty(FILE_SYSTEM_LOCATION, nameNode); } log.info("Connecting to hadoop file system at: " + (nameNode == null ? LOCAL : nameNode)); // constructor sets DEFAULT_REPLICATION_FACTOR_KEY ds = new HDataStorage(properties); if (cluster != null && !cluster.equalsIgnoreCase(LOCAL)) { log.info("Connecting to map-reduce job tracker at: " + jc.get(JOB_TRACKER_LOCATION)); } // Set job-specific configuration knobs jobConf = jc; }
From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPDigestUnitTestCase.java
@Override protected void establishUserApps() { ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl == null) { tcl = getClass().getClassLoader(); }// ww w . j a v a 2 s. c om final String WEBAPPDIR = "auth/webapp"; final String CONTEXTPATH = "/auth"; // for localhost:port/admin/index.html and whatever else is in the webapp directory final URL warUrl = tcl.getResource(WEBAPPDIR); final String warUrlString = warUrl.toExternalForm(); /* * Context context = new WebAppContext(warUrlString, CONTEXTPATH); server.setHandler(context); */ WebAppContext webapp = createWebApp(CONTEXTPATH, warUrlString); this.server.setHandler(webapp); // Thread.currentThread().setContextClassLoader(context.getClassLoader()); System.setProperty(PicketBoxConstants.USERNAME, "Aladdin"); System.setProperty(PicketBoxConstants.CREDENTIAL, "Open Sesame"); FilterHolder filterHolder = new FilterHolder(DelegatingSecurityFilter.class); /* * Map<String, String> contextParameters = new HashMap<String, String>(); * contextParameters.put(PicketBoxConstants.AUTHENTICATION_KEY, PicketBoxConstants.HTTP_DIGEST); * contextParameters.put(PicketBoxConstants.HTTP_CONFIGURATION_PROVIDER, * HTTPDigestConfigurationProvider.class.getName()); * * context.setInitParams(contextParameters); * * context.addFilter(filterHolder, "/", 1); */ webapp.setInitParameter(PicketBoxConstants.AUTHENTICATION_KEY, PicketBoxConstants.HTTP_DIGEST); webapp.setInitParameter(PicketBoxConstants.HTTP_CONFIGURATION_PROVIDER, HTTPDigestConfigurationProvider.class.getName()); ServletHandler servletHandler = new ServletHandler(); servletHandler.addFilter(filterHolder, createFilterMapping("/", filterHolder)); webapp.setServletHandler(servletHandler); }
From source file:edu.cornell.med.icb.io.ResourceFinder.java
/** * Search for a resource using the thread context class loader. If that fails, search * using the class loader that loaded this class. If that still fails, try one last * time with {@link ClassLoader#getSystemResource(String)}. * @param resource The resource to search for * @return A url representing the resource or {@code null} if the resource was not found *///from ww w .ja va 2s . co m private URL resourceToUrl(final String resource) { URL url; // get the configuration from the classpath of the current thread ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (LOG.isDebugEnabled()) { LOG.debug("Trying to find [" + resource + "] using context class loader " + loader); } url = loader.getResource(resource); if (url == null) { // We couldn't find resource - now try with the class loader that loaded this class loader = ResourceFinder.class.getClassLoader(); // NOPMD if (LOG.isDebugEnabled()) { LOG.debug("Trying to find [" + resource + "] using class loader " + loader); } url = loader.getResource(resource); } if (url == null) { // make a last attempt to get the resource from the system class loader if (LOG.isDebugEnabled()) { LOG.debug("Trying to find [" + resource + "] using system class loader"); } url = ClassLoader.getSystemResource(resource); } if (url != null && LOG.isDebugEnabled()) { LOG.debug("... found url is [" + url.toString() + "]"); } return url; }
From source file:XMLResourceBundleControl.java
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) { throw new NullPointerException(); }//from w w w. ja v a 2 s. com ResourceBundle bundle = null; if (!format.equals(XML)) { return null; } String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, format); URL url = loader.getResource(resourceName); if (url == null) { return null; } URLConnection connection = url.openConnection(); if (connection == null) { return null; } if (reload) { connection.setUseCaches(false); } InputStream stream = connection.getInputStream(); if (stream == null) { return null; } BufferedInputStream bis = new BufferedInputStream(stream); bundle = new XMLResourceBundle(bis); bis.close(); return bundle; }
From source file:appeng.recipes.loader.RecipeResourceCopier.java
/** * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs. * * @param clazz Any java class that lives in the same place as the resources you want. * @param path Should end with "/", but not start with one. * * @return Just the name of each member item, not the full paths. * * @throws URISyntaxException if it is a file path and the URL can not be converted to URI * @throws IOException if jar path can not be decoded * @throws UnsupportedOperationException if it is neither in jar nor in file path *///from ww w . j a v a2 s. c o m @Nonnull private String[] getResourceListing(@Nonnull final Class<?> clazz, @Nonnull final String path) throws URISyntaxException, IOException { assert clazz != null; assert path != null; final ClassLoader classLoader = clazz.getClassLoader(); if (classLoader == null) { throw new IllegalStateException( "ClassLoader was not found. It was probably loaded at a inappropriate time"); } URL dirURL = classLoader.getResource(path); if (dirURL != null) { final String protocol = dirURL.getProtocol(); if (protocol.equals(FILE_PROTOCOL)) { // A file path: easy enough final URI uriOfURL = dirURL.toURI(); final File fileOfURI = new File(uriOfURL); final String[] filesAndDirectoriesOfURI = fileOfURI.list(); if (filesAndDirectoriesOfURI == null) { throw new IllegalStateException( "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured."); } else { return filesAndDirectoriesOfURI; } } } if (dirURL == null) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ final String className = clazz.getName(); final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className); final String me = matcher.replaceAll("/") + CLASS_EXTENSION; dirURL = classLoader.getResource(me); } if (dirURL != null) { final String protocol = dirURL.getProtocol(); if (protocol.equals(JAR_PROTOCOL)) { /* A JAR path */ final String dirPath = dirURL.getPath(); final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only // the JAR file final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING)); try { final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar final Collection<String> result = new HashSet<String>(INITIAL_RESOURCE_CAPACITY); // avoid duplicates // in case it is a // subdirectory while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String entryFullName = entry.getName(); if (entryFullName.startsWith(path)) { // filter according to the path String entryName = entryFullName.substring(path.length()); final int checkSubDir = entryName.indexOf('/'); if (checkSubDir >= 0) { // if it is a subdirectory, we just return the directory name entryName = entryName.substring(0, checkSubDir); } result.add(entryName); } } return result.toArray(new String[result.size()]); } finally { jar.close(); } } } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:com.ibm.jaggr.core.impl.options.OptionsImpl.java
/** * Returns the default options for this the aggregator service. * * @return The default options./*from ww w .j a va2s .co m*/ */ protected Properties initDefaultOptions() { Properties defaultValues = new Properties(); defaultValues.putAll(defaults); // See if there's an aggregator.properties in the class loader's root ClassLoader cl = OptionsImpl.class.getClassLoader(); URL url = cl.getResource(getPropsFilename()); if (url != null) { loadFromUrl(defaultValues, url); } // If the bundle defines properties, then load those too if (aggregator != null) { url = aggregator.getPlatformServices().getResource(getPropsFilename()); if (url != null) { loadFromUrl(defaultValues, url); } } return defaultValues; }
From source file:org.toobsframework.transformpipeline.domain.XSLUriResolverImpl.java
protected URL resolveClasspathResource(String xslFile, String base) throws TransformerException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL configFileURL = null;//from www. j a va2 s .c o m String systemId = null; for (int i = 0; i < this.classpathBase.size(); i++) { systemId = this.classpathBase.get(i) + xslFile; if (log.isDebugEnabled()) { log.debug("Checking for: " + systemId); } configFileURL = classLoader.getResource(systemId); if (null != configFileURL) { break; } } return configFileURL; }
From source file:org.picketbox.test.jaxrs.RESTEasyStandaloneTestCase.java
@Override protected void establishUserApps() { ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if (tcl == null) { tcl = getClass().getClassLoader(); }/*from ww w. j a v a 2 s. c o m*/ final String WEBAPPDIR = "resteasy/standalone"; final String CONTEXTPATH = "/*"; // for localhost:port/admin/index.html and whatever else is in the webapp directory final URL warUrl = tcl.getResource(WEBAPPDIR); final String warUrlString = warUrl.toExternalForm(); // WebAppContext context = new WebAppContext(warUrlString, CONTEXTPATH); WebAppContext context = createWebApp(CONTEXTPATH, warUrlString); context.setContextPath("/"); ServletHolder servletHolder = new ServletHolder(new HttpServletDispatcher()); servletHolder.setInitParameter("javax.ws.rs.Application", TestApplicationConfig.class.getName()); context.addServlet(servletHolder, "/*"); // context.setParentLoaderPriority(true); server.setHandler(context); }