Example usage for java.lang ClassLoader getSystemResourceAsStream

List of usage examples for java.lang ClassLoader getSystemResourceAsStream

Introduction

In this page you can find the example usage for java.lang ClassLoader getSystemResourceAsStream.

Prototype

public static InputStream getSystemResourceAsStream(String name) 

Source Link

Document

Open for reading, a resource of the specified name from the search path used to load classes.

Usage

From source file:org.apache.james.jmap.methods.integration.GetMessageListMethodTest.java

@Test
public void getMessageListShouldSupportHasAttachmentSetToFalse() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, username, "mailbox");

    ComposedMessageId message1 = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), new Date(), false,
            new Flags());
    mailboxProbe.appendMessage(username, new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            ClassLoader.getSystemResourceAsStream("eml/twoAttachments.eml"), new Date(), false, new Flags());
    ComposedMessageId message3 = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            ClassLoader.getSystemResourceAsStream("eml/oneInlinedImage.eml"), new Date(), false, new Flags());
    await();//from w  w  w  . ja va 2 s . co m

    given().header("Authorization", accessToken.serialize())
            .body("[[\"getMessageList\", {\"filter\":{\"hasAttachment\":\"false\"}}, \"#0\"]]").when()
            .post("/jmap").then().statusCode(200).body(NAME, equalTo("messageList"))
            .body(ARGUMENTS + ".messageIds",
                    contains(message1.getMessageId().serialize(), message3.getMessageId().serialize()));
}

From source file:org.apromore.service.impl.CanoniserServiceImplIntgTest.java

private CanonisedProcess canoniseEPMLProcess(String fileName) throws CanoniserException, IOException {
    CanonisedProcess oFCanonised;//  w w  w . ja va2s . c o m
    try (InputStream oFProcess = ClassLoader.getSystemResourceAsStream(fileName)) {
        HashSet<RequestParameterType<?>> epmlParameters = new HashSet<>();
        epmlParameters.add(new RequestParameterType<>("addFakeProperties", true));
        oFCanonised = cSrv.canonise("EPML 2.0", oFProcess, epmlParameters);
    }
    return oFCanonised;
}

From source file:oracle.kv.hadoop.table.TableRecordReaderBase.java

/**
 * Convenience method that retrieves the login configuration and trust
 * credentials as resources from the classpath, and writes that
 * information to corresponding files on the user's local file system.
 * The login file and trust file that are created by this method can
 * then be used when attempting to interact with a secure KVStore.
 * <p>//from  w  ww .  ja v  a2  s . c o m
 * This method returns a string containing the fully qualified path to
 * the login file that is created. The login file will reference the
 * name of the trust file that is created; which must be written to
 * the same directory in which the login file resides.
 */
private static String createLocalKVSecurity(final String loginFlnm, final String trustFlnm) throws IOException {

    if (loginFlnm == null) {
        return null;
    }

    if (trustFlnm == null) {
        return null;
    }

    /*
     * If loginFile and/or trustFile is a filename and not an absolute
     * path, then generate local versions of the file.
     */
    final File userSecurityDirFd = new File(USER_SECURITY_DIR);
    if (!userSecurityDirFd.exists()) {
        if (!userSecurityDirFd.mkdirs()) {
            throw new IOException("failed to create " + userSecurityDirFd);
        }
    }

    InputStream loginStream = null;
    InputStream trustStream = null;

    final ClassLoader cl = TableRecordReaderBase.class.getClassLoader();
    if (cl != null) {
        loginStream = cl.getResourceAsStream(loginFlnm);
        trustStream = cl.getResourceAsStream(trustFlnm);
    } else {
        loginStream = ClassLoader.getSystemResourceAsStream(loginFlnm);
        trustStream = ClassLoader.getSystemResourceAsStream(trustFlnm);
    }

    /*
     * Retrieve the login configuration as a resource from the classpath,
     * and write that information to the user's local file system.
     */
    final Properties loginProps = new Properties();
    if (loginStream != null) {
        loginProps.load(loginStream);
    }

    /* Strip off the path of the trust file. */
    final String trustProp = loginProps.getProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY);
    if (trustProp != null) {
        final File trustPropFd = new File(trustProp);
        if (!trustPropFd.exists()) {
            loginProps.setProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY, trustPropFd.getName());
        }
    }

    final File loginFd = new File(USER_SECURITY_DIR + FILE_SEP + loginFlnm);
    final FileOutputStream loginFos = new FileOutputStream(loginFd);
    loginProps.store(loginFos, null);
    loginFos.close();

    /*
     * Retrieve the trust credentials as a resource from the classpath,
     * and write that information to the user's local file system.
     */
    final File trustFd = new File(USER_SECURITY_DIR + FILE_SEP + trustFlnm);
    final FileOutputStream trustFlnmFos = new FileOutputStream(trustFd);

    if (trustStream != null) {
        int nextByte = trustStream.read();
        while (nextByte != -1) {
            trustFlnmFos.write(nextByte);
            nextByte = trustStream.read();
        }
    }
    trustFlnmFos.close();

    return loginFd.toString();
}

