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.apache.marmotta.platform.core.services.templating.TemplatingServiceImpl.java

private void loadTemplateFromClasspath(String templateName, Class<?> clazz) {
    final String src = TemplatingService.PATH + templateName;
    final File tpl = new File(templateDir, templateName);
    if (!tpl.exists()) {
        try {/*w w w  .j av a  2s.  c om*/
            log.info("template {} not found in {}, copying fallback...", templateName,
                    templateDir.getAbsolutePath());
            final InputStream in = clazz.getResourceAsStream(src);
            if (in == null) {
                throw new IOException("Resource " + src + " not found in ClassLoader (" + clazz + ")");
            }
            FileUtils.copyInputStreamToFile(in, tpl);
        } catch (IOException e) {
            log.error("Could not load template from classpath, templating might react weird!", e);
        }
    }
}

From source file:com.seitenbau.stu.asserts.fest.impl.FileReferenceAssert.java

/** ford LFCR normalization! */
protected FileReferenceAssert hasEqualContentAsFileFromClasspath(Class relativeTo, String file)
        throws IOException {
    if (file == null) {
        throw new NullPointerException(formattedErrorMessage("File to compare to should not be null"));
    }/*  w  w w .j  ava2s  . c  om*/
    isNotNull();
    InputStream expected = relativeTo.getResourceAsStream(file);
    return hasEqualContentAs(expected, file);
}

From source file:org.sonar.core.persistence.TestDatabase.java

