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:minium.script.rhinojs.RhinoEngine.java

public <T> RhinoEngine(final RhinoProperties properties) {
    this.executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override/*from  w w w  .  j a  va  2  s .  co  m*/
        public Thread newThread(Runnable r) {
            Preconditions.checkState(executionThread == null, "Only one thread is supported");
            executionThread = FACTORY.newThread(r);
            return executionThread;
        }
    });

    // this ensures a single thread for this engine
    scope = runWithContext(new RhinoCallable<Scriptable, RuntimeException>() {
        @Override
        protected Scriptable doCall(Context cx, Scriptable scope) {
            try {
                Global global = new Global(cx);
                RequireProperties require = properties.getRequire();
                if (require != null) {
                    List<String> modulePathURIs = getModulePathURIs(require);
                    LOGGER.debug("Module paths: {}", modulePathURIs);
                    global.installRequire(cx, modulePathURIs, require.isSandboxed());
                }
                ClassLoader classloader = Thread.currentThread().getContextClassLoader();
                // we need to load compat/timeout.js because rhino does not have setTimeout, setInterval, etc.
                cx.evaluateReader(global,
                        new InputStreamReader(classloader.getResourceAsStream("compat/timeout.js")),
                        "compat/timeout.js", 1, null);
                return global;
            } catch (IOException e) {
                throw Throwables.propagate(e);
            }
        }
    });
}

From source file:access.deploy.Deployer.java

/**
 * Deploys a PostGIS Table resource to GeoServer. This will create a new GeoServer layer that will reference the
 * PostGIS table.//from  w ww  .  j a v a 2 s . co  m
 * 
 * PostGIS tables can be created via the Ingest process by, for instance, ingesting a Shapefile or a WFS into the
 * Database.
 * 
 * @param dataResource
 *            The DataResource to deploy.
 * @return The Deployment
 * @throws GeoServerException
 * @throws IOException
 */
private Deployment deployPostGisTable(DataResource dataResource) throws GeoServerException, IOException {
    // Create the JSON Payload for the Layer request to GeoServer
    ClassLoader classLoader = getClass().getClassLoader();
    InputStream templateStream = null;
    String featureTypeRequestBody = null;
    try {
        templateStream = classLoader
                .getResourceAsStream("templates" + File.separator + "featureTypeRequest.xml");
        featureTypeRequestBody = IOUtils.toString(templateStream);
    } catch (Exception exception) {
        LOGGER.error("Error reading GeoServer Template.", exception);
    } finally {
        try {
            if (templateStream != null) {
                templateStream.close();
            }
        } catch (Exception exception) {
            LOGGER.error("Error closing GeoServer Template Stream.", exception);
        }
    }

    // Get the appropriate Table Name from the DataResource
    String tableName = null;
    if (dataResource.getDataType() instanceof ShapefileDataType) {
        tableName = ((ShapefileDataType) dataResource.getDataType()).getDatabaseTableName();
    } else if (dataResource.getDataType() instanceof PostGISDataType) {
        tableName = ((PostGISDataType) dataResource.getDataType()).getTable();
    } else if (dataResource.getDataType() instanceof GeoJsonDataType) {
        tableName = ((GeoJsonDataType) dataResource.getDataType()).databaseTableName;
    }

    // Inject the Metadata from the Data Resource into the Payload
    String requestBody = String.format(featureTypeRequestBody, tableName, tableName, tableName,
            dataResource.getSpatialMetadata().getEpsgString(), "EPSG:4326");

    // Execute the POST to GeoServer to add the FeatureType
    HttpStatus statusCode = postGeoServerFeatureType(ADD_LAYER_ENDPOINT, requestBody);

    // Ensure the Status Code is OK
    if (statusCode != HttpStatus.CREATED) {
        pzLogger.log(
                String.format(
                        "Failed to Deploy PostGIS Table name %s for Resource %s to GeoServer. HTTP Code: %s",
                        tableName, dataResource.getDataId(), statusCode),
                Severity.ERROR,
                new AuditElement(ACCESS, "failedToCreatePostGisTable", dataResource.getDataId()));
        throw new GeoServerException(
                "Failed to Deploy to GeoServer; the Status returned a non-OK response code: " + statusCode);
    }

    // Create a new Deployment for this Resource
    String deploymentId = uuidFactory.getUUID();
    String capabilitiesUrl = String.format("%s%s", accessUtilities.getGeoServerBaseUrl(), CAPABILITIES_URL);

    pzLogger.log(String.format("Created PostGIS Table for Resource %s", dataResource.getDataId()),
            Severity.INFORMATIONAL, new AuditElement(ACCESS, "createPostGisTable", dataResource.getDataId()));

    return new Deployment(deploymentId, dataResource.getDataId(), accessUtilities.getGeoServerBaseUrl(), null,
            tableName, capabilitiesUrl);
}

