Example usage for java.lang Class getResourceAsStream

List of usage examples for java.lang Class getResourceAsStream

Introduction

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

Prototype

@CallerSensitive
public InputStream getResourceAsStream(String name) 

Source Link

Document

Finds a resource with a given name.

Usage

From source file:org.sonar.db.AbstractDbTester.java

public void assertDbUnit(Class testClass, String filename, String[] excludedColumnNames, String... tables) {
    IDatabaseConnection connection = null;
    try {/*from   w  w w. j  ava 2s. c  o  m*/
        connection = dbUnitConnection();

        IDataSet dataSet = connection.createDataSet();
        String path = "/" + testClass.getName().replace('.', '/') + "/" + filename;
        InputStream inputStream = testClass.getResourceAsStream(path);
        if (inputStream == null) {
            throw new IllegalStateException(String.format("File '%s' does not exist", path));
        }
        IDataSet expectedDataSet = dbUnitDataSet(inputStream);
        for (String table : tables) {
            DiffCollectingFailureHandler diffHandler = new DiffCollectingFailureHandler();

            ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(dataSet.getTable(table),
                    excludedColumnNames);
            ITable filteredExpectedTable = DefaultColumnFilter
                    .excludedColumnsTable(expectedDataSet.getTable(table), excludedColumnNames);
            Assertion.assertEquals(filteredExpectedTable, filteredTable, diffHandler);
            // Evaluate the differences and ignore some column values
            List diffList = diffHandler.getDiffList();
            for (Object o : diffList) {
                Difference diff = (Difference) o;
                if (!"[ignore]".equals(diff.getExpectedValue())) {
                    throw new DatabaseUnitException(diff.toString());
                }
            }
        }
    } catch (DatabaseUnitException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (Exception e) {
        throw translateException("Error while checking results", e);
    } finally {
        closeQuietly(connection);
    }
}

From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java

/**
 * Determine imports for the given bundle. Based on the user settings, this
 * method will consider only the the test hierarchy until the testing
 * framework is found or all classes available inside the test bundle. <p/>
 * Note that split packages are not supported.
 * //from   www.  j a  v a 2 s. co  m
 * @return
 */
private String[] determineImports() {

    boolean useTestClassOnly = false;

    // no jar entry present, bail out.
    if (jarEntries == null || jarEntries.isEmpty()) {
        logger.debug("No test jar content detected, generating bundle imports from the test class");
        useTestClassOnly = true;
    }

    else if (createManifestOnlyFromTestClass()) {
        logger.info("Using the test class for generating bundle imports");
        useTestClassOnly = true;
    } else
        logger.info("Using all classes in the jar for the generation of bundle imports");

    // className, class resource
    Map entries;

    if (useTestClassOnly) {

        entries = new LinkedHashMap(4);

        // get current class (test class that bootstraps the OSGi infrastructure)
        Class<?> clazz = getClass();
        String clazzPackage = null;
        String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName();

        do {

            // consider inner classes as well
            List classes = new ArrayList(4);
            classes.add(clazz);
            CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes);

            for (Iterator iterator = classes.iterator(); iterator.hasNext();) {
                Class<?> classToInspect = (Class) iterator.next();

                Package pkg = classToInspect.getPackage();
                if (pkg != null) {
                    clazzPackage = pkg.getName();
                    String classFile = ClassUtils.getClassFileName(classToInspect);
                    entries.put(classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX),
                            new InputStreamResource(classToInspect.getResourceAsStream(classFile)));
                }
                // handle default package
                else {
                    logger.warn("Could not find package for class " + classToInspect + "; ignoring...");
                }
            }

            clazz = clazz.getSuperclass();

        } while (!endPackage.equals(clazzPackage));
    } else
        entries = jarEntries;

    return determineImportsFor(entries);

}

From source file:org.geoserver.platform.GeoServerResourceLoader.java

/**
 * Copies a resource relative to a particular class from the classpath to the specified file. 
 * /*from  ww  w . ja  va  2  s  .c o  m*/
 * @param classpathResource Path to classpath content to be copied
 * @param target File to copy content into (must be already created)
 * @param scope Class used as base for classpathResource
 */

