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.lpe.common.util.system.LpeSystemUtils.java

/**
 * Detects and returns the root folder of the running application using the
 * passed class to locate the directory.
 * //  www  . jav  a2s. c o  m
 * @param mainClass
 *            class used to locate directory
 * @return returns the root folder of the running application.
 */
public static String getRootFolder(Class<?> mainClass) {
    if (mainClass == null) {
        mainClass = LpeSystemUtils.class;
    }

    final String baseErrorMsg = "Cannot locate root folder.";

    final String classFile = mainClass.getName().replaceAll("\\.", "/") + ".class";
    final URL classURL = ClassLoader.getSystemResource(classFile);

    String fullPath = "";
    String sampleClassFile = "/org/sopeco/util/Tools.class";
    if (classURL == null) {
        LpeSystemUtils tempObject = new LpeSystemUtils();
        fullPath = tempObject.getClass().getResource(sampleClassFile).toString();
        // logger.warn("{} The application may be running in an OSGi container.",
        // baseErrorMsg);
        // return ".";
    } else {
        fullPath = classURL.toString();
    }

    try {
        fullPath = URLDecoder.decode(fullPath, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("{} UTF-8 encoding is not supported.", baseErrorMsg);
        return ".";
    }

    if (fullPath.indexOf("file:") > -1) {
        fullPath = fullPath.replaceFirst("file:", "").replaceFirst(classFile, "");
        fullPath = fullPath.substring(0, fullPath.lastIndexOf('/'));
    }
    if (fullPath.indexOf("jar:") > -1) {
        fullPath = fullPath.replaceFirst("jar:", "").replaceFirst("!" + classFile, "");
        fullPath = fullPath.substring(0, fullPath.lastIndexOf('/'));
    }
    if (fullPath.indexOf("bundleresource:") > -1) {
        fullPath = fullPath.substring(0, fullPath.indexOf(sampleClassFile));
    }

    // replace the java separator with the
    fullPath = fullPath.replace('/', File.separatorChar);

    // remove leading backslash
    if (fullPath.startsWith("\\")) {
        fullPath = fullPath.substring(1);
    }

    // remove the final 'bin'
    final int binIndex = fullPath.indexOf(File.separator + "bin");
    if (binIndex == fullPath.length() - "/bin".length()) {
        fullPath = fullPath.substring(0, binIndex);
    }

    LOGGER.debug("Root folder is detected at {}.", fullPath);

    return fullPath;
}

From source file:dk.dma.ais.decode.DecodeTest.java

/**
 * Decode all messages in a file Tries to handle proprietary messages
 * //  w  ww. java2s .  c  o  m
 * Demonstrates and tests the process of decoding lines into Vdm messages, and the decoding into AIS messages
 * 
 * @throws IOException
 */
@Test
public void readLoopTest() throws IOException {
    // Make a list of proprietary handlers

    // Open file
    URL url = ClassLoader.getSystemResource("stream_example.txt");
    Assert.assertNotNull(url);
    try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
        Assert.assertNotNull(in);
        String line;

        // Prepare message classes
        AisMessage message;
        Vdm vdm = new Vdm();
        LinkedList<IProprietaryTag> tags = new LinkedList<>();

        while ((line = in.readLine()) != null) {

            // Ignore everything else than sentences
            if (!line.startsWith("$") && !line.startsWith("!")) {
                continue;
            }

            // Check if proprietary line
            if (ProprietaryFactory.isProprietaryTag(line)) {
                // Try to parse with one the registered factories in
                // META-INF/services/dk.dma.ais.proprietary.ProprietaryFactory
                IProprietaryTag tag = ProprietaryFactory.parseTag(new SentenceLine(line));
                if (tag != null) {
                    tags.add(tag);
                }
                continue;
            }

            // Handle VDM/VDO line
            try {
                int result = vdm.parse(new SentenceLine(line));
                // LOG.info("result = " + result);
                if (result == 0) {
                    message = AisMessage.getInstance(vdm);
                    Assert.assertNotNull(message);
                    if (tags.size() > 0) {
                        message.setTags(tags);
                    }

                    // Message ready for handling

                } else if (result == 1) {
                    // Wait for more data
                    continue;
                } else {
                    LOG.error("Failed to parse line: " + line + " result = " + result);
                    Assert.assertTrue(false);
                }

            } catch (Exception e) {
                LOG.info("VDM failed: " + e.getMessage() + " line: " + line + " tag: "
                        + (tags.size() > 0 ? tags.peekLast() : "null"));
                Assert.assertTrue(false);
            }

            // Create new VDM
            vdm = new Vdm();
            tags.clear();
        }
    }
}

