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:com.horstmann.violet.web.UMLEditorWebApplication.java

private void createDefaultWorkspace() throws IOException {
    setTheme(new WBootstrapTheme());
    useStyleSheet(new WLink(new WResource() {
        @Override//from w  w w  .ja va2  s . com
        protected void handleRequest(WebRequest request, WebResponse response) throws IOException {
            ClassLoader classLoader = this.getClass().getClassLoader();
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("text/css");
            InputStream inputStream = classLoader.getResourceAsStream("/violet.css");
            IOUtils.copy(inputStream, outputStream);
            inputStream.close();
            outputStream.close();
        }

    }));
    //URL resource = getClass().getResource("test.class.violet.html");
    //IFile aFile = new LocalFile(new File(resource.getFile()));
    GraphFile graphFile = new GraphFile(ClassDiagramGraph.class);
    IWorkspace workspace = new Workspace(graphFile);
    workspace.getAWTComponent().setSize(800, 600);
    workspace.getAWTComponent().prepareLayout();
    WorkspaceWidget workspaceWidget = new WorkspaceWidget(workspace);
    WContainerWidget root = getRoot();
    root.setWidth(new WLength(100, Unit.Percentage));
    root.setWidth(new WLength(100, Unit.Percentage));
    root.setStyleClass("root");
    root.addWidget(workspaceWidget);
    root.mouseMoved().setBlocked(true);

}

From source file:Engine.Lua.PlayerLua.java