public void copyFromClassPath(String classpathResource, File target, Class<?> scope) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    byte[] buffer = new byte[4096];
    int read;

    try {
        // Get the resource
        if (scope == null) {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathResource);
            if (is == null) {
                throw new IOException("Could not load " + classpathResource + " from scope "
                        + Thread.currentThread().getContextClassLoader().toString() + ".");
            }
        } else {
            is = scope.getResourceAsStream(classpathResource);
            if (is == null) {
                throw new IOException(
                        "Could not load " + classpathResource + " from scope " + scope.toString() + ".");
            }
        }

        // Write it to the target
        try {
            os = new FileOutputStream(target);
            while ((read = is.read(buffer)) > 0)
                os.write(buffer, 0, read);
        } catch (FileNotFoundException targetException) {
            throw new IOException("Can't write to file " + target.getAbsolutePath()
                    + ". Check write permissions on target folder for user " + System.getProperty("user.name"));
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Error trying to copy logging configuration file", e);
        }
    } finally {
        // Clean up
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:org.azyva.dragom.cliutil.CliUtil.java

/**
 * Returns the version of a text resource appropriate for the current default
 * Locale.//from w ww . j  av a 2 s. c om
 *
 * <p>A Reader is returned so that character encoding is taken into consideration.
 * The text resource is assumed to be encoded with UTF-8, regardless of the
 * platform default encoding.
 *
 * <p>The algorithm used for selecting the appropriate resource is similar to the
 * one implemented by ResourceBundle.getBundle.
        
 * <p>The resource base name is split on the last ".", if any, and the candidate
 * variants are inserted before it.
 *
 * @param clazz Class to which the resource belongs.
 * @param resourceBaseName Base name of the resource.
 * @return Resource as an InputStream, just as Class.getResourceAsStream would
 *   return. null if no resource version exists.
 */
public static Reader getLocalizedTextResourceReader(Class<?> clazz, String resourceBaseName) {
    int indexDot;
    String resourceBaseNamePrefix;
    String resourceBaseNameSuffix;
    Locale locale;
    String[] arrayCandidate;

    indexDot = resourceBaseName.lastIndexOf('.');

    if (indexDot != -1) {
        resourceBaseNamePrefix = resourceBaseName.substring(0, indexDot);
        resourceBaseNameSuffix = resourceBaseName.substring(indexDot);
    } else {
        resourceBaseNamePrefix = resourceBaseName;
        resourceBaseNameSuffix = "";
    }

    locale = Locale.getDefault();

    arrayCandidate = new String[7];

    arrayCandidate[0] = resourceBaseNamePrefix + "_" + locale.getLanguage() + "_" + locale.getScript() + "_"
            + locale.getCountry() + "_" + locale.getVariant();
    arrayCandidate[1] = resourceBaseNamePrefix + "_" + locale.getLanguage() + "_" + locale.getScript() + "_"
            + locale.getCountry();
    arrayCandidate[2] = resourceBaseNamePrefix + "_" + locale.getLanguage() + "_" + locale.getScript();
    arrayCandidate[3] = resourceBaseNamePrefix + "_" + locale.getLanguage() + "_" + locale.getCountry() + "_"
            + locale.getVariant();
    arrayCandidate[4] = resourceBaseNamePrefix + "_" + locale.getLanguage() + "_" + locale.getCountry();
    arrayCandidate[5] = resourceBaseNamePrefix + "_" + locale.getLanguage();
    arrayCandidate[6] = resourceBaseNamePrefix;

    for (String candidate : arrayCandidate) {
        if (!candidate.endsWith("_")) {
            InputStream inputStreamResource;

            inputStreamResource = clazz.getResourceAsStream(candidate + resourceBaseNameSuffix);

            if (inputStreamResource != null) {
                try {
                    return new InputStreamReader(inputStreamResource, "UTF-8");
                } catch (UnsupportedEncodingException uee) {
                    throw new RuntimeException(uee);
                }
            }
        }
    }

    return null;
}

From source file:org.bonitasoft.engine.test.APITestUtil.java

public BarResource getBarResource(final String path, final String name, Class<?> clazz) throws IOException {
    final InputStream stream = clazz.getResourceAsStream(path);
    assertThat(stream).isNotNull();//from  ww w . j a va2 s.c o  m
    try {
        final byte[] byteArray = IOUtils.toByteArray(stream);
        return new BarResource(name, byteArray);
    } finally {
        stream.close();
    }
}

From source file:edu.harvard.i2b2.adminTool.dataModel.KTableCellEditor.java

@SuppressWarnings("unchecked")
public Image loadImageResource(Display d, String name) {
    try {/*  w  w w. j av a  2 s . com*/

        Image ret = null;
        Class clazz = this.getClass();
        InputStream is = clazz.getResourceAsStream(name);
        if (is != null) {
            ret = new Image(d, is);
            is.close();
        }
        return ret;
    } catch (Exception e1) {
        return null;
    }
}

From source file:org.apache.click.util.ClickUtils.java

/**
 * Finds a resource with a given name. This method returns null if no
 * resource with this name is found./* w w  w . j  ava2  s. co  m*/
 * <p>
 * This method uses the current <tt>Thread</tt> context <tt>ClassLoader</tt> to find
 * the resource. If the resource is not found the class loader of the given
 * class is then used to find the resource.
 *
 * @param name the name of the resource
 * @param aClass the class lookup the resource against, if the resource is
 *     not found using the current <tt>Thread</tt> context <tt>ClassLoader</tt>.
 * @return the input stream of the resource if found or null otherwise
 */
public static InputStream getResourceAsStream(String name, Class<?> aClass) {
    Validate.notNull(name, "Parameter name is null");
    Validate.notNull(aClass, "Parameter aClass is null");

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

    InputStream inputStream = classLoader.getResourceAsStream(name);
    if (inputStream == null) {
        inputStream = aClass.getResourceAsStream(name);
    }

    return inputStream;
}

From source file:gdt.data.store.Entigrator.java

/**
 * Copy the icon from the class resource
 *  into icons folder.//  w  w w .jav a 2 s  .  com
 *  @param handler the handler class
 *  @param icon$ the name of icon resource.
 */
public void saveHandlerIcon(Class<?> handler, String icon$) {
    try {
        File iconFile = new File(getEntihome() + "/" + ICONS + "/" + icon$);
        if (iconFile.exists())
            return;
        InputStream is = handler.getResourceAsStream(icon$);
        iconFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(iconFile);
        byte[] b = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = is.read(b)) != -1) {
            fos.write(b, 0, bytesRead);
        }
        is.close();
        fos.close();
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).severe(e.toString());
    }

}