From source file:com.meyling.telnet.startup.Loader.java

/**
   This method will search for <code>resource</code> in different
   places. The search order is as follows:
        //from  w w  w.  ja v a2s .  c o  m
   <ol>
        
   <p><li>Search for <code>resource</code> using the thread context
   class loader under Java2. If that fails, search for
   <code>resource</code> using the class loader that loaded this
   class (<code>Loader</code>). Under JDK 1.1, only the the class
   loader that loaded this class (<code>Loader</code>) is used.
        
   <p><li>Try one last time with
   <code>ClassLoader.getSystemResource(resource)</code>, that is is
   using the system class loader in JDK 1.2 and virtual machine's
   built-in class loader in JDK 1.1.
        
   </ol>
*/
static public URL getResource(String resource) {
    ClassLoader classLoader = null;
    URL url = null;

    try {
        if (!java1) {
            classLoader = getTCL();
            if (classLoader != null) {
                trace.debug("Trying to find [" + resource + "] using context classloader " + classLoader + ".");
                url = classLoader.getResource(resource);
                if (url != null) {
                    return url;
                }
            }
        }

        // We could not find resource. Ler us now try with the
        // classloader that loaded this class.
        classLoader = Loader.class.getClassLoader();
        if (classLoader != null) {
            trace.debug("Trying to find [" + resource + "] using " + classLoader + " class loader.");
            url = classLoader.getResource(resource);
            if (url != null) {
                return url;
            }
        }
    } catch (Throwable t) {
        trace.warn(TSTR, t);
    }

    // Last ditch attempt: get the resource from the class path. It
    // may be the case that clazz was loaded by the Extentsion class
    // loader which the parent of the system class loader. Hence the
    // code below.
    trace.debug("Trying to find [" + resource + "] using ClassLoader.getSystemResource().");
    return ClassLoader.getSystemResource(resource);
}

From source file:com.antelink.sourcesquare.server.EmbeddedServer.java

public void startServer() throws Exception {

    logger.debug("adding webhandler");
    getClass().getClassLoader();/* ww w.  j  a  va  2s. com*/
    this.webContext = new WebAppContext(ClassLoader.getSystemResource("webapp/").toExternalForm(), "/");
    FilterHolder resultFilter = new FilterHolder(new ResultFilter(this.eventBus));
    this.webContext.addFilter(resultFilter, "/result.jsp", 1);

    logger.debug("loading: " + ClassLoader.getSystemResource("webapp/").toExternalForm());
    this.contexts.addHandler(this.webContext);

    logger.debug("adding status servlet");
    ServletHolder statusService = new ServletHolder(new StatusServlet());
    this.servletContext.addServlet(statusService, "/status");

    logger.debug("adding publish servlet");
    ServletHolder publishService = new ServletHolder(this.publishServlet);
    this.servletContext.addServlet(publishService, "/publish");

    logger.debug("adding shutdown servlet");
    ServletHolder shutdownService = new ServletHolder(this.shutdownServlet);
    this.servletContext.addServlet(shutdownService, "/shutdown");

    logger.debug("adding time servlet");
    ServletHolder timeService = new ServletHolder(new TimeServlet());
    this.servletContext.addServlet(timeService, "/time");

    logger.debug("adding quapcha servlet");
    ServletHolder quaptchaService = new ServletHolder(new QuaptchaServlet());
    this.servletContext.addServlet(quaptchaService, "/check/captcha");

    this.contexts.addHandler(this.servletContext);

    ErrorHandler errorHandler = new ErrorHandler();

    this.webContext.setErrorHandler(errorHandler);
    this.servletContext.setErrorHandler(errorHandler);

    this.jetty.setHandler(this.contexts);

    bind();

    this.jetty.start();
}