From source file:net.community.chest.gitcloud.facade.AbstractEnvironmentInitializer.java

protected void extractConfigFiles(File confDir, String resPrefix, Collection<String> names) {
    if (ConfigUtils.verifyFolderProperty(ConfigUtils.CONF_DIR_NAME, confDir)) {
        logger.info("extractConfigFiles(" + resPrefix + ") - created " + ExtendedFileUtils.toString(confDir));
    }/*from ww w.  j  a va 2 s .c  o m*/

    ClassLoader cl = ExtendedClassUtils.getDefaultClassLoader(getClass());
    for (String fileName : names) {
        File targetFile = new File(confDir, fileName);
        if (targetFile.exists()) {
            logger.info("extractConfigFiles(" + fileName + ")[" + resPrefix + "] skip - already exists: "
                    + ExtendedFileUtils.toString(targetFile));
            continue;
        }

        try {
            long copyLength = extractConfigFile(cl.getResourceAsStream(resPrefix + "/" + fileName), targetFile,
                    getWorkBuf(ExtendedIOUtils.DEFAULT_BUFFER_SIZE_VALUE));
            if (copyLength <= 0L) {
                throw new StreamCorruptedException("Bad copy count: " + copyLength);
            }

            logger.info("extractConfigFiles(" + resPrefix + ")[" + fileName + "] " + copyLength + " bytes: "
                    + ExtendedFileUtils.toString(targetFile));
        } catch (IOException e) {
            RuntimeException thrown = new RuntimeException(
                    "extractConfigFiles(" + resPrefix + ")[" + fileName + "]" + " failed ("
                            + e.getClass().getSimpleName() + ")" + " to extract contents: " + e.getMessage(),
                    e);
            logger.warn(thrown.getMessage(), e);
            throw thrown;
        }
    }
}

From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java

@Test
public void testJettyWorkingBinaryResponse() throws Exception {

    ClassLoader loader = ClientDriverSuccessTest.class.getClassLoader();

    byte[] binaryContent = IOUtils.toByteArray(loader.getResourceAsStream("example-binary.zip"));
    InputStream stream = new ByteArrayInputStream(binaryContent);

    String baseUrl = driver.getBaseUrl();
    driver.addExpectation(onRequestTo("/blah2"), giveResponseAsBytes(stream, "application/octet-stream"));

    HttpClient client = new DefaultHttpClient();
    HttpGet getter = new HttpGet(baseUrl + "/blah2");
    HttpResponse response = client.execute(getter);

    assertThat(response.getStatusLine().getStatusCode(), is(200));
    assertThat(IOUtils.toByteArray(response.getEntity().getContent()), is(binaryContent));

}

From source file:com.hazelcast.config.XmlConfigSchemaLocationTest.java