public void prepareDbUnit(Class testClass, String... testNames) {
    InputStream[] streams = new InputStream[testNames.length];
    try {/*from  w w w .j  a  v  a 2s. c o m*/
        for (int i = 0; i < testNames.length; i++) {
            String path = "/" + testClass.getName().replace('.', '/') + "/" + testNames[i];
            streams[i] = testClass.getResourceAsStream(path);
            if (streams[i] == null) {
                throw new IllegalStateException("DbUnit file not found: " + path);
            }
        }

        prepareDbUnit(streams);
        commands.resetPrimaryKeys(db.getDataSource());
    } catch (SQLException e) {
        throw translateException("Could not setup DBUnit data", e);
    } finally {
        for (InputStream stream : streams) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:HoverHelp.java

/**
 * Opens the main program./*from   w  ww  .  j av  a2  s  . c  o  m*/
 */
public Shell open(Display display) {
    // Load the images
    Class clazz = HoverHelp.class;
    try {
        if (images == null) {
            images = new Image[imageLocations.length];

            for (int i = 0; i < imageLocations.length; ++i) {
                InputStream stream = clazz.getResourceAsStream(imageLocations[i]);
                ImageData source = new ImageData(stream);
                ImageData mask = source.getTransparencyMask();
                images[i] = new Image(display, source, mask);
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception ex) {
        System.err.println(getResourceString("error.CouldNotLoadResources", new Object[] { ex.getMessage() }));
        return null;
    }

    // Create the window
    Shell shell = new Shell();
    createPartControl(shell);
    shell.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent e) {
            /* Free resources */
            if (images != null) {
                for (int i = 0; i < images.length; i++) {
                    final Image image = images[i];
                    if (image != null)
                        image.dispose();
                }
                images = null;
            }
        }
    });
    shell.pack();
    shell.open();
    return shell;
}

From source file:util.io.IOUtilities.java

/**
 * Ldt eine Datei aus einem Jar-File und gibt sie zurck.
 * <P>//from   ww  w . jav  a 2s. c  o m
 * Ist keine Datei mit diesem Namen im Jar-File, so wird versucht, sie vom
 * Dateisystem zu laden.
 *
 * @param fileName Der Name der Datei. (Ist case-sensitive!).
 * @param srcClass Eine Klasse, aus deren Jar-File das Image geladen werden soll.
 * @return The file loaded from the jar file as byte array.
 *
 * @throws IOException Wenn ein Fehler beim Laden der Datei auftrat.
 */
public static byte[] loadFileFromJar(String fileName, Class srcClass) throws IOException {
    if (fileName == null) {
        throw new IllegalArgumentException("fileName == null");
    }
    if (StringUtils.isEmpty(fileName)) {
        throw new IllegalArgumentException("fileName is empty");
        // if (srcClass == null) srcClass = IOUtilities.class;
    }

    // Der Dateiname muss mit einem '/' anfangen, sonst wird er nicht gefunden.

    InputStream in;

    if (srcClass == null) {
        in = new java.io.FileInputStream(fileName);
    } else {
        if ((fileName.charAt(0) != '/') && (fileName.charAt(0) != '\\')) {
            fileName = "/" + fileName;
        }

        in = srcClass.getResourceAsStream(fileName);

    }
    if (in == null) {
        throw new IOException("Resource not found: '" + fileName + "'");
    }

    byte[] buffer = new byte[10240];
    byte[] data = new byte[0];
    int len;
    while ((len = in.read(buffer)) != -1) {
        // data Array vergrern
        byte[] oldData = data;
        data = new byte[oldData.length + len];
        System.arraycopy(oldData, 0, data, 0, oldData.length);

        // Gerade gelesene Daten anhngen
        System.arraycopy(buffer, 0, data, oldData.length, len);
    }
    in.close();

    return data;
}

From source file:org.eclipse.swt.examples.hoverhelp.HoverHelp.java

/**
 * Opens the main program./* ww w . ja v  a2  s. com*/
 */
public Shell open(Display display) {
    // Load the images
    Class<HoverHelp> clazz = HoverHelp.class;
    try {
        if (images == null) {
            images = new Image[imageLocations.length];

            for (int i = 0; i < imageLocations.length; ++i) {
                try (InputStream stream = clazz.getResourceAsStream(imageLocations[i])) {
                    ImageData source = new ImageData(stream);
                    ImageData mask = source.getTransparencyMask();
                    images[i] = new Image(display, source, mask);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception ex) {
        System.err.println(getResourceString("error.CouldNotLoadResources", ex.getMessage()));
        return null;
    }

    // Create the window
    Shell shell = new Shell();
    createPartControl(shell);
    shell.addDisposeListener(e -> {
        /* Free resources */
        if (images != null) {
            for (final Image image : images) {
                if (image != null)
                    image.dispose();
            }
            images = null;
        }
    });
    shell.pack();
    shell.open();
    return shell;
}

From source file:org.carewebframework.ui.zk.ZKUtil.java

/**
 * Loads a page definition from a zul page. If the page is an embedded resource, prefix the file
 * name with the owning class name followed by a colon. For example,
 * "org.carewebframework.ui.component.PatientSelection:patientSelection.zul"
 * //from   w ww  .  j av  a  2s  .c o  m
 * @param filename File name pointing to the zul page.
 * @return A page definition representing the zul page.
 */
public static PageDefinition loadZulPageDefinition(String filename) {
    InputStream is = null;
    InputStreamReader reader = null;
    Class<?> containingClass = null;
    int i = filename.indexOf(":");

    try {
        if (i > 0) {
            containingClass = Class.forName(filename.substring(0, i));
            filename = filename.substring(i + 1);
        }

        if (containingClass == null) {
            return Executions.getCurrent().getPageDefinition(filename.replace("/zkau/web/", "~./"));
        }

        is = containingClass.getResourceAsStream(filename);

        if (is == null) {
            throw new IOException("Zul page not found: " + filename);
        }

        reader = new InputStreamReader(is);
        return Executions.getCurrent().getPageDefinitionDirectly(reader, null);
    } catch (Exception e) {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(is);
        throw new RuntimeException(e);
    }
}

From source file:SWTBrowserDemo.java

/**
 * Loads the resources// ww  w . j  ava2s  .co  m
 */
void initResources() {
    final Class clazz = this.getClass();
    try {
        if (images == null) {
            images = new Image[imageLocations.length];
            for (int i = 0; i < imageLocations.length; ++i) {
                InputStream sourceStream = clazz.getResourceAsStream(imageLocations[i]);
                ImageData source = new ImageData(sourceStream);
                ImageData mask = source.getTransparencyMask();
                images[i] = 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:it.haefelinger.flaka.util.InitSSL.java

protected File getDefaultTrustStore() {
    final String fname = "depot.keystore"; /* default name */
    final String clazz = "it.haefelinger.flaka.Break"; /* search here .. */

    String path;/*from  ww  w. java 2s. c  o  m*/
    File F = null;
    Class C = null;
    InputStream cin = null;

    /* retrieve loc from from package */
    try {
        C = Class.forName(clazz);
    } catch (Exception e) {
        error("unable to locate class `" + clazz + "' in classpath.");
        return null;
    }

    /* locate */
    cin = C.getResourceAsStream(fname);
    if (cin == null) {
        error("'" + fname + "' not found in \"flaka\".");
        return null;
    }

    /* create temporary loc */
    try {
        F = File.createTempFile("depot", null);
        F.deleteOnExit();
    } catch (Exception e) {
        error("unable to create a temporary loc", e);
        return null;
    }

    /* extract */
    path = F.getAbsolutePath();
    try {
        Static.writex(cin, path, false);
    } catch (Exception e) {
        F.delete();
        error("error while writing (temporary) loc '" + path + "'.", e);
        return null;
    }
    return F;
}

From source file:org.tmjee.miniwiki.radeox.macro.book.TextFileUrlMapper.java

public TextFileUrlMapper(Class klass) {
    services = new HashMap();

    boolean fileNotFound = false;
    try {/* w w  w . ja v  a 2  s. c o m*/
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(getFileName())));
        addMapping(br);
    } catch (IOException e) {
        log.warn("Unable to read " + getFileName());
        fileNotFound = true;
    }

    if (fileNotFound) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(klass.getResourceAsStream("/" + getFileName())));
            addMapping(br);
        } catch (Exception e) {
            log.warn("Unable to read /" + getFileName() + " from jar");
        }
    }
}