From source file:com.datamoin.tajo.tpcds.TpcDSTestUtil.java

public static void createTables(String database, TajoClient client) throws Exception {
    String dataDir = getDataDir();
    if (dataDir == null || dataDir.isEmpty()) {
        throw new IOException("No TPCDS_DATA_DIR property. Use -DTPCDS_DATA_DIR=<data dir>");
    }/* w w w  . j  a  va 2 s . c om*/

    if (dataDir.startsWith("hdfs://")) {
        Path path = new Path(dataDir);
        FileSystem fs = path.getFileSystem(new Configuration());
        for (String eachTable : tableNames) {
            Path tableDataDir = new Path(path, eachTable);
            if (!fs.exists(tableDataDir)) {
                throw new IOException(eachTable + " data dir [" + tableDataDir + "] not exists.");
            }
        }
    } else {
        File dataDirFile = new File(dataDir);
        if (!dataDirFile.exists()) {
            throw new IOException("TPCDS_DATA_DIR [" + dataDir + "] not exists.");
        }
        if (dataDirFile.isFile()) {
            throw new IOException("TPCDS_DATA_DIR [" + dataDir + "] is not a directory.");
        }

        for (String eachTable : tableNames) {
            File tableDataDir = new File(dataDirFile, eachTable);
            if (!tableDataDir.exists()) {
                throw new IOException(eachTable + " data dir [" + tableDataDir + "] not exists.");
            }
        }
    }

    KeyValueSet opt = new KeyValueSet();
    opt.set(StorageConstants.TEXT_DELIMITER, StorageConstants.DEFAULT_FIELD_DELIMITER);

    LOG.info("Create database: " + database);
    client.executeQuery("create database if not exists " + database);

    Path tpcdsResourceURL = new Path(ClassLoader.getSystemResource("tpcds").toString());

    Path ddlPath = new Path(tpcdsResourceURL, "ddl");
    FileSystem localFs = FileSystem.getLocal(new Configuration());

    FileStatus[] files = localFs.listStatus(ddlPath);

    String dataDirWithPrefix = dataDir;
    if (dataDir.indexOf("://") < 0) {
        dataDirWithPrefix = "file://" + dataDir;
    }

    for (FileStatus eachFile : files) {
        if (eachFile.isFile()) {
            String tableName = eachFile.getPath().getName().split("\\.")[0];
            String query = FileUtil.readTextFile(new File(eachFile.getPath().toUri()));
            query = query.replace("${DB}", database);
            query = query.replace("${DATA_LOCATION}", dataDirWithPrefix + "/" + tableName);

            LOG.info("Create table:" + tableName + "," + query);
            client.executeQuery(query);
        }
    }
}

From source file:com.sonatype.security.ldap.AbstractLdapTestCase.java

private String getFilePath(String filename) {
    // first check if the file is defined for the class
    String resourcePath = this.getClass().getName().replace('.', '/');
    resourcePath += "-" + filename;

    // now check if it exists
    if (ClassLoader.getSystemResource(resourcePath) != null) {
        return resourcePath;
    } else {/*w ww  . j a  va2 s. c  o  m*/
        return "/defaults/" + filename;
    }
}

From source file:com.novoda.imageloader.core.file.util.FileUtilTest.java

@Test
public void shouldCopyStreams() throws FileNotFoundException, URISyntaxException {
    URL testFile = ClassLoader.getSystemResource("testFile1");
    File from = new File(testFile.toURI());
    assertTrue(from.exists());//from  w  w  w  .  ja va  2s .c  om
    File to = new File(cacheDir.getAbsolutePath() + "testFile3");
    InputStream in = new FileInputStream(from);
    OutputStream out = new FileOutputStream(to);

    fileUtil.copyStream(in, out);

    FileAssert.assertBinaryEquals(from, to);
}