@Test
public void testSchemaLocationsExist() throws Exception {
    assumeTls12Available();// w ww  . j  a  v a  2 s .c o m

    ResourcesScanner scanner = new ResourcesScanner();
    Reflections reflections = new Reflections(scanner);
    Set<String> resources = reflections.getResources(Pattern.compile(".*\\.xml"));
    ClassLoader classLoader = getClass().getClassLoader();
    for (String resource : resources) {
        URL resourceUrl = classLoader.getResource(resource);
        String protocol = resourceUrl.getProtocol();

        // do not validate schemas from JARs (libraries). we are interested in local project files only.
        if (protocol.startsWith("jar")) {
            continue;
        }

        InputStream stream = null;
        try {
            stream = classLoader.getResourceAsStream(resource);
            validateSchemaLocationUrl(stream, resource);
        } finally {
            IOUtil.closeResource(stream);
        }
    }
}

From source file:org.apache.struts.util.PropertyMessageResources.java

/**
 * Load the messages associated with the specified Locale key.  For this
 * implementation, the <code>config</code> property should contain a fully
 * qualified package and resource name, separated by periods, of a series
 * of property resources to be loaded from the class loader that created
 * this PropertyMessageResources instance.  This is exactly the same name
 * format you would use when utilizing the <code>java.util.PropertyResourceBundle</code>
 * class.//from   w  w w .  j av  a 2s  . com
 *
 * @param localeKey Locale key for the messages to be retrieved
 */
protected synchronized void loadLocale(String localeKey) {
    if (log.isTraceEnabled()) {
        log.trace("loadLocale(" + localeKey + ")");
    }

    // Have we already attempted to load messages for this locale?
    if (locales.get(localeKey) != null) {
        return;
    }

    locales.put(localeKey, localeKey);

    // Set up to load the property resource for this locale key, if we can
    String name = config.replace('.', '/');

    if (localeKey.length() > 0) {
        name += ("_" + localeKey);
    }

    name += ".properties";

    InputStream is = null;
    Properties props = new Properties();

    // Load the specified property resource
    if (log.isTraceEnabled()) {
        log.trace("  Loading resource '" + name + "'");
    }

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

    if (classLoader == null) {
        classLoader = this.getClass().getClassLoader();
    }

    is = classLoader.getResourceAsStream(name);

    if (is != null) {
        try {
            props.load(is);
        } catch (IOException e) {
            log.error("loadLocale()", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("loadLocale()", e);
            }
        }
        if (log.isTraceEnabled()) {
            log.trace("  Loading resource completed");
        }
    } else {
        if (log.isWarnEnabled()) {
            log.warn("  Resource " + name + " Not Found.");
        }
    }

    // Copy the corresponding values into our cache
    if (props.size() < 1) {
        return;
    }

    synchronized (messages) {
        Iterator names = props.keySet().iterator();

        while (names.hasNext()) {
            String key = (String) names.next();

            if (log.isTraceEnabled()) {
                log.trace("  Saving message key '" + messageKey(localeKey, key));
            }

            messages.put(messageKey(localeKey, key), props.getProperty(key));
        }
    }
}

From source file:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

private BrokerManager broker() {
    mutex.lock();//from  w w  w. j  av  a  2 s .c  o  m
    try {
        if (__broker == null) {
            BrokerService brokerService = null;
            if (CONFIG_MANAGER.isBrokerEmbedded()) {
                try {
                    // check that only one instance is running per host
                    final ClassLoader resourceLoader = Thread.currentThread().getContextClassLoader();
                    final Properties properties = new Properties();
                    properties.load(resourceLoader.getResourceAsStream(ACTIVEMQ_PROPERTIES));
                    final int port = Integer
                            .parseInt(properties.getProperty(ACTIVEMQ_PORT_PROPERTY, ACTIVEMQ_DEFAULT_PORT));
                    if (isPortAvailable(port)) {
                        brokerService = createBroker(new URI("xbean:activemq.xml"), true);
                        LOGGER.info("New broker service created");
                    } else {
                        LOGGER.info("Port " + port + " unavailable broker service will not be started");
                    }
                } catch (Exception e) {
                    LOGGER.warn("Failed to create broker service", e);
                }
            }
            final String brokers = Joiner.on(",").skipNulls()
                    .join(from(CONFIG_MANAGER.getMessageBrokers()).transform(new Function<String, String>() {
                        @Override
                        public String apply(final String host) {
                            final String host2 = trimToNull(host);
                            return isNotBlank(host2) ? "nio://" + host2 : null;
                        }
                    }).filter(notNull()).toList());
            __broker = BrokerManager.builder().broker(brokerService).connFactory(new ActiveMQConnectionFactory(
                    isNotBlank(brokers) ? "failover://(" + brokers + ")?randomize=true" : DEFAULT_BROKER_URL))
                    .build();
        }
        return __broker;
    } finally {
        mutex.unlock();
    }
}

