List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:nl.toolforge.core.util.file.MyFileUtils.java
/** * Writes <code>fileRef</code> to <code>dir</code> as <code>newFileRef</code>. <code>fileRef</code> should be available in the classpath of * <code>classLoader</code>. * * @param dir The directory to write to * @param fileRef The original filename (path) * @param newFileName The new filename/* w ww . j a v a2 s .c om*/ * @param classLoader The class loader that contains <code>fileRef</code> * * @throws IOException */ public static void writeFile(File dir, File fileRef, File newFileName, ClassLoader classLoader) throws IOException { if (dir == null || fileRef == null || newFileName == null || "".equals(newFileName) || classLoader == null) { throw new NullPointerException(""); } BufferedReader in = new BufferedReader( new InputStreamReader(classLoader.getResourceAsStream(fileRef.getPath()))); dir.mkdirs(); if (newFileName.getPath().lastIndexOf("/") > 0) { String subDir = newFileName.getPath().substring(0, newFileName.getPath().lastIndexOf("/")); new File(dir, subDir).mkdirs(); } BufferedWriter out = new BufferedWriter(new FileWriter(new File(dir, newFileName.getPath()))); String str; while ((str = in.readLine()) != null) { out.write(str); } out.close(); in.close(); }
From source file:com.mgmtp.jfunk.common.util.ResourceLoader.java
/** * Loads a resource as {@link InputStream}. * //w ww. ja v a2 s . c o m * @param resource * The resource to be loaded. If {@code baseDir} is not {@code null}, it is loaded * relative to {@code baseDir}. * @return The stream */ public static InputStream getInputStream(final File resource) throws IOException { if (resource.exists()) { return new FileInputStream(resource); } LOG.info("Could not find file '" + resource.getAbsolutePath() + "' in the file system. Trying to load it from the classpath..."); String path = FilenameUtils.separatorsToUnix(resource.getPath()); ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream(path); if (is == null) { if (path.startsWith("/")) { LOG.info("Could not find file '" + resource + " in the file system. Trying to load it from the classpath without the leading slash..."); is = cl.getResourceAsStream(path.substring(1)); } if (is == null) { // If configs are to be loaded from the classpath, we also try it directly // stripping of the config directory String configDir = new File(getConfigDir()).getName(); if (path.startsWith(configDir)) { is = cl.getResourceAsStream(StringUtils.substringAfter(path, configDir + '/')); } } if (is == null) { throw new FileNotFoundException("Could not load file '" + resource + "'"); } } return is; }
From source file:com.amalto.commons.core.utils.xpath.JXPathContextFactory.java
/** * Private implementation method - will find the implementation * class in the specified order.// ww w . j a va 2 s. c om * @param property Property name * @param defaultFactory Default implementation, if nothing else is found * * @return class name of the JXPathContextFactory */ private static String findFactory(String property, String defaultFactory) { // Use the factory ID system property first try { String systemProp = System.getProperty(property); if (systemProp != null) { if (debug) { System.err.println("JXPath: found system property" + systemProp); } return systemProp; } } catch (SecurityException se) { //NOPMD // Ignore } // try to read from $java.home/lib/xml.properties try { String javah = System.getProperty("java.home"); String configFile = javah + File.separator + "lib" + File.separator + "jxpath.properties"; File f = new File(configFile); if (f.exists()) { Properties props = new Properties(); FileInputStream fis = new FileInputStream(f); try { props.load(fis); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { //NOPMD //swallow } } } String factory = props.getProperty(property); if (factory != null) { if (debug) { System.err.println("JXPath: found java.home property " + factory); } return factory; } } } catch (IOException ex) { if (debug) { ex.printStackTrace(); } } String serviceId = "META-INF/services/" + property; // try to find services in CLASSPATH try { ClassLoader cl = JXPathContextFactory.class.getClassLoader(); InputStream is = null; if (cl == null) { is = ClassLoader.getSystemResourceAsStream(serviceId); } else { is = cl.getResourceAsStream(serviceId); } if (is != null) { if (debug) { System.err.println("JXPath: found " + serviceId); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String factory = null; try { factory = rd.readLine(); } finally { try { rd.close(); } catch (IOException e) { //NOPMD //swallow } } if (factory != null && !"".equals(factory)) { if (debug) { System.err.println("JXPath: loaded from services: " + factory); } return factory; } } } catch (Exception ex) { if (debug) { ex.printStackTrace(); } } return defaultFactory; }
From source file:com.atlassw.tools.eclipse.checkstyle.builder.PackageNamesLoader.java
/** * Returns the default list of package names. * //from ww w . jav a2 s . c o m * @param aClassLoader the class loader that gets the default package names. * @return the default list of package names. * @throws CheckstylePluginException if an error occurs. */ public static List<String> getPackageNames(ClassLoader aClassLoader) throws CheckstylePluginException { if (sPackages == null) { sPackages = new ArrayList<String>(); PackageNamesLoader nameLoader = null; try { nameLoader = new PackageNamesLoader(); final InputStream stream = aClassLoader.getResourceAsStream(DEFAULT_PACKAGES); InputSource source = new InputSource(stream); nameLoader.parseInputSource(source); } catch (ParserConfigurationException e) { CheckstylePluginException.rethrow(e, "unable to parse " + DEFAULT_PACKAGES); //$NON-NLS-1$ } catch (SAXException e) { CheckstylePluginException.rethrow(e, "unable to parse " + DEFAULT_PACKAGES + " - " //$NON-NLS-1$ //$NON-NLS-2$ + e.getMessage()); } catch (IOException e) { CheckstylePluginException.rethrow(e, "unable to read " + DEFAULT_PACKAGES); //$NON-NLS-1$ } // load custom package files try { Enumeration<URL> packageFiles = aClassLoader.getResources("checkstyle_packages.xml"); //$NON-NLS-1$ while (packageFiles.hasMoreElements()) { URL aPackageFile = packageFiles.nextElement(); InputStream iStream = null; try { iStream = new BufferedInputStream(aPackageFile.openStream()); InputSource source = new InputSource(iStream); nameLoader.parseInputSource(source); } catch (SAXException e) { LimyEclipsePluginUtils.log(e); // CheckstyleLog.log(e, "unable to parse " + aPackageFile.toExternalForm() //$NON-NLS-1$ // + " - " + e.getLocalizedMessage()); //$NON-NLS-1$ } catch (IOException e) { LimyEclipsePluginUtils.log(e); // CheckstyleLog.log(e, "unable to read " + aPackageFile.toExternalForm()); //$NON-NLS-1$ } finally { IOUtils.closeQuietly(iStream); } } } catch (IOException e1) { CheckstylePluginException.rethrow(e1); } } return sPackages; }
From source file:com.ikon.util.ReportUtils.java
/** * Generates a report based on a JDBC connection (from file) *//*from w ww .j a va 2s. c o m*/ public static OutputStream generateReport(OutputStream out, String fileReport, Map<String, Object> params, int outputType, Connection con) throws Exception { if (!JasperCharged.containsKey(fileReport)) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { JasperReport jasperReport = JasperCompileManager.compileReport(cl.getResourceAsStream(fileReport)); JasperCharged.put(fileReport, jasperReport); } catch (Exception e) { throw new Exception("Compiling error: " + e.getMessage()); } } try { JasperReport jasperReport = (JasperReport) JasperCharged.get(fileReport); JasperPrint print = JasperFillManager.fillReport(jasperReport, params, con); export(out, outputType, print); } catch (JRException je) { throw new JRException("Error generating report", je); } return out; }
From source file:com.ikon.util.ReportUtils.java
/** * Generates a report based on a map collection (from file) *///from w ww . jav a 2s . co m public static OutputStream generateReport(OutputStream out, String fileReport, Map<String, Object> params, int outputType, Collection<Map<String, Object>> list) throws Exception { if (!JasperCharged.containsKey(fileReport)) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { JasperReport jasperReport = JasperCompileManager.compileReport(cl.getResourceAsStream(fileReport)); JasperCharged.put(fileReport, jasperReport); } catch (Exception e) { throw new Exception("Compiling error: " + e.getMessage()); } } try { JasperReport jasperReport = (JasperReport) JasperCharged.get(fileReport); JasperPrint print = JasperFillManager.fillReport(jasperReport, params, new JRMapCollectionDataSource(list)); export(out, outputType, print); } catch (JRException je) { throw new JRException("Error generating report", je); } return out; }
From source file:edu.cwru.jpdg.Javac.java
/** * loads a java file from the resources directory. Give the fully * qualified name of the java file. eg. for: * * source/test/resources/java/test/parse/HelloWorld.java * * give://from w ww . jav a 2s . co m * * test.parse.HelloWorld */ public static String load(String full_name) { ClassLoader loader = Javac.class.getClassLoader(); String[] split = StringUtils.split(full_name, "."); String name = split[split.length - 1]; String slash_name = StringUtils.join(split, pathsep); String resource = Paths.get("java").resolve(slash_name + ".java").toString(); InputStream ci = loader.getResourceAsStream(resource); BufferedReader bi = new BufferedReader(new InputStreamReader(ci)); List<String> lines = new ArrayList<String>(); String line; try { while ((line = bi.readLine()) != null) { lines.add(line); } } catch (IOException e) { throw new RuntimeException(e.getMessage()); } lines.add(line); return StringUtils.join(lines, "\n"); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java
private static void loadApplicationPropertiesFile() { // Set the projects properties. // First look for a system property pointing to a project properties file. // This value can be either a file path, file protocol (e.g. - file:/path/to/file), // or a URL (http://some/server/file). // If this value either does not exist or is not valid, the default // file that comes with this application will be used for initialization. String environmentProjectPropsFile = System.getProperty(ApplicationConstants.ENV_PROJECT_PROPS); logger.info("Have {} from environment: {}", ApplicationConstants.PROJECT_PROPS, environmentProjectPropsFile); URI projectPropsUri = null;/*w ww . j av a 2 s .c o m*/ if (environmentProjectPropsFile != null) { try { projectPropsUri = new URI(environmentProjectPropsFile); // properties file needs a scheme in the URI so convert to file if necessary. if (null == projectPropsUri.getScheme()) { File projectProperties = new File(environmentProjectPropsFile); if (projectProperties.exists() && projectProperties.isFile()) { projectPropsUri = projectProperties.toURI(); } else { // No scheme and not a file - yikes!!! Let's bail and // use fall-back file. projectPropsUri = null; throw new URISyntaxException(environmentProjectPropsFile, "Not a valid file"); } } } catch (URISyntaxException e) { // fall back to default file logger.error("Unable to load properties file: {} -- reason: {}", environmentProjectPropsFile, e.getReason()); logger.error("Falling back to default {} file: {}", ApplicationConstants.PROJECT_PROPS, ApplicationConstants.PROJECT_PROPS); } } applicationProps = new Properties(); // load properties if environment value set if (projectPropsUri != null) { File envPropFile = new File(projectPropsUri); if (envPropFile.exists() && envPropFile.isFile() && envPropFile.canRead()) { Reader reader; try { reader = new FileReader(envPropFile); logger.info("About to load {} from environment: {}", ApplicationConstants.PROJECT_PROPS, envPropFile.getAbsolutePath()); applicationProps.load(reader); logger.info("Success -- loaded properties file."); } catch (IOException e) { logger.error("Could not load environment properties file: {}", projectPropsUri, e); // set URI back to null so default prop file loaded projectPropsUri = null; } } } if (projectPropsUri == null) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { InputStream resourceStream = loader.getResourceAsStream(ApplicationConstants.PROJECT_PROPS); applicationProps.load(resourceStream); logger.info("loaded default applicationProps: "); } catch (IOException e) { logger.error("Could not load properties file: {}", ApplicationConstants.PROJECT_PROPS, e); // couldn't load default properties so bail... throw new RuntimeException("Couldn't load an applications properties file.", e); } } }
From source file:info.extensiblecatalog.OAIToolkit.utils.ApplInfo.java
/** * start logging/* w w w. ja v a 2 s . c o m*/ */ public static void initLogging(String rootDir, String logDir, String propertyFileName) throws FileNotFoundException { ClassLoader cloader = ApplInfo.class.getClassLoader(); InputStream logProps = cloader.getResourceAsStream(propertyFileName); if (null == logProps) { File propertyFile = new File(rootDir, propertyFileName); if (propertyFile.exists()) { try { System.out.println(" log4j property file: " + propertyFile.getAbsoluteFile()); logProps = new FileInputStream(propertyFile); } catch (FileNotFoundException e) { System.out.println("Exception" + e); throw e; } } } if (null != logProps) { LoggingParameters logParams = new LoggingParameters(logDir); Logging.initLogging(logParams, logProps); } }
From source file:net.semanticmetadata.lire.utils.FileUtils.java
/** * Used to access a file in the resource folder. * @param resourceName the path to the file, eg. "data/files.lst" * @return//from w ww. j a va2s. c om */ public static InputStream getInputStreamFromResources(String resourceName) { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); return classloader.getResourceAsStream(resourceName); }