From source file:PaintExample.java

/**
 * Loads the image resources.//w w  w  .ja  va  2s  .c  o m
 */
public void initResources() {
    final Class clazz = PaintExample.class;
    try {
        for (int i = 0; i < tools.length; ++i) {
            Tool tool = tools[i];
            String id = tool.group + '.' + tool.name;
            InputStream sourceStream = clazz.getResourceAsStream(getResourceString(id + ".image"));
            ImageData source = new ImageData(sourceStream);
            ImageData mask = source.getTransparencyMask();
            tool.image = new Image(null, source, mask);
            try {
                sourceStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return;
    } catch (Throwable t) {
    }

    String error = "Unable to load resources";
    freeResources();
    throw new RuntimeException(error);
}

From source file:PrintKTableExample.java

/**
 * reads an Image as ressource (either from file system or from a jar)
 *//*from w  ww  .  j  a  v a 2 s.  co m*/
public static Image loadImageResource(Display d, String name) {
    try {

        Image ret = null;
        Class clazz = new Object().getClass();
        InputStream is = clazz.getResourceAsStream(name);
        if (is != null) {
            ret = new Image(d, is);
            is.close();
        }
        if (ret == null)
            System.out.println("Error loading bitmap:\n" + name);
        return ret;
    } catch (Exception e1) {
        System.out.println("Error loading bitmap:\n" + name);
        return null;
    }
}