From source file:org.alfresco.dataprep.SiteService.java

private String readContentRmSite() {
    ClassLoader classLoader = getClass().getClassLoader();
    InputStream input = classLoader.getResourceAsStream("contentRMSite.xml");
    try {/*from   w w w.  ja va  2s.c  o m*/
        return IOUtils.toString(input);
    } catch (IOException e) {
        throw new RuntimeException("Unable to read contentRMSite.xml ", e);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:com.agilejava.maven.docbkx.GeneratorMojo.java

/**
 * Generate the source code of the plugin supporting the {@link #type}.
 *
 * @throws MojoExecutionException//from  www . j a  va  2 s . c  om
 *             If we fail to generate the source code.
 */
private void generateSourceCode() throws MojoExecutionException {
    File sourcesDir = new File(targetDirectory, getPackageName().replace('.', '/'));

    try {
        FileUtils.forceMkdir(sourcesDir);
    } catch (IOException ioe) {
        throw new MojoExecutionException("Can't create directory for sources.", ioe);
    }

    ClassLoader loader = this.getClass().getClassLoader();
    InputStream in = loader.getResourceAsStream("plugins.stg");
    Reader reader = new InputStreamReader(in, Charset.forName(encoding));
    StringTemplateGroup group = new StringTemplateGroup(reader);
    StringTemplate template = group.getInstanceOf("plugin");
    File targetFile = new File(sourcesDir, getClassName() + ".java");
    Specification specification = null;

    try {
        specification = createSpecification();
        getLog().info("Number of parameters: " + specification.getParameters().size());
        template.setAttribute("spec", specification);
        FileUtils.writeStringToFile(targetFile, template.toString(), encoding);
    } catch (IOException ioe) {
        if (specification == null) {
            throw new MojoExecutionException("Failed to read parameters.", ioe);
        } else {
            throw new MojoExecutionException("Failed to create " + targetFile + ".", ioe);
        }
    }

    project.addCompileSourceRoot(targetDirectory.getAbsolutePath());
}

From source file:org.alfresco.reporting.ReportingHelper.java

/**
 * Reads external properties file. The properties in this file will override 
 * the default mapping of individual Alfresco PROPERTY types into SQL column  
 * definitions ** on a per-property basis**
 * (One often knows a zip code is d:text, but never more than 8 charaters, so 
 * VARCHAR(8) will do). The total length of the row (sum of the column lengths) 
 * can never be more than 65535 bytes. And i guess UTF-8 makes a reservation of 
 * 4 bytes per character/*from   w w  w.  jav a 2s .  c  o  m*/
 * 
 * The properties file REPORTING_CUSTOM_PROPERTIES can be named differently using
 * the method setCustomModelProperties(String newFileName)
 * 
 * @return Properties object with as content the key/value pairs from the properties file.
 */
public Properties getReplacementDataType() {

    try {
        ClassLoader cl = this.getClass().getClassLoader();
        InputStream is = cl.getResourceAsStream(Constants.REPORTING_CUSTOM_PROPERTIES);
        Properties p = new Properties();
        p.load(is);
        replacementTypes = p;
    } catch (Exception e) {
        //e.printStackTrace();
        replacementTypes = new Properties();
    }

    return replacementTypes;
}