public void tester(String luaFile) {
    Dog dog = new Dog("Rex");
    Cat cat = new Cat("Felix");
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine scriptEngine = sem.getEngineByName("luaj");
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile);
    InputStreamReader isr = new InputStreamReader(is);
    CompiledScript script;//from ww  w  . j  a  va 2s  . co  m
    try {
        script = ((Compilable) scriptEngine).compile(isr);
        isr.close();
        is.close();
        Bindings sb = new SimpleBindings();
        script.eval(sb); // Put the Lua functions into the sb environment
        LuaValue luaDog = CoerceJavaToLua.coerce(dog); // Java to Lua
        //CoerceLuaToJava()
        LuaFunction onTalk = (LuaFunction) sb.get("onTalk"); // Get Lua function
        LuaValue b = onTalk.call(luaDog); // Call the function
        System.out.println("onTalk answered: " + b);
        LuaFunction onWalk = (LuaFunction) sb.get("onWalk");
        LuaValue[] dogs = { luaDog };
        Varargs dist = onWalk.invoke(LuaValue.varargsOf(dogs)); // Alternative

        System.out.println("onWalk returned: " + dist);

        Dog retunredDog = (Dog) CoerceLuaToJava.coerce(luaDog, Dog.class);
        System.out.println("AAAAAAAAAa:" + retunredDog.name);
    } catch (ScriptException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:monitoring.tools.GooglePlayAPI.java

private void loadProperties() throws Exception {
    Properties prop = new Properties();
    try {//from ww  w  .j  a v  a2 s.c  o  m
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream input = classLoader.getResourceAsStream("config.properties");
        prop.load(input);
        clientID = prop.getProperty("clientID");
        clientSecret = prop.getProperty("clientSecret");
        refreshToken = prop.getProperty("refreshToken");
        accessToken = prop.getProperty("accessToken");
    } catch (Exception e) {
        throw new IOException("There was an unexpected error loading the properties file.");
    }
}

From source file:io.klerch.alexa.tellask.util.resource.ResourceUtteranceReader.java

/**
 * {@inheritDoc}/*www .  ja va2  s  .  co m*/
 */
@Override
public InputStream read(final String locale) {
    Validate.notNull(locale, "Locale must not be blank.");

    final String resourcePath = leadingPath + locale + resourceLocation;
    final String resourcePath2 = resourcePath.startsWith("/") ? resourcePath.substring(1) : resourcePath;

    final ClassLoader cl = getClass().getClassLoader();

    Validate.notNull(cl.getResource(resourcePath2),
            "Resource " + resourcePath2 + " does not exist in current context.");

    return cl.getResourceAsStream(resourcePath2);
}

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

private JsonNode getJson(ClassLoader classLoader, String path) {
    try {/*  w ww . j  a  v a  2s. co  m*/
        InputStream is = classLoader.getResourceAsStream(path);
        if (is == null) {
            return null;
        }
        return new ObjectMapper().readTree(is);
    } catch (IOException e) {
        return null;
    }
}

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

private String getOpaqueJsonString(ClassLoader classLoader, String path) {
    try {/*from   w  w w  .j a  v  a  2 s.c  om*/
        InputStream is = classLoader.getResourceAsStream(path);
        if (is == null) {
            return null;
        }
        return IOUtils.toString(is, Charset.defaultCharset());
    } catch (IOException e) {
        return null;
    }
}

From source file:org.apache.sqoop.utils.TestConnectorClassLoader.java

@Test
public void testGetResource() throws IOException {
    URL testJar = makeTestJar().toURI().toURL();

    ClassLoader currentClassLoader = getClass().getClassLoader();
    ClassLoader connectorClassloader = new ConnectorClassLoader(new URL[] { testJar }, currentClassLoader, null,
            false);//from   w  w  w .  jav a2  s  . c o m

    assertNull(currentClassLoader.getResourceAsStream("resource.txt"),
            "Resource should be null for current classloader");

    InputStream in = connectorClassloader.getResourceAsStream("resource.txt");
    assertNotNull(in, "Resource should not be null for connector classloader");
    assertEquals("hello", IOUtils.toString(in));
}

From source file:com.opengamma.maven.scripts.ScriptableScriptGeneratorMojo.java

private Template getTemplate(String templateName) throws MojoExecutionException {
    try {/*from www  .j  av  a  2s  . c o m*/
        if (_resourceArtifact == null) {
            return getTemplateFromFile(_baseDir, templateName);
        } else {
            ClassLoader resourceLoader = getResourceLoader(_resourceArtifact, _project);
            InputStream resourceStream = resourceLoader.getResourceAsStream(templateName);
            if (resourceStream == null) {
                throw new MojoExecutionException("Resource '" + templateName + "' not found");
            }
            String templateStr;
            try {
                templateStr = IOUtils.toString(resourceStream);
            } finally {
                resourceStream.close();
            }
            return new Template(templateName, new StringReader(templateStr), new Configuration());
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Error loading Freemarker template from '" + templateName + "'", e);
    }
}

From source file:org.talend.components.api.component.runtime.DependenciesReader.java

/**
 * this will locate the file META-INF/mavenGroupId/mavenArtifactId/dependencies.txt and parse it to extract
 * the dependencies of the component except the test depenencies.
 * /* w w  w. ja v a2s  .  c o  m*/
 * @param mavenGroupId group id of the component to locate the dep file
 * @param mavenArtifactId artifact id of the component to locate the dep file.
 * @param classLoader used to locate the file using {@link ClassLoader#getResourceAsStream(String)}
 * @return set of string pax-url formated
 * @throws IOException if reading the file failed.
 */
public Set<String> getDependencies(ClassLoader classLoader) throws IOException {
    ClassLoader zeClassLoader = classLoader;
    if (zeClassLoader == null) {
        zeClassLoader = this.getClass().getClassLoader();
    }
    try (InputStream depStream = zeClassLoader.getResourceAsStream(depTxtPath)) {
        if (depStream == null) {
            throw new ComponentException(ComponentsApiErrorCode.COMPUTE_DEPENDENCIES_FAILED,
                    ExceptionContext.withBuilder().put("path", depTxtPath).build());
        } // else we found it so parse it now
        return parseDependencies(depStream);
    }
}

From source file:com.googlecode.jsfFlex.shared.tasks.AbstractFileManipulatorTaskRunner.java

public synchronized String getComponentTemplate(ClassLoader loader, String template) {
    StringBuilder fileContent = new StringBuilder();
    BufferedReader bufferRead = null;

    try {//  ww w .j a v  a2 s.c o m

        bufferRead = new BufferedReader(new InputStreamReader(loader.getResourceAsStream(template)));
        char[] charBuffer = new char[2048];
        int offSet = 0;

        while ((offSet = bufferRead.read(charBuffer, 0, 2048)) > -1) {
            fileContent.append(charBuffer, 0, offSet);
        }

    } catch (FileNotFoundException fileNotFoundExcept) {
        throw new ComponentBuildException(getErrorMessage("getComponentTemplate", template),
                fileNotFoundExcept);
    } catch (IOException ioExcept) {
        throw new ComponentBuildException(getErrorMessage("getComponentTemplate", template), ioExcept);
    } finally {

        if (bufferRead != null) {
            try {
                bufferRead.close();
            } catch (IOException closerException) {
                _log.debug("Error while closing the writer within getComponentTemplate", closerException);
            }
        }

    }

    return fileContent.toString();
}