List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:org.apache.jsieve.ConfigurationManager.java
/** * <p>/*from w w w . j a va2 s .c om*/ * Method getConfigStream answers an InputStream over the Sieve * configuration file. It is located by searching the classpath of the * current ClassLoader. * </p> * <p> * The context classloader is searched first. If a suitably named resource * is found then this is returned. Otherwise, the classloader used to load * this class is searched for the resource. * </p> * * @return InputStream * @throws IOException */ private InputStream getConfigStream(String configName) throws IOException { InputStream stream = null; // Context classloader is usually right in a JEE evironment final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { stream = contextClassLoader.getResourceAsStream(configName); } // Sometimes context classloader will not be set conventionally // So, try class classloader if (null == stream) { stream = ConfigurationManager.class.getClassLoader().getResourceAsStream(configName); } if (null == stream) throw new IOException("Resource \"" + configName + "\" not found"); return stream; }
From source file:io.syndesis.maven.ExtractConnectorDescriptorsMojo.java
@SuppressWarnings("PMD.AvoidCatchingGenericException") private Properties loadComponentProperties(ClassLoader classLoader) { try {//from ww w .j ava 2s . c o m // load the component files using the recommended way by a component.properties file InputStream is = classLoader .getResourceAsStream("META-INF/services/org/apache/camel/component.properties"); if (is != null) { Properties ret = new Properties(); ret.load(is); return ret; } } catch (Exception e) { getLog().warn("WARN: Error loading META-INF/services/org/apache/camel/component.properties file due " + e.getMessage()); } return null; }
From source file:com.dm.estore.core.config.impl.InitDataLoaderImpl.java
private void readProducts(final ParseHandler handler) throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try (InputStream is = classLoader.getResourceAsStream("Products.csv"); final InputStreamReader fileInputStream = new InputStreamReader(is); final CSVReader reader = new CSVReader(fileInputStream);) { String[] nextLine;/*from www.ja v a 2 s .c o m*/ while ((nextLine = reader.readNext()) != null) { handler.handle(nextLine); } } }
From source file:com.dm.estore.core.config.impl.InitDataLoaderImpl.java
private void readCategories(final ParseHandler handler) throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try (InputStream is = classLoader.getResourceAsStream("Categories.csv"); final InputStreamReader fileInputStream = new InputStreamReader(is); final CSVReader reader = new CSVReader(fileInputStream);) { String[] nextLine;/*from ww w. j a v a2 s .co m*/ while ((nextLine = reader.readNext()) != null) { handler.handle(nextLine); } } }
From source file:com.google.ratel.util.RatelUtils.java
/** * Load the resource for the given resourcePath from the classpath. * * @param resourcePath the path of the resource to load * @return the byte array for the given resource path * @throws IOException if the resource could not be loaded */// w ww .j av a2 s .com public static InputStream getClasspathResourceAsStream(String resourcePath) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(resourcePath); if (inputStream == null) { inputStream = RatelUtils.class.getResourceAsStream(resourcePath); } return inputStream; }
From source file:oracle.kv.hadoop.table.TableInputFormatBase.java
/** * Set/create the artifacts required to connect to and interact * with a secure store; specifically, a login properties file, * a trust file containing public keys and/or certificates, and * <code>PasswordCredentials</code>. If the value input for the * <code>loginFile</code> and <code>trustFile</code> parameter * is a fully-qualified path, then this method initializes the * corresponding static variables to those values so that the * <code>getSplits</code> method can contact a secure store, extracts * the filenames from those paths, uses those values to initialize * the corresponding static filename variables used to initialize * the splits that are created, and returns. * <p>//from ww w .java 2 s . c o m * If the value input for the <code>loginFile</code> and * <code>trustFile</code> parameter is not a fully-qualified path, * then this method uses the given file names to retrieve the contents * of the associated login file and trust file as resources from * the classpath, and writes that information to corresponding files * on the local file system (in a directory owned by the user under * which the application is executed). After generating the local * files, the fully-qualified paths to those files are used to * initialize the corresponding static variables so that the * <code>getSplits</code> method can contact a secure store. */ private static void setLocalKVSecurity(final String loginFile, final PasswordCredentials userPasswordCredentials, final String trustFile) throws IOException { if (loginFile == null) { return; } if (userPasswordCredentials == null) { return; } if (trustFile == null) { return; } final File loginFd = new File(loginFile); boolean loginIsAbsolute = false; if (loginFd.isAbsolute()) { loginIsAbsolute = true; TableInputFormatBase.localLoginFile = loginFile; TableInputFormatBase.loginFlnm = loginFd.getName(); } else { TableInputFormatBase.loginFlnm = loginFile; } TableInputFormatBase.passwordCredentials = userPasswordCredentials; final File trustFd = new File(trustFile); boolean trustIsAbsolute = false; if (trustFd.isAbsolute()) { trustIsAbsolute = true; TableInputFormatBase.trustFlnm = trustFd.getName(); } else { TableInputFormatBase.trustFlnm = trustFile; } if (loginIsAbsolute && trustIsAbsolute) { return; } /* * If loginFile and/or trustFile is a filename and not an absolute * path, then generate local versions of the file. */ final File userSecurityDirFd = new File(USER_SECURITY_DIR); if (!userSecurityDirFd.exists()) { if (!userSecurityDirFd.mkdirs()) { throw new IOException("failed to create " + userSecurityDirFd); } } final ClassLoader cl = TableInputFormatBase.class.getClassLoader(); if (!loginIsAbsolute) { InputStream loginStream = null; if (cl != null) { loginStream = cl.getResourceAsStream(loginFlnm); } else { loginStream = ClassLoader.getSystemResourceAsStream(loginFlnm); } /* * Retrieve the login configuration as a resource from the * classpath, and write that information to the user's local * file system. But exclude any properties related to user * authorization; that is, exclude all properties of the form * 'oracle.kv.auth.*", to prevent those property values from * being sent and cached on the DataNodes. */ final Properties loginProps = new Properties(); if (loginStream != null) { loginProps.load(loginStream); } /* Exclude 'oracle.kv.auth.*" properties. */ loginProps.remove(KVSecurityConstants.AUTH_USERNAME_PROPERTY); loginProps.remove(KVSecurityConstants.AUTH_WALLET_PROPERTY); loginProps.remove(KVSecurityConstants.AUTH_PWDFILE_PROPERTY); /* Strip off the path of the trust file. */ final String trustProp = loginProps.getProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY); if (trustProp != null) { final File trustPropFd = new File(trustProp); if (!trustPropFd.exists()) { loginProps.setProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY, trustPropFd.getName()); } } final File absoluteLoginFd = new File(USER_SECURITY_DIR + FILE_SEP + loginFlnm); final FileOutputStream loginFos = new FileOutputStream(absoluteLoginFd); try { loginProps.store(loginFos, null); } finally { loginFos.close(); } TableInputFormatBase.localLoginFile = absoluteLoginFd.toString(); } if (!trustIsAbsolute) { InputStream trustStream = null; if (cl != null) { trustStream = cl.getResourceAsStream(trustFlnm); } else { trustStream = ClassLoader.getSystemResourceAsStream(trustFlnm); } /* * Retrieve the trust credentials as a resource from the classpath, * and write that information to the user's local file system. */ final File absoluteTrustFd = new File(USER_SECURITY_DIR + FILE_SEP + trustFlnm); final FileOutputStream trustFlnmFos = new FileOutputStream(absoluteTrustFd); try { int nextByte = trustStream.read(); while (nextByte != -1) { trustFlnmFos.write(nextByte); nextByte = trustStream.read(); } } finally { trustFlnmFos.close(); } } }
From source file:com.agilejava.docbkx.maven.AbstractFoMojo.java
/** * DOCUMENT ME!/*from ww w . j av a 2 s .co m*/ * * @return DOCUMENT ME! * * @throws MojoExecutionException DOCUMENT ME! */ protected Configuration loadFOPConfig() throws MojoExecutionException { // if using external fop configuration file if (externalFOPConfiguration != null) { DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(); try { if (getLog().isDebugEnabled()) getLog().debug("Using external FOP configuration file: " + externalFOPConfiguration.toString()); getLog().info("Ignoring pom inline FOP configuration"); return builder.buildFromFile(externalFOPConfiguration); } catch (IOException ioe) { throw new MojoExecutionException("Failed to load external FOP config.", ioe); } catch (SAXException saxe) { throw new MojoExecutionException("Failed to parse external FOP config.", saxe); } catch (ConfigurationException e) { throw new MojoExecutionException("Failed to do something Avalon requires....", e); } // else generating the configuration file } else { ClassLoader loader = this.getClass().getClassLoader(); InputStream in = loader.getResourceAsStream("fonts.stg"); Reader reader = new InputStreamReader(in); StringTemplateGroup group = new StringTemplateGroup(reader); StringTemplate template = group.getInstanceOf("config"); template.setAttribute("fonts", fonts); if (targetResolution != 0) { template.setAttribute("targetResolution", targetResolution); } if (sourceResolution != 0) { template.setAttribute("sourceResolution", sourceResolution); } DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(); final String config = template.toString(); if (getLog().isDebugEnabled()) { getLog().debug(config); } try { return builder.build(IOUtils.toInputStream(config)); } catch (IOException ioe) { throw new MojoExecutionException("Failed to load FOP config.", ioe); } catch (SAXException saxe) { throw new MojoExecutionException("Failed to parse FOP config.", saxe); } catch (ConfigurationException e) { throw new MojoExecutionException("Failed to do something Avalon requires....", e); } } }
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 *///from w w w . j ava2 s .co m public static InputStream loadResourceAsStream(String name) { InputStream in = null; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { in = contextClassLoader.getResourceAsStream(name); } if (in == null) { in = ObjectHelper.class.getClassLoader().getResourceAsStream(name); } return in; }
From source file:com.linkedin.restli.server.ParseqTraceDebugRequestHandler.java
@Override public void handleRequest(final RestRequest request, final RequestContext context, final ResourceDebugRequestHandler resourceDebugRequestHandler, final RestLiAttachmentReader attachmentReader, final RequestExecutionCallback<RestResponse> callback) { //Find out the path coming after the "__debug" path segment String fullPath = request.getURI().getPath(); int debugSegmentIndex = fullPath.indexOf(RestLiServer.DEBUG_PATH_SEGMENT); final String debugHandlerPath = fullPath .substring(debugSegmentIndex + RestLiServer.DEBUG_PATH_SEGMENT.length() + 1); assert (debugHandlerPath.startsWith(HANDLER_ID)); //Decide whether this is a user issued debug request or a follow up static content request for tracevis html. if (debugHandlerPath.equals(TRACEVIS_PATH) || debugHandlerPath.equals(RAW_PATH)) { //Execute the request as if it was a regular rest.li request through resource debug request handler. //By using the returned execution report shape the response accordingly. //Since we are executing the request as though its a normal rest.li request, we don't have to //drain the incoming request attachments. Our concerns are only the scenarios listed in the onError() and onSuccess() //in the callback. resourceDebugRequestHandler.handleRequest(request, context, new RequestExecutionCallback<RestResponse>() { @Override//from w w w . j ava2 s . co m public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) { //Since this is eventually sent back as a success, we need to //drain any request attachments as well as any response attachments. //Normally this is done by StreamResponseCallbackAdaptor's onError, but //this is sent back as a success so we handle it here instead. if (requestAttachmentReader != null && !requestAttachmentReader.haveAllAttachmentsFinished()) { try { //Here we simply call drainAllAttachments. At this point the current callback assigned is likely the //TopLevelReaderCallback in RestLiServer. When this callback is notified that draining is completed (via //onDrainComplete()), then no action is taken (which is what is desired). // //We can go ahead and send the error back to the client while we continue to drain the //bytes in the background. Note that it could be the case that even though there is an exception thrown, //that application code could still be reading these attachments. In such a case we would not be able to call //drainAllAttachments() successfully. Therefore we handle this exception and swallow. requestAttachmentReader.drainAllAttachments(); } catch (RestLiAttachmentReaderException readerException) { //Swallow here. //It could be the case that the application code is still absorbing attachments. //We back off and send the original response to the client. If the application code is not doing this, //there is a chance for a resource leak. In such a case the framework can do nothing else. } } //Drop all attachments to send back on the ground as well. if (responseAttachments != null) { responseAttachments.getResponseAttachmentsBuilder().build().abortAllDataSources(e); } sendDebugResponse(callback, executionReport, debugHandlerPath); } @Override public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) { //Since we aren't going to send any response attachments back, we need //to drain them here. if (responseAttachments != null) { responseAttachments.getResponseAttachmentsBuilder().build().abortAllDataSources( new UnsupportedOperationException("Response attachments " + "may not be sent back for parseq trace debugging")); } sendDebugResponse(callback, executionReport, debugHandlerPath); } }); } else { //We know that the request is a static content request. So here we figure out the internal path for the //JAR resource from the request path. A request uri such as "/__debug/parseqtrace/trace.html" translates to //"/tracevis/trace.html" for the resource path. String resourcePath = debugHandlerPath.replaceFirst(HANDLER_ID, ENTRY_PATH_SEGMENT_TRACEVIS); ClassLoader currentClassLoader = getClass().getClassLoader(); InputStream resourceStream = currentClassLoader.getResourceAsStream(resourcePath); String mediaType = null; if (resourceStream != null) { mediaType = determineMediaType(resourcePath); } // If the requested file type is not supported by this debug request handler, return 404. if (mediaType == null) { callback.onError(new RestLiServiceException(HttpStatus.S_404_NOT_FOUND), null, null, null); } try { sendByteArrayAsResponse(callback, IOUtils.toByteArray(resourceStream), mediaType); } catch (IOException exception) { callback.onError(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, exception), null, null, null); } } }
From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncherFactory.java
/** * Loads the configuration from the migration config properties file. * * @param launcher the launcher to configure * @param systemName the name of the system * @param propFile the name of the prop file to configure from * @throws MigrationException if an unexpected error occurs *//*from w w w . j av a 2s.c o m*/ private void configureFromMigrationProperties(JdbcMigrationLauncher launcher, String systemName, String propFile) throws MigrationException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream(propFile); if (is != null) { try { Properties props = loadProperties(is); configureFromMigrationProperties(launcher, systemName, props); } catch (IOException e) { throw new MigrationException("Error reading in autopatch properties file", e); } finally { try { is.close(); } catch (IOException ioe) { throw new MigrationException("Error closing autopatch properties file", ioe); } } } else { throw new MigrationException("Unable to find autopatch properties file '" + propFile + "'"); } }