List of usage examples for java.lang ClassLoader getResource
public URL getResource(String name)
From source file:org.apache.camel.util.ObjectHelper.java
/** * Attempts to load the given resource as a stream using the thread context * class loader or the class loader used to load this class * * @param name the name of the resource to load * @return the stream or null if it could not be loaded *//* w w w. ja v a 2 s. c o m*/ public static URL loadResourceAsURL(String name) { URL url = null; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { url = contextClassLoader.getResource(name); } if (url == null) { url = ObjectHelper.class.getClassLoader().getResource(name); } return url; }
From source file:com.joyent.manta.client.MantaClientPutIT.java
@Test public final void testPutWithMarkSupportedStream() throws IOException, URISyntaxException { final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Assert.assertNotNull(classLoader.getResource(TEST_FILENAME)); try (InputStream testDataInputStream = classLoader.getResourceAsStream(TEST_FILENAME); CountingInputStream countingInputStream = new CountingInputStream(testDataInputStream)) { Assert.assertTrue(countingInputStream.markSupported()); mantaClient.put(path, countingInputStream); Assert.assertTrue(mantaClient.existsAndIsAccessible(path)); File localFile = Paths.get(classLoader.getResource(TEST_FILENAME).toURI()).toFile(); byte[] expectedBytes = FileUtils.readFileToByteArray(localFile); try (MantaObjectInputStream in = mantaClient.getAsInputStream(path)) { byte[] actualBytes = IOUtils.readFully(in, (int) localFile.length()); AssertJUnit.assertArrayEquals(expectedBytes, actualBytes); }//www . j ava 2 s . com } }
From source file:it.danja.newsmonitor.utils.HttpServer.java
public void init() { // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build();/* w w w .j a v a 2 s .co m*/ // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service httpService = new HttpService(httpproc, reqistry); if (port == 8443) { // Initialize SSL context ClassLoader cl = HttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { log.info("HttpServer : Keystore not found"); System.exit(1); } KeyStore keystore = null; try { keystore = KeyStore.getInstance("jks"); } catch (KeyStoreException e) { log.error(e.getMessage()); } try { keystore.load(url.openStream(), "secret".toCharArray()); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage()); } catch (CertificateException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } KeyManagerFactory kmfactory = null; try { kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage()); } try { kmfactory.init(keystore, "secret".toCharArray()); } catch (UnrecoverableKeyException e) { log.error(e.getMessage()); } catch (KeyStoreException e) { log.error(e.getMessage()); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage()); } KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = null; try { sslcontext = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage()); } try { sslcontext.init(keymanagers, null, null); } catch (KeyManagementException e) { log.error(e.getMessage()); } this.sf = sslcontext.getServerSocketFactory(); } }
From source file:org.apache.pig.backend.hadoop.executionengine.HExecutionEngine.java
public JobConf getExecConf(Properties properties) throws ExecException { JobConf jc = null;/*from w w w .jav a 2s.c o m*/ // 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); return jc; }
From source file:info.magnolia.templating.jsp.AbstractTagTestCase.java
@Before public void setUp() throws Exception { // need to pass a web.xml file to setup servletunit working directory final ClassLoader classLoader = getClass().getClassLoader(); final URL webXmlUrl = classLoader.getResource("WEB-INF/web.xml"); if (webXmlUrl == null) { Assert.fail("Could not find WEB-INF/web.xml"); }//from w ww. ja v a 2 s. c o m final String path = URLDecoder.decode(webXmlUrl.getFile(), "UTF-8"); HttpUnitOptions.setDefaultCharacterSet("utf-8"); System.setProperty("file.encoding", "utf-8"); // check we can write in jasper's scratch directory final File jspScratchDir = new File("target/jsp-test-scratch-dir"); final String jspScratchDirAbs = jspScratchDir.getAbsolutePath(); if (!jspScratchDir.exists()) { Assert.assertTrue("Can't create path " + jspScratchDirAbs + ", aborting test", jspScratchDir.mkdirs()); } final File checkFile = new File(jspScratchDir, "empty"); Assert.assertTrue("Can't write check file: " + checkFile + ", aborting test", checkFile.createNewFile()); Assert.assertTrue("Can't remove check file:" + checkFile + ", aborting test", checkFile.delete()); // start servletRunner final Hashtable<String, String> params = new Hashtable<String, String>(); params.put("javaEncoding", "utf-8"); params.put("development", "true"); params.put("keepgenerated", "false"); params.put("modificationTestInterval", "1000"); params.put("scratchdir", jspScratchDirAbs); params.put("engineOptionsClass", TestServletOptions.class.getName()); runner = new ServletRunner(new File(path), CONTEXT); runner.registerServlet("*.jsp", "org.apache.jasper.servlet.JspServlet", params); // setup context session = MockUtil.createAndSetHierarchyManager("website", StringUtils.join(new String[] { "/foo/bar.@type=mgnl:page", "/foo/bar.title=Bar title", "/foo/bar/0.text=hello root 1", "/foo/bar.mgnl\\:template=testPageTemplate", "/foo/bar/paragraphs.@type=mgnl:area", "/foo/bar/paragraphs/0.@type=mgnl:component", "/foo/bar/paragraphs/0.@uuid=100", "/foo/bar/paragraphs/1.@type=mgnl:component", "/foo/bar/paragraphs/1.@uuid=101", "/foo/bar/paragraphs/1.text=hello 1", "/foo/bar/paragraphs/1.mgnl\\:template=testParagraph1", "/foo/bar/paragraphs/1/image.@type=mgnl:resource", "/foo/bar/paragraphs/1/image.jcr:data=binary:12345", "/foo/bar/paragraphs/1/image.extension=jpg", "/foo/bar/paragraphs/1/image.fileName=file", }, "\n")); aggState = new AggregationState(); // let's make sure we render stuff on an author instance aggState.setPreviewMode(false); final ServerConfiguration serverCfg = new ServerConfiguration(); serverCfg.setAdmin(true); ConfiguredTemplateDefinition testParagraph0 = new ConfiguredTemplateDefinition(); testParagraph0.setName("testParagraph0"); testParagraph0.setTitle("Test Paragraph 0"); ConfiguredTemplateDefinition testParagraph1 = new ConfiguredTemplateDefinition(); testParagraph1.setName("testParagraph1"); testParagraph1.setTitle("Test Paragraph 1"); testParagraph1.setDialog("testDialog"); ConfiguredTemplateDefinition testParagraph2 = new ConfiguredTemplateDefinition(); testParagraph2.setName("testParagraph2"); testParagraph2.setTitle("Test Paragraph 2"); final TemplateDefinitionProvider p0provider = mock(TemplateDefinitionProvider.class); final TemplateDefinitionProvider p1provider = mock(TemplateDefinitionProvider.class); final TemplateDefinitionProvider p2provider = mock(TemplateDefinitionProvider.class); when(p0provider.getTemplateDefinition()).thenReturn(testParagraph0); when(p0provider.getId()).thenReturn(testParagraph0.getName()); when(p1provider.getTemplateDefinition()).thenReturn(testParagraph1); when(p1provider.getId()).thenReturn(testParagraph1.getName()); when(p2provider.getTemplateDefinition()).thenReturn(testParagraph2); when(p2provider.getId()).thenReturn(testParagraph2.getName()); ComponentsTestUtil.setInstance(ServerConfiguration.class, serverCfg); // register some default components used internally ComponentsTestUtil.setImplementation(MessagesManager.class, DefaultMessagesManager.class); ComponentsTestUtil.setImplementation(I18nContentSupport.class, DefaultI18nContentSupport.class); ComponentsTestUtil.setImplementation(I18nAuthoringSupport.class, DefaultI18nAuthoringSupport.class); ComponentsTestUtil.setImplementation(ContextFactory.class, ContextFactory.class); ComponentsTestUtil.setImplementation(TemplateDefinitionAssignment.class, MetaDataBasedTemplateDefinitionAssignment.class); // configure node2bean because its processor is injected into DefaultMessagesManager constructor ComponentsTestUtil.setImplementation(Node2BeanProcessor.class, Node2BeanProcessorImpl.class); ComponentsTestUtil.setImplementation(TypeMapping.class, TypeMappingImpl.class); ComponentsTestUtil.setImplementation(Node2BeanTransformer.class, Node2BeanTransformerImpl.class); MockContext systemContext = new MockContext(); systemContext.addSession("website", session.getJcrSession()); ComponentsTestUtil.setInstance(SystemContext.class, systemContext); aggState.setCurrentContent(session.getContent("/foo/bar/paragraphs/1")); renderingContext = new AggregationStateBasedRenderingContext(aggState, null); final RenderingEngine renderingEngine = mock(RenderingEngine.class); when(renderingEngine.getRenderingContext()).thenReturn(renderingContext); ComponentsTestUtil.setInstance(RenderingEngine.class, renderingEngine); final TemplateDefinitionRegistry tdr = new TemplateDefinitionRegistry(); tdr.register(p0provider); tdr.register(p1provider); tdr.register(p2provider); ComponentsTestUtil.setInstance(TemplateDefinitionRegistry.class, tdr); req = mock(HttpServletRequest.class); req.setAttribute(Sources.REQUEST_LINKS_DRAWN, Boolean.TRUE); res = mock(HttpServletResponse.class); when(res.getWriter()).thenReturn(null); when(res.isCommitted()).thenReturn(true); ctx = mock(WebContext.class); when(ctx.getAggregationState()).thenReturn(aggState); when(ctx.getLocale()).thenReturn(Locale.US); when(ctx.getResponse()).thenReturn(res); when(ctx.getRequest()).thenReturn(req); MgnlUser mockUser = mock(MgnlUser.class); when(mockUser.getLanguage()).thenReturn("en"); when(ctx.getUser()).thenReturn(mockUser); when(ctx.getContextPath()).thenReturn("contextPath"); when(ctx.getHierarchyManager("website")).thenReturn(session); when(ctx.getJCRSession("website")).thenReturn(session.getJcrSession()); setupExpectations(ctx, req); MgnlContext.setInstance(ctx); }
From source file:nz.govt.natlib.ndha.manualdeposit.customui.IconRenderer.java
private Icon createIcon(final ClassLoader cLoader, final String iconPath) { Icon retVal = null;/*from w w w . ja va 2 s . c o m*/ if (new File(iconPath).exists()) { retVal = new ImageIcon(iconPath); } else { final java.net.URL imageURL = cLoader.getResource(iconPath); if (imageURL != null) { retVal = new ImageIcon(imageURL); } } return retVal; }
From source file:org.apache.oozie.service.XLogService.java
/** * Initialize the log service./*from w ww . j av a 2 s .c o m*/ * * @param services services instance. * @throws ServiceException thrown if the log service could not be initialized. */ public void init(Services services) throws ServiceException { String oozieHome = Services.getOozieHome(); String oozieLogs = System.getProperty(OOZIE_LOG_DIR, oozieHome + "/logs"); System.setProperty(OOZIE_LOG_DIR, oozieLogs); try { LogManager.resetConfiguration(); log4jFileName = System.getProperty(LOG4J_FILE, DEFAULT_LOG4J_PROPERTIES); if (log4jFileName.contains("/")) { throw new ServiceException(ErrorCode.E0011, log4jFileName); } if (!log4jFileName.endsWith(".properties")) { throw new ServiceException(ErrorCode.E0012, log4jFileName); } String configPath = ConfigurationService.getConfigurationDirectory(); File log4jFile = new File(configPath, log4jFileName); if (log4jFile.exists()) { fromClasspath = false; } else { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL log4jUrl = cl.getResource(log4jFileName); if (log4jUrl == null) { throw new ServiceException(ErrorCode.E0013, log4jFileName, configPath); } fromClasspath = true; } if (fromClasspath) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL log4jUrl = cl.getResource(log4jFileName); PropertyConfigurator.configure(log4jUrl); } else { interval = Long.parseLong(System.getProperty(LOG4J_RELOAD, DEFAULT_RELOAD_INTERVAL)); PropertyConfigurator.configureAndWatch(log4jFile.toString(), interval * 1000); } log = new XLog(LogFactory.getLog(getClass())); log.info(XLog.OPS, STARTUP_MESSAGE, BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VERSION), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_USER_NAME), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_TIME), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VC_REVISION), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VC_URL)); String from = (fromClasspath) ? "CLASSPATH" : configPath; String reload = (fromClasspath) ? "disabled" : Long.toString(interval) + " sec"; log.info("Log4j configuration file [{0}]", log4jFileName); log.info("Log4j configuration file loaded from [{0}]", from); log.info("Log4j reload interval [{0}]", reload); XLog.Info.reset(); XLog.Info.defineParameter(USER); XLog.Info.defineParameter(GROUP); XLogFilter.reset(); XLogFilter.defineParameter(USER); XLogFilter.defineParameter(GROUP); // Getting configuration for oozie log via WS ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = (fromClasspath) ? cl.getResourceAsStream(log4jFileName) : new FileInputStream(log4jFile); extractInfoForLogWebService(is); } catch (IOException ex) { throw new ServiceException(ErrorCode.E0010, ex.getMessage(), ex); } }
From source file:com.linkedin.pinot.core.segment.index.loader.SegmentPreProcessorTest.java
@BeforeClass public void setUp() throws Exception { // For indexLoadingConfigMetadata, we specify two columns without inverted index ('column1', 'column13'), one // non-existing column ('noSuchColumn') and one column with existed inverted index ('column7'). indexLoadingConfigMetadata = new IndexLoadingConfigMetadata(new PropertiesConfiguration()); indexLoadingConfigMetadata.initLoadingInvertedIndexColumnSet( new String[] { COLUMN1_NAME, COLUMN7_NAME, COLUMN13_NAME, NO_SUCH_COLUMN_NAME }); indexLoadingConfigMetadata.setEnableDefaultColumns(true); // For newColumnsSchema, we add 4 different data type metric columns with one user-defined default null value, and // 3 different data type dimension columns with one user-defined default null value and one multi-value column. ClassLoader classLoader = getClass().getClassLoader(); URL resourceUrl = classLoader.getResource(NEW_COLUMNS_SCHEMA1); Preconditions.checkNotNull(resourceUrl); newColumnsSchema1 = Schema.fromFile(new File(resourceUrl.getFile())); resourceUrl = classLoader.getResource(NEW_COLUMNS_SCHEMA2); Preconditions.checkNotNull(resourceUrl); newColumnsSchema2 = Schema.fromFile(new File(resourceUrl.getFile())); resourceUrl = classLoader.getResource(NEW_COLUMNS_SCHEMA3); Preconditions.checkNotNull(resourceUrl); newColumnsSchema3 = Schema.fromFile(new File(resourceUrl.getFile())); }
From source file:edu.berkeley.compbio.phyloutils.HugenholtzTaxonomyService.java
private synchronized static InputStream getInputStream(String filename) throws PhyloUtilsException, IOException { //ClassLoader classClassLoader = new NewickParser().getClass().getClassLoader(); ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); //ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); //URL res1 = classClassLoader.getResource(filename); URL res = threadClassLoader.getResource(filename); //URL res3 = systemClassLoader.getResource(filename); if (res == null) { File f = new File(filename); if (f.exists()) { res = f.toURI().toURL(); // new URL("file://" + filename); }// w w w . jav a2 s . co m } if (res == null) { logger.error("file not found: " + filename); //Get the System Classloader //ClassLoader.getSystemClassLoader(); //Get the URLs URL[] urls = ((URLClassLoader) threadClassLoader).getURLs(); for (int i = 0; i < urls.length; i++) { logger.warn(urls[i].getFile()); } throw new PhyloUtilsException("file not found: " + filename); } InputStream is = res.openStream(); is = filename.endsWith(".gz") ? new GZIPInputStream(is) : is; /*if (is == null) { is = new FileInputStream(filename); }*/ return is; }
From source file:ffx.xray.FiniteDifferenceTest.java
public FiniteDifferenceTest(boolean ciOnly, String info, SolventModel solventModel, int[] atoms, String pdbName, String mtzName) {/* w w w .j a va 2 s . c o m*/ this.ciOnly = ciOnly; this.atoms = atoms; ci = System.getProperty("ffx.ci", "false").equalsIgnoreCase("true"); if (!ci && ciOnly) { atomArray = null; refinementData = null; sigmaAMinimize = null; return; } int index = pdbName.lastIndexOf("."); String name = pdbName.substring(0, index); // load the structure ClassLoader cl = this.getClass().getClassLoader(); File structure = new File(cl.getResource(pdbName).getPath()); File mtzFile = new File(cl.getResource(mtzName).getPath()); // load any properties associated with it CompositeConfiguration properties = Keyword.loadProperties(structure); // read in Fo/sigFo/FreeR MTZFilter mtzFilter = new MTZFilter(); ReflectionList reflectionList; Crystal crystal = Crystal.checkProperties(properties); Resolution resolution = Resolution.checkProperties(properties); if (crystal == null || resolution == null) { reflectionList = mtzFilter.getReflectionList(mtzFile); } else { reflectionList = new ReflectionList(crystal, resolution); } refinementData = new DiffractionRefinementData(properties, reflectionList); assertTrue(info + " mtz file should be read in without errors", mtzFilter.readFile(mtzFile, reflectionList, refinementData, properties)); ForceFieldFilter forceFieldFilter = new ForceFieldFilter(properties); ForceField forceField = forceFieldFilter.parse(); // associate molecular assembly with the structure, set up forcefield MolecularAssembly molecularAssembly = new MolecularAssembly(name); molecularAssembly.setFile(structure); molecularAssembly.setForceField(forceField); PDBFilter pdbFile = new PDBFilter(structure, molecularAssembly, forceField, properties); pdbFile.readFile(); pdbFile.applyAtomProperties(); molecularAssembly.finalize(true, forceField); ForceFieldEnergy energy = new ForceFieldEnergy(molecularAssembly, pdbFile.getCoordRestraints()); List<Atom> atomList = molecularAssembly.getAtomList(); atomArray = atomList.toArray(new Atom[0]); boolean use_3g = properties.getBoolean("use_3g", true); // initialize atomic form factors for (Atom atom : atomArray) { XRayFormFactor xrayFormFactor = new XRayFormFactor(atom, use_3g, 2.0); atom.setFormFactorIndex(xrayFormFactor.ffIndex); if (atom.getOccupancy() == 0.0) { atom.setFormFactorWidth(1.0); continue; } double aRad = 2.4; double xyz[] = new double[3]; xyz[0] = atom.getX() + aRad; xyz[1] = atom.getY(); xyz[2] = atom.getZ(); while (true) { double rho = xrayFormFactor.rho(0.0, 1.0, xyz); if (rho > 0.1) { aRad += 0.5; } else if (rho > 0.001) { aRad += 0.1; } else { aRad += 0.75; atom.setFormFactorWidth(aRad); break; } xyz[0] = atom.getX() + aRad; } } // set up FFT and run it ParallelTeam parallelTeam = new ParallelTeam(); CrystalReciprocalSpace crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam, parallelTeam, false, false); crs.computeDensity(refinementData.fc); refinementData.setCrystalReciprocalSpace_fc(crs); crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam, parallelTeam, true, false, solventModel); crs.computeDensity(refinementData.fs); refinementData.setCrystalReciprocalSpace_fs(crs); ScaleBulkMinimize scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, crs, parallelTeam); scaleBulkMinimize.minimize(6, 1.0e-4); sigmaAMinimize = new SigmaAMinimize(reflectionList, refinementData, parallelTeam); sigmaAMinimize.minimize(7, 2.0e-2); SplineMinimize splineMinimize = new SplineMinimize(reflectionList, refinementData, refinementData.spline, SplineEnergy.Type.FOFC); splineMinimize.minimize(7, 1e-5); CrystalStats crystalstats = new CrystalStats(reflectionList, refinementData); crystalstats.printScaleStats(); crystalstats.printHKLStats(); crystalstats.printSNStats(); crystalstats.printRStats(); }