Example usage for java.lang ClassLoader getResourceAsStream

List of usage examples for java.lang ClassLoader getResourceAsStream

Introduction

In this page you can find the example usage for java.lang ClassLoader getResourceAsStream.

Prototype

public InputStream getResourceAsStream(String name) 

Source Link

Document

Returns an input stream for reading the specified resource.

Usage

From source file:org.apache.click.service.ClickResourceService.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  w  w . j  av  a2 s  .c o m*/
private byte[] getClasspathResourceData(String resourcePath) throws IOException {

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    InputStream inputStream = classLoader.getResourceAsStream(resourcePath);
    if (inputStream == null) {
        inputStream = getClass().getResourceAsStream(resourcePath);
    }

    try {

        if (inputStream != null) {
            return IOUtils.toByteArray(inputStream);
        } else {
            return null;
        }

    } finally {
        ClickUtils.close(inputStream);
    }
}

From source file:arxiv.xml.XMLParser.java

/**
 * Constructs a new XML parser by initializing the JAXB unmarshaller and setting up the XML validation.
 *
 * @throws HarvesterError if there are any problems
 *//*from  w w w  . j  a va 2 s.  co  m*/
public XMLParser() {
    try {
        unmarshaller = JAXBContext.newInstance("org.openarchives.oai._2:org.arxiv.oai.arxivraw")
                .createUnmarshaller();
    } catch (JAXBException e) {
        throw new HarvesterError("Error creating JAXB unmarshaller", e);
    }

    ClassLoader classLoader = this.getClass().getClassLoader();
    List<Source> schemaSources = Lists.newArrayList();

    schemaSources.add(new StreamSource(classLoader.getResourceAsStream("OAI-PMH.xsd")));
    schemaSources.add(new StreamSource(classLoader.getResourceAsStream("arXivRaw.xsd")));

    try {
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        unmarshaller.setSchema(schema);
    } catch (SAXException e) {
        throw new HarvesterError("Error creating validation schema", e);
    }
}

From source file:com.icesoft.applications.faces.auctionMonitor.stubs.StubServer.java

/**
 * Method used to find and read an item properties file The item values will
 * then be loaded into the global auction state In the getSearchResults
 * method, these values will be converted into a list of ItemTypes
 */// w w  w.jav a 2s  .com
private void loadItemList() {
    // Determine the location of the property file
    Properties props = new Properties();
    try {
        ClassLoader cl = this.getClass().getClassLoader();
        props = new Properties();
        props.load(cl.getResourceAsStream(ITEM_PROPERTIES_RESOURCE));
    } catch (IOException e) {
        if (log.isErrorEnabled()) {
            log.error("Property file \'" + ITEM_PROPERTIES_RESOURCE + "\' could not be found because of " + e);
        }
    }

    // Loop through each property and put the values in the global auction state
    int itemCounter = 0;
    String itemPrefix, idValue, key;
    while (true) {
        itemPrefix = ITEM + itemCounter + ".";
        idValue = props.getProperty(itemPrefix + ID);
        key = idValue + ".";

        // No more item sets were found, so break the loop
        if (idValue == null) {
            break;
        }

        // Add the core values for the current item
        AuctionState.getAuctionMap().put(key + ID, idValue);
        AuctionState.getAuctionMap().put(key + BID_COUNT,
                new Integer(props.getProperty(itemPrefix + BID_COUNT)));
        AuctionState.getAuctionMap().put(key + INITIAL_BID_COUNT,
                new Integer(props.getProperty(itemPrefix + BID_COUNT)));
        AuctionState.getAuctionMap().put(key + CURRENCY, props.getProperty(itemPrefix + CURRENCY));
        AuctionState.getAuctionMap().put(key + DESCRIPTION, props.getProperty(itemPrefix + DESCRIPTION));
        AuctionState.getAuctionMap().put(key + IMAGE, props.getProperty(itemPrefix + IMAGE));
        AuctionState.getAuctionMap().put(key + LOCATION, props.getProperty(itemPrefix + LOCATION));
        AuctionState.getAuctionMap().put(key + PRICE, new Double(props.getProperty(itemPrefix + PRICE)));
        AuctionState.getAuctionMap().put(key + INITIAL_PRICE,
                new Double(props.getProperty(itemPrefix + PRICE)));
        AuctionState.getAuctionMap().put(key + SITE, props.getProperty(itemPrefix + SITE));
        AuctionState.getAuctionMap().put(key + SELLER, props.getProperty(itemPrefix + SELLER));
        AuctionState.getAuctionMap().put(key + TITLE, props.getProperty(itemPrefix + TITLE));
        AuctionState.getAuctionMap().put(key + EXPIRESINDAYS, props.getProperty(itemPrefix + EXPIRESINDAYS));

        // Calculate and add the expiry date
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,
                Integer.parseInt((String) AuctionState.getAuctionMap().get(key + EXPIRESINDAYS)));

        AuctionState.getAuctionMap().put(key + END_TIME, calendar);

        // Update the running total of number of items
        itemCounter++;
    }
}

