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:gemlite.core.internal.support.hotdeploy.scanner.ScannerIteratorItem.java

private byte[] readContent(ClassLoader loader, JarEntry entry) throws IOException {
    URL url = loader.getResource(entry.getName());
    URLConnection ulc = url.openConnection();
    InputStream in3 = ulc.getInputStream();
    InputStream in2 = url.openStream();

    InputStream in = loader.getResourceAsStream(entry.getName());
    if (in == null) {
        LogUtil.getCoreLog().trace("ReadContent inputStream is null entry.name={} , loader={}", entry.getName(),
                loader);//from ww w.j a v  a2  s .c o  m
    }

    BufferedInputStream bi = new BufferedInputStream(in);
    byte[] bt = new byte[in.available()];
    bi.read(bt);
    bi.close();
    in.close();
    return bt;
}

From source file:io.syndesis.maven.ExtractConnectorDescriptorsMojo.java

@SuppressWarnings("PMD.AvoidCatchingGenericException")
private String extractComponentJavaType(ClassLoader classLoader, String scheme) {
    try {/*www  .ja  v a 2s  .  c o  m*/
        InputStream is = classLoader
                .getResourceAsStream("META-INF/services/org/apache/camel/component/" + scheme);
        if (is != null) {
            Properties props = new Properties();
            props.load(is);
            return (String) props.get("class");
        }
    } catch (Exception e) {
        getLog().warn("WARN: Error loading META-INF/services/org/apache/camel/component/" + scheme
                + " file due " + e.getMessage());
    }
    return null;
}

From source file:com.envirover.spl.Config.java

public boolean init(String[] args) throws IOException, ParseException {
    Options options = new Options();
    options.addOption(CLI_OPTION_HELP, false, "help");
    options.addOption(CLI_OPTION_IMEI, true, "IMEI of RockBLOCK");
    options.addOption(CLI_OPTION_USERNAME, true, "Rock 7 Core username");
    options.addOption(CLI_OPTION_PASSWORD, true, "Rock 7 Core password");
    options.addOption(CLI_OPTION_AUTOPILOT, true, "Autopilot code");
    options.addOption(CLI_OPTION_MAV_TYPE, true, "MAV type");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption(CLI_OPTION_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("spl", options);
    }/*from  w  w  w .jav  a  2s .co  m*/

    Properties props = new Properties();

    InputStream in = null;
    try {
        ClassLoader loader = Config.class.getClassLoader();
        in = loader.getResourceAsStream(CONFIG_PROPERTIES_FILE);
        if (in != null)
            props.load(in);
    } finally {
        if (in != null) {
            in.close();
        }
    }

    if (props.getProperty(PROP_ROCKBLOCK_PORT) != null)
        rockblockPort = Integer.valueOf(props.getProperty(PROP_ROCKBLOCK_PORT));

    if (props.getProperty(PROP_MAVLINK_PORT) != null)
        mavlinkPort = Integer.valueOf(props.getProperty(PROP_MAVLINK_PORT));

    if (props.getProperty(PROP_WS_PORT) != null)
        wsPort = Integer.valueOf(props.getProperty(PROP_WS_PORT));

    if (props.getProperty(PROP_QUEUE_SIZE) != null)
        queueSize = Integer.valueOf(props.getProperty(PROP_QUEUE_SIZE));

    if (props.getProperty(PROP_HEARTBEAT_INTERVAL) != null)
        heartbeatInterval = Integer.valueOf(props.getProperty(PROP_HEARTBEAT_INTERVAL));

    if (props.getProperty(PROP_ROCKBLOCK_URL) != null)
        rockblockUrl = props.getProperty(PROP_ROCKBLOCK_URL);

    imei = cmd.getOptionValue(CLI_OPTION_IMEI, props.getProperty(PROP_ROCKBLOCK_IMEI));

    if (imei == null || imei.isEmpty()) {
        System.out.println(MessageFormat.format("Required configuration property ''{0}'' is not set.",
                PROP_ROCKBLOCK_IMEI));
        return false;
    }

    username = cmd.getOptionValue(CLI_OPTION_USERNAME, props.getProperty(PROP_ROCKBLOCK_USERNAME));

    if (username == null || username.isEmpty()) {
        System.out.println(MessageFormat.format("Required configuration property ''{0}'' is not set.",
                PROP_ROCKBLOCK_USERNAME));
        return false;
    }

    password = cmd.getOptionValue(CLI_OPTION_PASSWORD, props.getProperty(PROP_ROCKBLOCK_PASSWORD));

    if (password == null || password.isEmpty()) {
        System.out.println(MessageFormat.format("Required configuration property ''{0}'' is not set.",
                PROP_ROCKBLOCK_PASSWORD));
        return false;
    }

    autopilot = Short.valueOf(cmd.getOptionValue(CLI_OPTION_AUTOPILOT,
            props.getProperty(PROP_MAV_AUTOPILOT, DEFAULT_AUTOPILOT.toString())));

    mavType = Short.valueOf(cmd.getOptionValue(CLI_OPTION_MAV_TYPE,
            props.getProperty(PROP_MAV_TYPE, DEFAULT_MAV_TYPE.toString())));

    return true;
}

