Example usage for java.lang ClassLoader getSystemResource

List of usage examples for java.lang ClassLoader getSystemResource

Introduction

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

Prototype

public static URL getSystemResource(String name) 

Source Link

Document

Find a resource of the specified name from the search path used to load classes.

Usage

From source file:org.wte4j.impl.WordTemplateTest.java

private WordTemplate<String> createWordTemplate(String pathToTemplateFile) throws IOException {
    File templateDocument = FileUtils.toFile(ClassLoader.getSystemResource(pathToTemplateFile));
    byte[] templateContent = FileUtils.readFileToByteArray(templateDocument);

    PersistentTemplate persistentData = new PersistentTemplate();
    persistentData.setDocumentName("test");
    persistentData.setLanguage("de");
    persistentData.setInputType(String.class);
    persistentData.setEditedAt(new Date());
    persistentData.setCreatedAt(new Date());
    persistentData.setEditor(new User("default", "default"));
    persistentData.setContent(templateContent);

    WordTemplate<String> wordTemplate = new WordTemplate<String>(persistentData, new SimpleValueModelService(),
            new SimpleFormatterFactory());
    return wordTemplate;
}

From source file:com.alfaariss.oa.engine.core.EngineLauncher.java

private Properties getConfigProperties() throws OAException {
    _logger.debug(//from  ww w.j  av a  2 s .c  om
            "Search for '" + PROPERTIES_FILENAME + "' as resource of the current thread context classloader");
    URL urlProperties = Thread.currentThread().getContextClassLoader().getResource(PROPERTIES_FILENAME);
    if (urlProperties != null) {
        String sProperties = urlProperties.getFile();
        _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in: " + sProperties);
        File fProperties = new File(sProperties);
        if (fProperties != null && fProperties.exists()) {
            _logger.info("Updating configuration items with the items in: " + fProperties.getAbsolutePath());
            return getProperties(fProperties);
        }

        _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
    } else
        _logger.info(
                "No '" + PROPERTIES_FILENAME + "' found as resource of the current thread context classloader");

    _logger.debug(
            "Search for '" + PROPERTIES_FILENAME + "' as resource of the classloader of the current class");
    urlProperties = EngineLauncher.class.getResource(PROPERTIES_FILENAME);
    if (urlProperties != null) {
        String sProperties = urlProperties.getFile();
        _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in: " + sProperties);
        File fProperties = new File(sProperties);
        if (fProperties != null && fProperties.exists()) {
            _logger.info("Updating configuration items with the items in: " + fProperties.getAbsolutePath());
            return getProperties(fProperties);
        }

        _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
    } else
        _logger.info(
                "No '" + PROPERTIES_FILENAME + "' found as resource of the classloader of the current class");

    _logger.debug("Search for '" + PROPERTIES_FILENAME + "' as system resource of the static classloader");
    urlProperties = ClassLoader.getSystemResource(PROPERTIES_FILENAME);
    if (urlProperties != null) {
        String sProperties = urlProperties.getFile();
        _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in: " + sProperties);
        File fProperties = new File(sProperties);
        if (fProperties != null && fProperties.exists()) {
            _logger.info("Updating configuration items with the items in: " + fProperties.getAbsolutePath());
            return getProperties(fProperties);
        }

        _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
    } else
        _logger.info("No '" + PROPERTIES_FILENAME + "' found as system resource of the static classloader");

    return null;
}

From source file:org.pentaho.pac.server.common.ThreadSafeHttpClient.java

private static void loadProperties() {
    FileInputStream fis = null;//w ww.  ja va 2s . c o m
    Properties properties = null;
    try {
        URL url = ClassLoader.getSystemResource(DEFAULT_CONSOLE_PROPERTIES_FILE_NAME);
        fis = new FileInputStream(new File(url.toURI()));
    } catch (Exception e) {
        contentCharacterSet = DEFAULT_CONTENT_CHARACTERSET_VALUE;
    }
    if (null != fis) {
        properties = new Properties();
        try {
            properties.load(fis);
        } catch (IOException e) {
            contentCharacterSet = DEFAULT_CONTENT_CHARACTERSET_VALUE;
        }
    }
    if (properties != null) {
        contentCharacterSet = properties.getProperty(CONTENT_CHARACTERSET_PROPERTY,
                DEFAULT_CONTENT_CHARACTERSET_VALUE);
    } else {
        contentCharacterSet = DEFAULT_CONTENT_CHARACTERSET_VALUE;
    }
}

From source file:org.openpnp.model.Configuration.java