From source file:fr.gael.dhus.server.http.webapp.owc.controller.OwcMenuController.java

@PreAuthorize("isAuthenticated () AND hasRole('ROLE_DATA_MANAGER')")
@RequestMapping(value = "/settings/menu", method = RequestMethod.PUT)
public ResponseEntity<?> setMenu(@RequestBody MenuData body) throws JSONException {

    URL configFile = ClassLoader.getSystemResource("../etc/conf/menu.json");
    if (configFile != null && body != null) {
        logger.debug("Loading configuration file " + configFile.getPath());

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

            PrintWriter fileWriter = new PrintWriter(new FileOutputStream(configFile.getPath(), false));
            fileWriter.println("{\"sections\":[");
            for (MenuSectionsData section : body.getSections()) {
                fileWriter.println("{");
                if (section.getTitle() != null && !section.getTitle().isEmpty())
                    fileWriter.println("\"title\":\"" + section.getTitle() + "\",");
                if (section.getIcon() != null && !section.getIcon().isEmpty())
                    fileWriter.println("\"icon\":\"" + section.getIcon() + "\",");
                if (section.getComponent() != null && !section.getComponent().isEmpty())
                    fileWriter.println("\"component\":\"" + section.getComponent() + "\",");
                if (section.getWidth() != null && !section.getWidth().isEmpty())
                    fileWriter.println("\"width\":\"" + section.getWidth() + "\",");
                if (section.getRemoteUrl() != null && !section.getRemoteUrl().isEmpty())
                    fileWriter.println("\"remoteUrl\":\"" + section.getRemoteUrl() + "\"");
                else
                    fileWriter.println("\"remoteUrl\":\"\"");
                fileWriter.println("},");

            }
            fileWriter.println("]}");
            fileWriter.close();

            return new ResponseEntity<>("{\"code\":\"success\"}", HttpStatus.OK);
        } catch (IOException e) {

            logger.error(" Cannot write menu configration file ");
            e.printStackTrace();
            return new ResponseEntity<>("{\"code\":\"unauthorized\"}", HttpStatus.UNAUTHORIZED);
        }
    } else {
        logger.error(" Cannot get menu configration file ");
        return new ResponseEntity<>("{\"code\":\"unauthorized\"}", HttpStatus.UNAUTHORIZED);
    }

}

From source file:org.oncoblocks.centromere.dataimport.cli.test.ImportCommandTests.java

@Test
public void importRunnerTest() throws Exception {
    Assert.isTrue(sampleDataRepository.count() == 0);
    Assert.isTrue(dataFileRepository.count() == 0);
    Assert.isTrue(dataSetRepository.count() == 0);
    String[] args = { "import", "-t", "sample_data", "-i",
            ClassLoader.getSystemResource("placeholder.txt").getPath(), "--skip-invalid-records", "-d",
            "{\"label\": \"test\", \"name\": \"Test data\", \"source\": \"internal\"}" };
    ImportCommandArguments arguments = new ImportCommandArguments();
    JCommander commander = new JCommander();
    commander.addCommand("import", arguments);
    commander.parse(args);/*from   ww  w. ja v  a 2 s  .  co  m*/
    ImportCommandRunner runner = new ImportCommandRunner(manager);
    runner.run(arguments);
    Assert.isTrue(sampleDataRepository.count() == 5);
    Assert.isTrue(dataFileRepository.count() == 1);
    Assert.isTrue(dataSetRepository.count() == 1);
}

From source file:ch.sdi.core.impl.data.CsvCollectorTest.java

/**
 * @param aFilename//from www.  j  a v  a 2 s  . co  m
 * @return
 */
private File toFile(String aFilename) {
    URL url = ClassLoader.getSystemResource(aFilename);
    File file = new File(url.getPath());
    return file;
}