From source file:io.github.mikesaelim.arxivoaiharvester.xml.XMLParser.java

/**
 * Constructs a new XML parser by initializing the JAXB unmarshaller and setting up the XML validation.
 *
 * @throws HarvesterError if there are any problems
 *///from  ww w  . j  a  v a 2s.  c o  m
public XMLParser() {
    try {
        unmarshaller = JAXBContext.newInstance("org.openarchives.oai._2:org.arxiv.oai.arxivraw")
                .createUnmarshaller();
    } catch (JAXBException e) {
        throw new HarvesterError("Error creating JAXB unmarshaller", e);
    }

    ClassLoader classLoader = this.getClass().getClassLoader();
    List<Source> schemaSources = Lists.newArrayList(
            new StreamSource(classLoader.getResourceAsStream("OAI-PMH.xsd")),
            new StreamSource(classLoader.getResourceAsStream("arXivRaw.xsd")));
    try {
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        unmarshaller.setSchema(schema);
    } catch (SAXException e) {
        throw new HarvesterError("Error creating validation schema", e);
    }
}

From source file:com.haulmont.cuba.uberjar.ServerRunner.java

protected int getDefaultWebPort() {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {//  w  ww  . ja va  2 s  .com
        Properties properties = new Properties();
        properties.load(classLoader.getResourceAsStream(getPropertiesForPort(classLoader)));
        String webPort = (String) properties.get("cuba.webPort");
        if (webPort != null && !webPort.isEmpty()) {
            return Integer.parseInt(webPort);
        }
    } catch (Exception e) {
        System.out.println("Error while parsing port, use default port");
    }
    return 8080;
}

From source file:ingest.inspect.PointCloudInspector.java

@Override
public DataResource inspect(DataResource dataResource, boolean host) throws DataInspectException,
        AmazonClientException, InvalidInputException, IOException, FactoryException {
    logger.log(String.format("Begin parsing Point Cloud for Data %s", dataResource.getDataId()),
            Severity.INFORMATIONAL,
            new AuditElement(INGEST, "beginParsingPointCloud", dataResource.getDataId()));

    // Load point cloud post request template
    ClassLoader classLoader = getClass().getClassLoader();
    String pointCloudTemplate = null;
    InputStream templateStream = null;
    try {/*from  w ww .  j  a  v a  2s .c  o  m*/
        templateStream = classLoader
                .getResourceAsStream("templates" + File.separator + "pointCloudRequest.json");
        pointCloudTemplate = IOUtils.toString(templateStream);
    } finally {
        if (templateStream != null) {
            templateStream.close();
        }
    }

    // Obtain File URL from AWS S3 Bucket
    FileAccessFactory fileFactory = ingestUtilities.getFileFactoryForDataResource(dataResource);
    FileLocation fileLocation = ((PointCloudDataType) dataResource.getDataType()).getLocation();
    String awsS3Url = fileFactory.getFileUri(fileLocation);

    // Inject URL into the Post Payload
    String payloadBody = String.format(pointCloudTemplate, awsS3Url);

    // Attempt to populate Spatial metadata for the Point Cloud by pointing
    // to the Point Cloud metadata service.
    SpatialMetadata spatialMetadata = new SpatialMetadata();
    try {
        // Post payload to point cloud endpoint for the metadata response
        PointCloudResponse pointCloudResponse = postPointCloudTemplate(POINT_CLOUD_ENDPOINT, payloadBody);

        // Set the Metadata
        spatialMetadata.setMaxX(pointCloudResponse.getMaxx());
        spatialMetadata.setMaxY(pointCloudResponse.getMaxy());
        spatialMetadata.setMaxZ(pointCloudResponse.getMaxz());
        spatialMetadata.setMinX(pointCloudResponse.getMinx());
        spatialMetadata.setMinY(pointCloudResponse.getMiny());
        spatialMetadata.setMinZ(pointCloudResponse.getMinz());
        spatialMetadata.setCoordinateReferenceSystem(pointCloudResponse.getSpatialreference());

        String formattedSpatialreference = pointCloudResponse.getSpatialreference().replace("\\\"", "\"");
        // Decode CoordinateReferenceSystem and parse EPSG code
        CoordinateReferenceSystem worldCRS = CRS.parseWKT(formattedSpatialreference);
        spatialMetadata.setEpsgCode(CRS.lookupEpsgCode(worldCRS, true));

        // Populate the projected EPSG:4326 spatial metadata
        populateSpatialMetadata(spatialMetadata, dataResource.getDataId());
    } catch (Exception exception) {
        String error = String.format("Error populating Spatial Metadata for %s Point Cloud located at %s: %s",
                dataResource.getDataId(), awsS3Url, exception.getMessage());
        logger.log(error, Severity.WARNING);
        LOG.error(error, exception);
    }

    // Set the DataResource Spatial Metadata
    dataResource.spatialMetadata = spatialMetadata;

    logger.log(String.format("Completed parsing Point Cloud for Data %s", dataResource.getDataId()),
            Severity.INFORMATIONAL,
            new AuditElement(INGEST, "completeParsingPointCloud", dataResource.getDataId()));

    return dataResource;
}