From source file:de.micromata.genome.gwiki.page.gspt.taglibs.TagLibraryInfoImpl.java

protected InputStream loadImpl(String uri) throws IOException {
    String luri = uri;/*  w  ww .j  a v  a2  s.co m*/
    if (luri.startsWith("/WEB-INF/") == true) {
        luri = luri.substring("/WEB-INF/".length());
    }
    if (luri.startsWith("/") == true) {
        luri = luri.substring(1);
    }
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream(luri);
    if (is != null) {
        return is;
    }
    if (TagLibraryInfo.class.getClassLoader() != cl) {
        is = cl.getResourceAsStream(luri);
        if (is != null) {
            return is;
        }
    }
    is = pageContext.getServletContext().getResourceAsStream(uri);
    return is;
}

From source file:org.alfresco.repo.node.integrity.IncompleteNodeTaggerTest.java

public void setUp() throws Exception {
    DictionaryDAO dictionaryDao = (DictionaryDAO) IntegrityTest.ctx.getBean("dictionaryDAO");
    ClassLoader cl = BaseNodeServiceTest.class.getClassLoader();
    // load the test model
    InputStream modelStream = cl
            .getResourceAsStream("org/alfresco/repo/node/integrity/IntegrityTest_model.xml");
    assertNotNull(modelStream);/* w  w  w.ja  v a 2s.  c  om*/
    M2Model model = M2Model.createModel(modelStream);
    dictionaryDao.putModel(model);

    tagger = (IncompleteNodeTagger) IntegrityTest.ctx.getBean("incompleteNodeTagger");

    serviceRegistry = (ServiceRegistry) IntegrityTest.ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    nodeService = serviceRegistry.getNodeService();
    authenticationService = serviceRegistry.getAuthenticationService();
    permissionService = serviceRegistry.getPermissionService();
    this.authenticationComponent = (AuthenticationComponent) IntegrityTest.ctx
            .getBean("authenticationComponent");

    this.authenticationComponent.setSystemUserAsCurrentUser();

    String user = getName();
    if (!authenticationService.authenticationExists(user)) {
        authenticationService.createAuthentication(user, user.toCharArray());
    }

    // begin a transaction
    TransactionService transactionService = serviceRegistry.getTransactionService();
    txn = transactionService.getUserTransaction();
    txn.begin();
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, getName());
    if (!nodeService.exists(storeRef)) {
        nodeService.createStore(storeRef.getProtocol(), storeRef.getIdentifier());
        rootNodeRef = nodeService.getRootNode(storeRef);
        // Make sure our user can do everything
        permissionService.setPermission(rootNodeRef, user, PermissionService.ALL_PERMISSIONS, true);
    } else {
        rootNodeRef = nodeService.getRootNode(storeRef);
    }

    properties = new PropertyMap();
    properties.put(IntegrityTest.TEST_PROP_TEXT_C, "abc");

    // Authenticate as a test-specific user
    authenticationComponent.setCurrentUser(user);
}