public void load() throws Exception {
    boolean forceSave = false;
    boolean overrideUserConfig = Boolean.getBoolean("overrideUserConfig");

    try {/*from  w w w  . j  a v  a2  s  .  c  om*/
        File file = new File(configurationDirectory, "packages.xml");
        if (overrideUserConfig || !file.exists()) {
            logger.info("No packages.xml found in configuration directory, loading defaults.");
            file = File.createTempFile("packages", "xml");
            FileUtils.copyURLToFile(ClassLoader.getSystemResource("config/packages.xml"), file);
            forceSave = true;
        }
        loadPackages(file);
    } catch (Exception e) {
        String message = e.getMessage();
        if (e.getCause() != null && e.getCause().getMessage() != null) {
            message = e.getCause().getMessage();
        }
        throw new Exception("Error while reading packages.xml (" + message + ")", e);
    }

    try {
        File file = new File(configurationDirectory, "parts.xml");
        if (overrideUserConfig || !file.exists()) {
            logger.info("No parts.xml found in configuration directory, loading defaults.");
            file = File.createTempFile("parts", "xml");
            FileUtils.copyURLToFile(ClassLoader.getSystemResource("config/parts.xml"), file);
            forceSave = true;
        }
        loadParts(file);
    } catch (Exception e) {
        String message = e.getMessage();
        if (e.getCause() != null && e.getCause().getMessage() != null) {
            message = e.getCause().getMessage();
        }
        throw new Exception("Error while reading parts.xml (" + message + ")", e);
    }

    try {
        File file = new File(configurationDirectory, "machine.xml");
        if (overrideUserConfig || !file.exists()) {
            logger.info("No machine.xml found in configuration directory, loading defaults.");
            file = File.createTempFile("machine", "xml");
            FileUtils.copyURLToFile(ClassLoader.getSystemResource("config/machine.xml"), file);
            forceSave = true;
        }
        loadMachine(file);
    } catch (Exception e) {
        String message = e.getMessage();
        if (e.getCause() != null && e.getCause().getMessage() != null) {
            message = e.getCause().getMessage();
        }
        throw new Exception("Error while reading machine.xml (" + message + ")", e);
    }

    loaded = true;

    for (ConfigurationListener listener : listeners) {
        listener.configurationLoaded(this);
    }

    if (forceSave) {
        logger.info("Defaults were loaded. Saving to configuration directory.");
        configurationDirectory.mkdirs();
        save();
    }

    for (ConfigurationListener listener : listeners) {
        listener.configurationComplete(this);
    }
}

From source file:com.linkedin.thirdeye.hadoop.derivedcolumn.transformation.DerivedColumnTransformationTest.java

@Before
public void setUp() throws Exception {
    DerivedColumnTransformationPhaseMapper mapper = new DerivedColumnTransformationPhaseMapper();
    mapDriver = MapDriver.newMapDriver(mapper);
    Configuration configuration = mapDriver.getConfiguration();
    configuration.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization,"
            + "org.apache.hadoop.io.serializer.WritableSerialization");

    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_TABLE_NAME.toString(), "collection");
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_DIMENSION_NAMES.toString(), "d1,d2,d3");
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_METRIC_NAMES.toString(), "m1,m2");
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_METRIC_TYPES.toString(), "INT,INT");
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_TIMECOLUMN_NAME.toString(), "hoursSinceEpoch");
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_TOPK_DIMENSION_NAMES.toString(), "d2,");
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_TOPK_METRICS.toString() + ".d2", "m1");
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_TOPK_KVALUES.toString() + ".d2", "1");

    ThirdEyeConfig thirdeyeConfig = ThirdEyeConfig.fromProperties(props);
    configuration/*from  w  w  w. jav  a 2s .  c  o  m*/
            .set(DerivedColumnTransformationPhaseConstants.DERIVED_COLUMN_TRANSFORMATION_PHASE_THIRDEYE_CONFIG
                    .toString(), OBJECT_MAPPER.writeValueAsString(thirdeyeConfig));

    Schema inputSchema = new Schema.Parser().parse(ClassLoader.getSystemResourceAsStream(AVRO_SCHEMA));
    setUpAvroSerialization(mapDriver.getConfiguration(), inputSchema);

    Schema outputSchema = new Schema.Parser()
            .parse(ClassLoader.getSystemResourceAsStream(TRANSFORMATION_SCHEMA));
    configuration
            .set(DerivedColumnTransformationPhaseConstants.DERIVED_COLUMN_TRANSFORMATION_PHASE_OUTPUT_SCHEMA
                    .toString(), outputSchema.toString());

    configuration.set(
            DerivedColumnTransformationPhaseConstants.DERIVED_COLUMN_TRANSFORMATION_PHASE_TOPK_PATH.toString(),
            ClassLoader.getSystemResource(TOPK_PATH).toString());

    TemporaryPath tmpPath = new TemporaryPath();
    outputPath = tmpPath.toString();
    configuration.set(DerivedColumnTransformationPhaseConstants.DERIVED_COLUMN_TRANSFORMATION_PHASE_OUTPUT_PATH
            .toString(), outputPath);

}

From source file:org.apache.james.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java

@Test
public void simpleEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    MailboxMessage mail = new SimpleMailboxMessage(MESSAGE_ID, date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/mail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    mail.setModSeq(MOD_SEQ);/*w  w w  .  j a v a2  s .c o m*/
    mail.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mail,
            ImmutableList.of(new MockMailboxSession("user1").getUser(),
                    new MockMailboxSession("user2").getUser()))).when(IGNORING_ARRAY_ORDER)
                            .when(IGNORING_VALUES)
                            .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/mail.json")));
}