From source file:nu.studer.idea.errorreporting.PluginErrorReportSubmitter.java

private void queryPropertiesFile(@NotNull PluginDescriptor pluginDescriptor, @NotNull Properties properties) {
    ClassLoader loader = pluginDescriptor.getPluginClassLoader();
    InputStream stream = loader.getResourceAsStream(ERROR_SUBMITTER_PROPERTIES_PATH);
    if (stream != null) {
        LOGGER.debug("Reading errorReporter.properties from file system: " + ERROR_SUBMITTER_PROPERTIES_PATH);

        try {//from  w w w . ja  v a2  s  .c o m
            properties.load(stream);
        } catch (Exception e) {
            LOGGER.info("Could not read in errorReporter.properties from file system", e);
        }
    }
}

From source file:com.krawler.esp.utils.PropsLoader.java

public static Properties loadProperties(String name, ClassLoader loader) {
    if (name == null)
        throw new IllegalArgumentException("null input: name");

    if (name.startsWith("/"))
        name = name.substring(1);// ww  w.j a va 2  s.c  o  m

    if (name.endsWith(SUFFIX))
        name = name.substring(0, name.length() - SUFFIX.length());

    Properties result = null;

    InputStream in = null;
    try {
        if (loader == null)
            loader = ClassLoader.getSystemClassLoader();

        if (LOAD_AS_RESOURCE_BUNDLE) {
            name = name.replace('/', '.');
            // Throws MissingResourceException on lookup failures:
            final ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault(), loader);

            result = new Properties();
            for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
                final String key = (String) keys.nextElement();
                final String value = rb.getString(key);

                result.put(key, value);
            }
        } else {
            name = name.replace('.', '/');

            if (!name.endsWith(SUFFIX))
                name = name.concat(SUFFIX);

            // Returns null on lookup failures:
            in = loader.getResourceAsStream(name);
            if (in != null) {
                result = new Properties();
                result.load(in); // Can throw IOException
            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        result = null;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Throwable ignore) {
                logger.warn(ignore.getMessage(), ignore);
            }
    }

    if (THROW_ON_LOAD_FAILURE && (result == null)) {
        throw new IllegalArgumentException("could not load [" + name + "]" + " as "
                + (LOAD_AS_RESOURCE_BUNDLE ? "a resource bundle" : "a classloader resource"));
    }

    return result;
}

From source file:io.vertx.lang.js.JSVerticleFactory.java

private boolean hasEngines(ClassLoader loader) {
    StringBuilder buf = new StringBuilder();
    BufferedReader br = new BufferedReader(new InputStreamReader(loader.getResourceAsStream("package.json")));
    br.lines().forEach(line -> buf.append(line));
    JsonObject json = new JsonObject(buf.toString());
    return json.containsKey("engines") && json.getJsonObject("engines").containsKey("node");
}

From source file:org.openmrs.module.kenyaemr.metadata.MetadataManager.java

/**
 * Checks whether the given version of the MDS package has been installed yet, and if not, install it
 * @param groupUuid the package group UUID
 * @param filename the package filename/*from w  w  w  . ja v  a2s .c  o  m*/
 * @param loader the class loader to use for loading the packages (null to use the default)
 * @return whether any changes were made to the db
 * @throws IOException
 */
protected static boolean installMetadataPackageIfNecessary(String groupUuid, String filename,
        ClassLoader loader) throws IOException {
    try {
        Matcher matcher = Pattern.compile("[\\w/-]+-(\\d+).zip").matcher(filename);
        if (!matcher.matches())
            throw new RuntimeException("Filename must match PackageNameWithNoSpaces-X.zip");
        Integer version = Integer.valueOf(matcher.group(1));

        ImportedPackage installed = Context.getService(MetadataSharingService.class)
                .getImportedPackageByGroup(groupUuid);
        if (installed != null && installed.getVersion() >= version) {
            log.info("Metadata package " + filename + " is already installed with version "
                    + installed.getVersion());
            return false;
        }

        if (loader == null) {
            loader = MetadataManager.class.getClassLoader();
        }

        if (loader.getResource(filename) == null) {
            throw new RuntimeException("Cannot find " + filename + " for group " + groupUuid);
        }

        PackageImporter metadataImporter = MetadataSharing.getInstance().newPackageImporter();
        metadataImporter.setImportConfig(ImportConfig.valueOf(ImportMode.MIRROR));
        metadataImporter.loadSerializedPackageStream(loader.getResourceAsStream(filename));
        metadataImporter.importPackage();
        return true;
    } catch (Exception ex) {
        log.error("Failed to install metadata package " + filename, ex);
        return false;
    }
}