From source file:com.urbancode.x2o.xml.NamespaceConfiguration.java

public void loadNameSpaceFromClassPath(String nameSpace) {
    BidiMap biMap = new DualHashBidiMap();
    String filePath = nameSpace.replaceAll("\\.", Matcher.quoteReplacement("/"));
    String resourceName = filePath + "/" + NAMESPACE_FILE;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Properties props = new Properties();

    log.debug("Looking for resource: " + resourceName);

    try {//from   w ww. j ava  2  s  . co  m
        props.load(classLoader.getResourceAsStream(resourceName));
    } catch (IOException e) {
        log.error(e.getClass() + " caught in " + this.getClass());
        // swallow
    }

    // build the biDirectionalMap
    for (Object prop : props.keySet()) {
        biMap.put(prop, props.getProperty((String) prop));
    }

    log.debug("added following elements into map: " + biMap.keySet());
    log.debug("Added following value: " + biMap.values());

    nameSpaces.put(nameSpace, biMap);
}

From source file:jp.xet.uncommons.wicket.utils.ErrorReportRequestCycleListener.java

/**
 * ????/* w  w  w  .  j av  a2s. c o m*/
 * 
 * @return ??
 * @since 1.0
 */
protected String loadEnvironment() {
    if (environment != null) {
        EnvironmentProfile profile = RemoteEnvironmentProfile
                .toEnvironmentProfile(environment.getActiveProfiles());
        return profile.toString();
    }

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream in = null;
    try {
        in = cl.getResourceAsStream(PROP_PATH);
        if (in == null) {
            return null;
        }
        Properties properties = new Properties();
        properties.load(in);
        return properties.getProperty("environment");
    } catch (IOException ex) {
        return "";
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("IOException should not have been thrown.", e);
            }
        }
    }
}

From source file:com.google.caja.precajole.StaticPrecajoleMap.java

private byte[] loadResource(String id) {
    if (id == null) {
        return null;
    }// w ww.j  a va  2 s. c o m
    ClassLoader cl = StaticPrecajoleMap.class.getClassLoader();
    InputStream is = cl.getResourceAsStream(dir + id);
    if (is == null) {
        return null;
    }
    try {
        return ByteStreams.toByteArray(is);
    } catch (IOException e) {
        return null;
    }
}

From source file:com.linkedin.restli.server.ParseqTraceDebugRequestHandler.java

private void sendTracevisEntryPageAsResponse(final RequestExecutionCallback<RestResponse> callback,
        final RequestExecutionReport executionReport) {
    String mediaType = HEADER_VALUE_TEXT_HTML;

    ClassLoader currentClassLoader = getClass().getClassLoader();
    InputStream resourceStream = currentClassLoader
            .getResourceAsStream(ENTRY_PATH_SEGMENT_TRACEVIS + PATH_SEP + ENTRY_PAGE);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {/*  w w  w  . j a v a  2 s  .  c  om*/
        IOUtils.copy(resourceStream, outputStream);
        Trace trace = executionReport.getParseqTrace();

        if (trace != null) {
            //Serialize the Parseq trace into JSON and then inject a javascript into the response
            //which will call the corresponding render function on the entry page html with the JSON
            //string.
            JsonTraceCodec traceCodec = new JsonTraceCodec();
            IOUtils.write(createTraceRenderScript(traceCodec.encode(trace)), outputStream);
        }
    } catch (IOException exception) {
        callback.onError(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, exception), null,
                null, null);
    }

    sendByteArrayAsResponse(callback, outputStream.toByteArray(), mediaType);
}

From source file:org.apache.shindig.gadgets.rewrite.image.ImageRewriterTest.java

/** Extracts an image by its resource name and converts it into a byte array. */
private byte[] getImageBytes(String imageResourceName) throws IOException {
    ClassLoader classLoader = getClass().getClassLoader();
    byte[] imageBytes = IOUtils.toByteArray(classLoader.getResourceAsStream(imageResourceName));
    assertNotNull(imageBytes);//from   w  ww . j  a v a  2  s  .  co  m
    return imageBytes;
}