From source file:it.greenvulcano.util.bin.BinaryUtils.java

/**
 * Loads the full content of a file.<br>
 * The file must be reachable via the <i>parent classloader</i>, or at least
 * via the <i>system classloader</i>.<br>
 * The full content of a file is then stored into a <code>byte</code> array.<br>
 * //from   w ww  .j  a  va2s.  com
 * @param filename
 *        the name of the file to be read
 * @return the full content of the file, stored into a <code>byte</code>
 *         array
 * @throws IOException
 *         if any I/O error occurs
 */
public static byte[] readFileAsBytesFromCP(String filename) throws IOException {
    filename = TextUtils.adjustPath(filename);
    URL url = ClassLoader.getSystemResource(filename);
    if (url == null) {
        throw new IOException("File " + filename + " not found in classpath");
    }

    InputStream in = null;
    try {
        in = url.openStream();
        return inputStreamToBytes(in);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java

/**
 * Extract template from class//from   w  w w.  j  a  v  a  2  s .c o m
 */
private void extractTemplate(File dst, String templateName) throws IOException, URISyntaxException {

    LOGGER.info("Extracting OpenDJ template....");
    if (!dst.exists()) {
        LOGGER.debug("Creating target dir {}", dst.getPath());
        dst.mkdirs();
    }

    templateRoot = new File(DATA_TEMPLATE_DIR, templateName);
    String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource)

    // Determing if we need to extract from JAR or directory
    if (templateRoot.isDirectory()) {
        LOGGER.trace("Need to do directory copy.");
        MiscUtil.copyDirectory(templateRoot, dst);
        return;
    }

    LOGGER.debug("Try to localize OpenDJ Template in JARs as " + templateRootPath);

    URL srcUrl = ClassLoader.getSystemResource(templateRootPath);
    LOGGER.debug("srcUrl " + srcUrl);
    // sample:
    // file:/C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar!/test-data/opendj.template
    // output:
    // /C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar
    //
    // beware that in the URL there can be spaces encoded as %20, e.g.
    // file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar!/test-data/opendj.template
    //
    if (srcUrl.getPath().contains("!/")) {
        URI srcFileUri = new URI(srcUrl.getPath().split("!/")[0]); // e.g. file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar
        File srcFile = new File(srcFileUri);
        JarFile jar = new JarFile(srcFile);
        LOGGER.debug("Extracting OpenDJ from JAR file {} to {}", srcFile.getPath(), dst.getPath());

        Enumeration<JarEntry> entries = jar.entries();

        JarEntry e;
        byte buf[] = new byte[655360];
        while (entries.hasMoreElements()) {
            e = entries.nextElement();

            // skip other files
            if (!e.getName().contains(templateRootPath)) {
                continue;
            }

            // prepare destination file
            String filepath = e.getName().substring(templateRootPath.length());
            File dstFile = new File(dst, filepath);

            // test if directory
            if (e.isDirectory()) {
                LOGGER.debug("Create directory: {}", dstFile.getAbsolutePath());
                dstFile.mkdirs();
                continue;
            }

            LOGGER.debug("Extract {} to {}", filepath, dstFile.getAbsolutePath());
            // Find file on classpath
            InputStream is = ClassLoader.getSystemResourceAsStream(e.getName());
            // InputStream is = jar.getInputStream(e); //old way

            // Copy content
            OutputStream out = new FileOutputStream(dstFile);
            int len;
            while ((len = is.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            is.close();
        }
        jar.close();
    } else {
        try {
            File file = new File(srcUrl.toURI());
            File[] files = file.listFiles();
            for (File subFile : files) {
                if (subFile.isDirectory()) {
                    MiscUtil.copyDirectory(subFile, new File(dst, subFile.getName()));
                } else {
                    MiscUtil.copyFile(subFile, new File(dst, subFile.getName()));
                }
            }
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }
    LOGGER.debug("OpenDJ Extracted");
}

From source file:org.astrojournal.gui.AJMainGUI.java

/**
 * Set AstroJournal window.//from   ww  w  . jav a  2  s  . c  om
 */
private void setAJWindow() {
    // Configure AJMainGUI with basic parameters
    setTitle(AJMetaInfo.NAME.getInfo() + " " + AJMetaInfo.VERSION.getInfo());
    setIconImage(new ImageIcon(ClassLoader.getSystemResource("graphics/logo/aj_icon_32.png")).getImage());
    setSize(550, 580);
    setMinimumSize(new Dimension(520, 450));
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setResizable(true);
    getContentPane().setLayout(new BorderLayout());
}

From source file:org.apache.james.mailbox.elasticsearch.json.MailboxMessageToElasticSearchJsonTest.java

@Test
public void recursiveEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage recursiveMail = new SimpleMailboxMessage(date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/recursiveMail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    recursiveMail.setModSeq(MOD_SEQ);// ww  w . j  a va 2s .  c o m
    recursiveMail.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(recursiveMail,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .when(IGNORING_VALUES)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/recursiveMail.json")));
}