From source file:com.buildml.main.CliUtils.java

/**
 * A helper function for genLocalizedMessage, used for recursion.
 * /*from  w ww .ja va 2s  .co m*/
 * @param lang The language to localize into (e.g. "en" or "fr").
 * @param message The message to be displayed (possibly including #include).
 * @param sb The StringBuffer we'll use to build up the final string.
 */
private static void genLocalizedMessageHelper(String lang, String message, StringBuffer sb) {

    /* tokenize the string, and handle each line separately */
    String[] lines = message.split("\n");
    for (int i = 0; i < lines.length; i++) {
        String thisLine = lines[i];

        /* 
         * If this line contains an #include directive, read the file content, then
         * call ourselves recursively to process the content.
         */
        if (thisLine.matches("#include .*")) {
            String includeLine[] = thisLine.split(" ");

            /* try to open the file (resource) as a stream */
            String fileName = "messages/" + lang + "/" + includeLine[1];
            InputStream inStream = ClassLoader.getSystemResourceAsStream(fileName);
            if (inStream == null) {
                sb.append("<missing include: " + fileName + ">\n");
            }

            /* read the stream into a string, then recursively process it */
            else {
                try {
                    String content = IOUtils.toString(inStream, "UTF-8");
                    genLocalizedMessageHelper(lang, content, sb);

                } catch (IOException e1) {
                    sb.append("<invalid include: " + fileName + ">\n");
                }

                try {
                    inStream.close();
                } catch (IOException e) {
                    /* nothing */
                }
            }
        }

        /* no #include directive, so just include the line verbatim */
        else {
            sb.append(lines[i]);
            sb.append('\n');
        }
    }

}

From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

/**
 * Prepare instrumentation exceptions.//from w w w . ja  v a2  s .  co  m
 */
private static void prepareInstrumentationExceptions() {
    // well known exceptions
    exceptions.add("java.lang.ref.Reference");
    exceptions.add("java.lang.ref.Finalizer");
    exceptions.add("se.sics.kompics.p2p.simulator.P2pSimulator");
    exceptions.add("org.apache.log4j.PropertyConfigurator");
    exceptions.add("org.apache.log4j.helpers.FileWatchdog");
    exceptions.add("org.mortbay.thread.QueuedThreadPool");
    exceptions.add("org.mortbay.io.nio.SelectorManager");
    exceptions.add("org.mortbay.io.nio.SelectorManager$SelectSet");
    exceptions.add("org.apache.commons.math.stat.descriptive.SummaryStatistics");
    exceptions.add("org.apache.commons.math.stat.descriptive.DescriptiveStatistics");

    // try to add user-defined exceptions from properties file
    InputStream in = ClassLoader.getSystemResourceAsStream("timer.interceptor.properties");
    Properties p = new Properties();
    if (in != null) {
        try {
            p.load(in);
            for (String classname : p.stringPropertyNames()) {
                String value = p.getProperty(classname);
                if (value != null && value.equals("IGNORE")) {
                    exceptions.add(classname);
                    logger.debug("Adding instrumentation exception {}", classname);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        logger.debug("Could not find timer.interceptor.properties");
    }
}

From source file:org.firstopen.singularity.devicemgr.interrogator.WaveTrend_IO.java

public static Properties getProperties(String fileName) throws Exception {
    // getResource at the momment hard-wire for now.
    InputStream is = ClassLoader.getSystemResourceAsStream(fileName);
    Properties properties = new Properties();

    if (is == null) {
        throw new Exception(fileName + " not found");
    }/*w  w  w  .  j  a va 2  s  .  c  om*/
    properties.load(is);

    return properties;

}

From source file:org.colombbus.tangara.Configuration.java

private boolean testExecutionMode() {
    executionMode = false;/* ww  w .j  a  v  a 2s  .  c o  m*/
    JarFile file = null;
    try {
        file = new JarFile(getTangaraPath());
        ZipEntry entry = file.getEntry(EXECUTION_PROPERTIES_FILENAME);
        if (entry != null) {
            executionMode = true;
            System.out.println("execution mode detected");
            Properties executionProperties = new Properties();
            InputStream ips = ClassLoader.getSystemResourceAsStream(EXECUTION_PROPERTIES_FILENAME);
            executionProperties.load(ips);
            if (executionProperties.containsKey("main-program")) {
                String mainTangaraFile = executionProperties.getProperty("main-program");
                System.out.println("main tangara file: " + mainTangaraFile);
                properties.setProperty("main-program", mainTangaraFile);
            } else {
                System.err.println("error : main program not specified");
            }
            if (executionProperties.containsKey("language")) {
                String language = executionProperties.getProperty("language");
                properties.setProperty("language", language);
                System.out.println("language: " + language);
            } else {
                System.err.println("error : language not specified");
            }
            if (executionProperties.containsKey("resources")) {
                String resources = executionProperties.getProperty("resources");
                properties.setProperty("program.resources", resources);
                System.out.println("resources: " + resources);
            } else {
                System.err.println("error : resources not specified");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                System.err.println("error while closing tangara JAR file");
            }
        }
    }
    return executionMode;
}

From source file:oracle.kv.hadoop.table.TableInputFormatBase.java

/**
 * Set/create the artifacts required to connect to and interact
 * with a secure store; specifically, a login properties file,
 * a trust file containing public keys and/or certificates, and
 * <code>PasswordCredentials</code>. If the value input for the
 * <code>loginFile</code> and <code>trustFile</code> parameter
 * is a fully-qualified path, then this method initializes the
 * corresponding static variables to those values so that the
 * <code>getSplits</code> method can contact a secure store, extracts
 * the filenames from those paths, uses those values to initialize
 * the corresponding static filename variables used to initialize
 * the splits that are created, and returns.
 * <p>//www.ja va  2  s .c o m
 * If the value input for the <code>loginFile</code> and
 * <code>trustFile</code> parameter is not a fully-qualified path,
 * then this method uses the given file names to retrieve the contents
 * of the associated login file and trust file as resources from
 * the classpath, and writes that information to corresponding files
 * on the local file system (in a directory owned by the user under
 * which the application is executed). After generating the local
 * files, the fully-qualified paths to those files are used to
 * initialize the corresponding static variables so that the
 * <code>getSplits</code> method can contact a secure store.
 */
private static void setLocalKVSecurity(final String loginFile,
        final PasswordCredentials userPasswordCredentials, final String trustFile) throws IOException {

    if (loginFile == null) {
        return;
    }

    if (userPasswordCredentials == null) {
        return;
    }

    if (trustFile == null) {
        return;
    }

    final File loginFd = new File(loginFile);
    boolean loginIsAbsolute = false;
    if (loginFd.isAbsolute()) {
        loginIsAbsolute = true;
        TableInputFormatBase.localLoginFile = loginFile;
        TableInputFormatBase.loginFlnm = loginFd.getName();
    } else {
        TableInputFormatBase.loginFlnm = loginFile;
    }

    TableInputFormatBase.passwordCredentials = userPasswordCredentials;

    final File trustFd = new File(trustFile);
    boolean trustIsAbsolute = false;
    if (trustFd.isAbsolute()) {
        trustIsAbsolute = true;
        TableInputFormatBase.trustFlnm = trustFd.getName();
    } else {
        TableInputFormatBase.trustFlnm = trustFile;
    }

    if (loginIsAbsolute && trustIsAbsolute) {
        return;
    }

    /*
     * If loginFile and/or trustFile is a filename and not an absolute
     * path, then generate local versions of the file.
     */
    final File userSecurityDirFd = new File(USER_SECURITY_DIR);
    if (!userSecurityDirFd.exists()) {
        if (!userSecurityDirFd.mkdirs()) {
            throw new IOException("failed to create " + userSecurityDirFd);
        }
    }

    final ClassLoader cl = TableInputFormatBase.class.getClassLoader();

    if (!loginIsAbsolute) {

        InputStream loginStream = null;
        if (cl != null) {
            loginStream = cl.getResourceAsStream(loginFlnm);
        } else {
            loginStream = ClassLoader.getSystemResourceAsStream(loginFlnm);
        }

        /*
         * Retrieve the login configuration as a resource from the
         * classpath, and write that information to the user's local
         * file system. But exclude any properties related to user
         * authorization; that is, exclude all properties of the form
         * 'oracle.kv.auth.*", to prevent those property values from
         * being sent and cached on the DataNodes.
         */
        final Properties loginProps = new Properties();
        if (loginStream != null) {
            loginProps.load(loginStream);
        }

        /* Exclude 'oracle.kv.auth.*" properties. */
        loginProps.remove(KVSecurityConstants.AUTH_USERNAME_PROPERTY);
        loginProps.remove(KVSecurityConstants.AUTH_WALLET_PROPERTY);
        loginProps.remove(KVSecurityConstants.AUTH_PWDFILE_PROPERTY);

        /* Strip off the path of the trust file. */
        final String trustProp = loginProps.getProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY);
        if (trustProp != null) {
            final File trustPropFd = new File(trustProp);
            if (!trustPropFd.exists()) {
                loginProps.setProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY, trustPropFd.getName());
            }
        }

        final File absoluteLoginFd = new File(USER_SECURITY_DIR + FILE_SEP + loginFlnm);
        final FileOutputStream loginFos = new FileOutputStream(absoluteLoginFd);
        try {
            loginProps.store(loginFos, null);
        } finally {
            loginFos.close();
        }

        TableInputFormatBase.localLoginFile = absoluteLoginFd.toString();
    }

    if (!trustIsAbsolute) {

        InputStream trustStream = null;
        if (cl != null) {
            trustStream = cl.getResourceAsStream(trustFlnm);
        } else {
            trustStream = ClassLoader.getSystemResourceAsStream(trustFlnm);
        }

        /*
         * Retrieve the trust credentials as a resource from the classpath,
         * and write that information to the user's local file system.
         */
        final File absoluteTrustFd = new File(USER_SECURITY_DIR + FILE_SEP + trustFlnm);
        final FileOutputStream trustFlnmFos = new FileOutputStream(absoluteTrustFd);

        try {
            int nextByte = trustStream.read();
            while (nextByte != -1) {
                trustFlnmFos.write(nextByte);
                nextByte = trustStream.read();
            }
        } finally {
            trustFlnmFos.close();
        }
    }
}

From source file:com.chtr.tmoauto.webui.CommonFunctions.java

/**
 * Compares two images, returning true if they are similar enough to constitute a match.
 *
 * @param img1 The first image to compare
 * @param img2 The second image to compare
 * @param errorsPerThousandThreshold The acceptable errors per thousand (pixels); i.e. haw many mismatched
 *           pixels are there allowed to be before the images are considered different. The lower the
 *           number the more strict the comparison will be
 * @return/*  w  w w.  j a v  a  2 s  .c o  m*/
 * @throws IOException
 */
public static boolean compareImages(String image1, String image2, long errorsPerThousandThreshold) {
    try {
        BufferedImage img1 = ImageIO.read(ClassLoader.getSystemResourceAsStream(image1));
        BufferedImage img2 = ImageIO.read(ClassLoader.getSystemResourceAsStream(image2));
        if (img1.getWidth() != img2.getWidth() || img1.getHeight() != img2.getHeight()) {
            log.trace("The two images are different sizes, automatically returning false");
            return false;
        }
        long ept = compareRGB24Images(img1, img2, 0, 0, img1.getWidth(), img1.getHeight(),
                DEFAULT_KERNEL_RADIUS);
        boolean match = ept <= errorsPerThousandThreshold;
        log.info("Match:[{}]  Err/1K:[{}]  Limit:[{}]  PixErrLim:[{}]", match, ept, errorsPerThousandThreshold,
                PIXEL_ERROR_LIMIT);
        return match;
    } catch (Exception ex) {
        log.error("Error", ex);
    }
    return false;
}

From source file:org.regenstrief.util.Util.java

/**
 * Retrieves the InputStream from the given location, attempting to open it by any means,
 * without decompressing//from ww w.ja v a  2  s  . c o m
 * 
 * @param location the location of the InputStream
 * @return the InputStream
 **/
public final static InputStream getRawStream(final String location) {
    InputStream stream = null;
    String s = location;
    final String sep = getFileSeparator();
    String paths[] = null;
    int n = 1;

    for (int i = 0; i < n; i++) {
        if (i > 0) {
            if (contains(paths[i - 1], sep)) {
                paths[i - 1] = paths[i - 1].substring(0, paths[i - 1].lastIndexOf(sep) + 1);
            }
            s = paths[i - 1] + location;
        }

        try {
            stream = getRawStreamFromURL(s);
        } catch (final Exception e) {
        }
        if (stream != null) {
            break;
        }
        try {
            stream = Util.class.getResourceAsStream(s);
        } catch (final Exception e) {
        }
        if (stream != null) {
            break;
        }
        try {
            stream = Util.class.getClassLoader().getResourceAsStream(s);
            //stream = getStream(Util.class.getClassLoader(), s);
        } catch (final Exception e) {
        }
        if (stream != null) {
            break;
        }
        try {
            stream = ClassLoader.getSystemResourceAsStream(s);
        } catch (final Exception e) {
        }
        if (stream != null) {
            break;
        }
        /*try
        {   stream = getStream(ClassLoader.getSystemClassLoader(), s);
        } catch (Exception e) {}
        if (stream != null)
        {   break;
        }*/
        try {
            stream = new FileInputStream(s);
        } catch (final Exception e) {
        }
        if (stream != null) {
            break;
        }

        if (i == 0) {
            paths = getClassPath();
            n = length(paths);
            n = n > 0 ? n + 1 : n;
        }
    }

    if ((stream == null) && (location.charAt(0) != '/')) {
        return getRawStream('/' + location);
    }

    return stream;
}