Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

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

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:com.smartsheet.api.internal.SmartsheetImpl.java

/**
 * Compose a User-Agent string that represents this version of the SDK (along with platform info)
 *
 * @return a User-Agent string//from ww  w.  j av a  2 s.c o  m
 */
private String generateUserAgent(String userAgent) {
    String title = null;
    String thisVersion = null;

    if (userAgent == null) {
        StackTraceElement[] callers = Thread.currentThread().getStackTrace();
        String module = null;
        String callerClass = null;
        int stackIdx;
        for (stackIdx = callers.length - 1; stackIdx >= 0; stackIdx--) {
            callerClass = callers[stackIdx].getClassName();
            try {
                Class<?> clazz = Class.forName(callerClass);
                ClassLoader classLoader = clazz.getClassLoader();
                // skip JRE classes
                if (classLoader == null) {
                    continue;
                }
                String classFilePath = callerClass.replace(".", "/") + ".class";
                URL classUrl = classLoader.getResource(classFilePath);
                if (classUrl != null) {
                    String classUrlPath = classUrl.getPath();
                    int jarSeparator = classUrlPath.indexOf('!');
                    if (jarSeparator > 0) {
                        module = classUrlPath.substring(0, jarSeparator);
                        // extract the last path element (the jar name only)
                        module = module.substring(module.lastIndexOf('/') + 1);
                        break;
                    }
                }
            } catch (Exception ex) {
            }
        }
        userAgent = module + "!" + callerClass;
    }
    try {
        final Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("sdk.properties"));
        thisVersion = properties.getProperty("sdk.version");
        title = properties.getProperty("sdk.name");
    } catch (IOException e) {
    }
    return title + "/" + thisVersion + "/" + userAgent + "/" + System.getProperty("os.name") + " "
            + System.getProperty("java.vm.name") + " " + System.getProperty("java.vendor") + " "
            + System.getProperty("java.version");
}

From source file:org.samjoey.gui.GraphicalViewer.java

private void selectedPGN(File file) {

    String fileLoc = file.getAbsolutePath();
    //fileLoc = "File:" + fileLoc.substring(2);
    if (fileLoc.substring(fileLoc.length() - 3).equals("pgn")) {
        for (int i = 0; i < fileLoc.length(); i++) {
            if (fileLoc.substring(i, i + 1).equals("/")) {
                fileLoc = fileLoc.substring(0, i) + "\\" + fileLoc.substring(i + 1);
            }/*from   w  w  w.  j av a 2  s  .  c  o m*/
        }
        try {
            // Below: Talk to JavaScript
            ScriptEngineManager factory = new ScriptEngineManager();
            // create JavaScript engine
            final ScriptEngine engine = factory.getEngineByName("JavaScript");
            // evaluate JavaScript code from given file - specified by first argument
            engine.put("engine", engine);
            ClassLoader cl = GraphicalViewer.class.getClassLoader();
            // Talk to GameLooper_1
            URL url = cl.getResource("\\org\\samjoey\\gameLooper\\GameLooper_1.js");
            String loopLoc = url.toString().substring(5);
            for (int i = 0; i < loopLoc.length() - 3; i++) {
                if (loopLoc.substring(i, i + 3).equals("%5c")) {
                    loopLoc = loopLoc.substring(0, i) + "/" + loopLoc.substring(i + 3);
                }
            }
            engine.put("loopLoc", loopLoc);
            // Talk to calcDefs_1
            url = cl.getResource("\\org\\samjoey\\calculator\\calcDefs_1.js");
            String defsLoc = url.toString().substring(5);
            for (int i = 0; i < defsLoc.length() - 3; i++) {
                if (defsLoc.substring(i, i + 3).equals("%5c")) {
                    defsLoc = defsLoc.substring(0, i) + "/" + defsLoc.substring(i + 3);
                }
            }
            engine.put("defsLoc", defsLoc);
            // Talk to Calculator
            url = cl.getResource("\\org\\samjoey\\calculator\\Calculator.js");
            String calcLoc = url.toString().substring(5);
            for (int i = 0; i < calcLoc.length() - 3; i++) {
                if (calcLoc.substring(i, i + 3).equals("%5c")) {
                    calcLoc = calcLoc.substring(0, i) + "/" + calcLoc.substring(i + 3);
                }
            }
            engine.put("calcLoc", calcLoc);
            String args[] = { "-g:false", fileLoc };
            engine.put("arguments", args);

            // Create a Thread to update the parser's progress bar
            parserProgress.setStringPainted(true);
            running = false;
            running = true;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    long last = 0l;
                    boolean print = true;
                    double p = .01;
                    while (engine.get("progress") == null || engine.get("size") == null
                            || Integer.parseInt((String) engine.get("progress")) != Integer
                                    .parseInt((String) engine.get("size"))) {
                        //if (Parser.numGames > 0 && Parser.progress == Parser.numGames) {
                        try {
                            parserProgress.setValue(Integer.parseInt((String) engine.get("progress")));
                            parserProgress.setMaximum(Integer.parseInt((String) engine.get("size")));
                            if (last == 0l) {
                                last = System.nanoTime();
                            }
                            if ((double) parserProgress.getValue() / (double) parserProgress.getMaximum() > p
                                    && print) {
                                //System.out.println(p + ": " + (System.nanoTime() - last));
                                //print = false;
                                p += .01;
                            }
                        } catch (Exception e) {
                        }
                        //} else {
                        //    parserProgress.setMaximum(Parser.numGames - 1);
                        //    parserProgress.setMinimum(0);
                        //    parserProgress.setValue(Parser.progress);
                        //}
                    }
                    // finally
                    parserProgress.setValue(parserProgress.getMaximum());
                }
            };
            thread.start();

            // I have no clue what's here!??
            engine.eval(new java.io.FileReader(
                    GraphicalViewer.class.getClassLoader().getResource("driver_1.js").toString().substring(5)));
            while (games == null || games.get((int) (Math.random() * games.size())).getVarData().size() < 20) {
                games = (LinkedList<Game>) engine.get("gameList");
            }
        } catch (ScriptException | FileNotFoundException ex) {
            Logger.getLogger(GraphicalViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (fileLoc.substring(fileLoc.length() - 4).equals("jsca")) {
        JSCAParser jsca = new JSCAParser(fileLoc);
        games = (LinkedList<Game>) jsca.getGamesList();
    }

    Set<String> keys = games.get(0).getVarData().keySet();
    for (String key : keys) {
        Variable_Chooser.addItem(key);
    }
    graphs = GraphUtility.getGraphs(games);

    setViewer(0, 0);
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 *//*  w  ww. j av  a  2  s.co m*/
public void contextInitialized(final ServletContextEvent sContextEvent) {
    final String methodName = SecurityServiceListener.CNAME
            + "#contextInitialized(final ServletContextEvent sContextEvent)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletContextEvent: {}", sContextEvent);
    }

    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ServletContext sContext = sContextEvent.getServletContext();
    final ClassLoader classLoader = SecurityServiceListener.class.getClassLoader();

    if (DEBUG) {
        DEBUGGER.debug("ServletContext: {}", sContext);
        DEBUGGER.debug("ClassLoader: {}", classLoader);
    }

    try {
        if (sContext != null) {
            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSLOGGING_FILE)) {
                System.err.println("Logging configuration not found. No logging enabled !");
            } else {
                DOMConfigurator.configure(Loader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSLOGGING_FILE)));
            }

            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSCONFIG_FILE)) {
                xmlURL = classLoader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSCONFIG_FILE));

            } else {
                ERROR_RECORDER.error("System configuration not found. Shutting down !");

                throw new SecurityServiceException(
                        "System configuration file location not provided by application. Cannot continue.");
            }

            if (DEBUG) {
                DEBUGGER.debug("xmlURL: {}", xmlURL);
            }

            if (xmlURL != null) {
                context = JAXBContext.newInstance(SecurityConfigurationData.class);
                marshaller = context.createUnmarshaller();
                configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

                SecurityServiceListener.svcBean.setConfigData(configData);

                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(SecurityServiceConstants.DS_CONTEXT);

                DAOInitializer.configureAndCreateAuthConnection(
                        new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                        false, SecurityServiceListener.svcBean);

                Map<String, DataSource> dsMap = new HashMap<String, DataSource>();

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    dsMap.put(mgr.getDsName(), (DataSource) envContext.lookup(mgr.getDataSource()));
                }

                SecurityServiceListener.svcBean.setDataSources(dsMap);
            } else {
                throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
            }
        } else {
            throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
        }
    } catch (NamingException nx) {
        ERROR_RECORDER.error(nx.getMessage(), nx);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
    } catch (JAXBException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);
    }
}

From source file:business.controllers.RequestController.java

@Profile("dev")
@PreAuthorize("isAuthenticated() and hasRole('palga') and hasPermission(#id, 'requestAssignedToUser')")
@RequestMapping(value = "/requests/{id}/excerptList/useExample", method = RequestMethod.POST)
public Integer useExampleExcerptList(UserAuthenticationToken user, @PathVariable String id) {
    ClassLoader classLoader = getClass().getClassLoader();
    String filename = "Example excerptlist groot bestand.csv";
    URL resource = classLoader.getResource("test/" + filename);
    try {/*from   ww  w.  java  2  s.  c om*/
        InputStream input = resource.openStream();
        MultipartFile file = new MockMultipartFile(resource.getFile(), input);

        Integer flowTotalChunks = 1;
        Integer flowChunkNumber = 1;
        String flowIdentifier = "flow_" + UUID.randomUUID().toString();

        return this.uploadExcerptList(user, id, filename, flowTotalChunks, flowChunkNumber, flowIdentifier,
                file);
    } catch (IOException e) {
        log.error("Error while uploading example file: " + e.getMessage());
        throw new FileUploadError(e.getMessage());
    }
}

From source file:com.autentia.tnt.manager.report.ReportManager.java

private void parseDocument(Boolean typeFile, String reportName) {

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

    final InputStream jasperreportDtd = loader
            .getResourceAsStream("net/sf/jasperreports/engine/dtds/jasperreport.dtd");
    InputStream xmlSource = null;

    parsingStart = System.currentTimeMillis();
    log.debug("parseDocument - [start] " + reportName);
    try {/*from   w ww  .  j  a  v  a  2  s  .  com*/
        SAXParser sp = new SAXParser();
        log.debug("parseDocument -   newSAXParser=" + (System.currentTimeMillis() - parsingStart) + " ms.");

        File f = null;
        try {
            if (typeFile == true)
                f = new File(loader.getResource(reportName).toURI());
            else
                f = new File(reportName);
        } catch (URISyntaxException e) {
            log.error("Error en ParseDocument", e);
        }
        log.debug("parseDocument -   getResource=" + (System.currentTimeMillis() - parsingStart) + " ms.");

        xmlSource = new FileInputStream(f);

        sp.setContentHandler(this);
        sp.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (publicId.equals("//JasperReports//DTD Report Design//EN")
                        || systemId.equals("http://jasperreports.sourceforge.net/dtds/jasperreport.dtd")) {
                    return new InputSource(jasperreportDtd);
                } else {
                    String msg = "DTD (" + publicId + " " + systemId + ") cannot be resolved by ReportManager: "
                            + "please change TNTConcept to add the new DTD or change your JasperReport's JRXML file "
                            + "to use the standard DTD";
                    log.error("parseDocument - " + msg);
                    throw new IllegalArgumentException(msg);
                }
            }
        });

        sp.parse(new InputSource(xmlSource));
    } catch (FinalizeParsingException fpe) {
        // ignore this exception as it is thrown as an optimization
    } catch (SAXException se) {
        log.error("parseDocument - exception", se);
    } catch (IOException ie) {
        log.error("parseDocument - exception", ie);
    }

    finally {
        if (xmlSource != null) {
            try {
                xmlSource.close();
            } catch (IOException e) {
                // ignored
            }
        }
        try {
            jasperreportDtd.close();
        } catch (IOException e) {
            // ignored
        }
        log.info(
                "parseDocument - " + reportName + " (" + (System.currentTimeMillis() - parsingStart) + " ms.)");
    }
}

From source file:org.openmrs.module.distrotools.api.impl.DistroToolsServiceImpl.java

/**
 * @see DistroToolsService#installPackage(String, ClassLoader, String)
 *//*from  ww w . j a  va2  s. com*/
public boolean installPackage(String filename, ClassLoader loader, String groupUuid) throws APIException {
    Matcher matcher = Pattern.compile("[\\w/-]+-(\\d+).zip").matcher(filename);
    if (!matcher.matches()) {
        throw new APIException("Filename must match PackageNameWithNoSpaces-X.zip");
    }

    Integer version = Integer.valueOf(matcher.group(1));

    ImportedPackage installed = Context.getService(MetadataSharingService.class)
            .getImportedPackageByGroup(groupUuid);
    if (installed != null && installed.getVersion() >= version) {
        log.info("Metadata package " + filename + " is already installed with version "
                + installed.getVersion());
        return false;
    }

    if (loader.getResource(filename) == null) {
        throw new APIException("Cannot load " + filename + " for group " + groupUuid);
    }

    try {
        PackageImporter metadataImporter = MetadataSharing.getInstance().newPackageImporter();
        metadataImporter.setImportConfig(ImportConfig.valueOf(ImportMode.MIRROR));
        metadataImporter.loadSerializedPackageStream(loader.getResourceAsStream(filename));
        metadataImporter.importPackage();

        log.debug("Loaded metadata package '" + filename + "'");
        return true;

    } catch (Exception ex) {
        throw new APIException("Failed to install metadata package " + filename, ex);
    }
}

From source file:io.siddhi.extension.io.file.FileSourceRegexModeTestCase.java

@BeforeClass
public void init() {
    ClassLoader classLoader = FileSourceRegexModeTestCase.class.getClassLoader();
    String rootPath = classLoader.getResource("files").getFile();
    sourceRoot = new File(rootPath + "/repo");
    dirUri = rootPath + "/new";
    newRoot = new File(dirUri);
    moveAfterProcessDir = rootPath + "/moved_files";
}

From source file:com.aurel.track.dbase.InitDatabase.java

private static void insertNullObjectsAndSampleData() {
    ResultSet rs = null;/*from w  w w  . j a  v  a 2  s .  c o m*/
    Connection coni = null;
    Connection cono = null;
    try {
        coni = getConnection();
        cono = getConnection();
        Statement istmt = coni.createStatement();
        Statement ostmt = cono.createStatement();
        LOGGER.info("Testing for NULL objects...");
        // --------------- T S I T E ----------------------
        rs = istmt.executeQuery("SELECT * FROM TSITE");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TSITE " + "(OBJECTID) " + "VALUES (1)");
                LOGGER.info("Inserted TSITE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting TSITE object: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        // --------------- T P R O J E C T T Y P E ----------------------
        rs = istmt.executeQuery("SELECT * FROM TPROJECTTYPE WHERE OBJECTID = 0");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute(
                        "INSERT INTO TPROJECTTYPE " + "(OBJECTID, LABEL, NOTIFYOWNERLEVEL, NOTIFYMANAGERLEVEL) "
                                + "VALUES (0, 'Generic Space', 0, 1)");
                LOGGER.info("Inserted NULL project (PKEY = 0) into TPROJECTTYPE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TPROJECTTYPE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        rs = istmt.executeQuery("SELECT * FROM TPROJECTTYPE WHERE OBJECTID = -1");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TPROJECTTYPE " + "(OBJECTID, LABEL, DEFAULTFORPRIVATE) "
                        + "VALUES (-1, 'Private Project', 'Y')");
                LOGGER.info("Inserted Private project (PKEY = -1) into TPROJECTTYPE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting private space in TPROJECTTYPE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        rs = istmt.executeQuery("SELECT * FROM TPROJECT WHERE PKEY = 0");
        // ------------------- T P R O J E C T  -----------------------
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TPROJECT " + "(PKEY, LABEL, DEFOWNER, DEFMANAGER, PROJECTTYPE) "
                        + "VALUES (0, 'Generic Space', 1, 1, 0)");
                LOGGER.info("Inserted NULL project (PKEY = 0) into TPROJECT");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TPROJECT: " + exc.getMessage());
            }
        }

        // ----------------------- T R O L E ------------------------------
        rs = istmt.executeQuery("SELECT * FROM TROLE WHERE PKEY = -1");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TROLE " + "(PKEY, LABEL, ACCESSKEY, EXTENDEDACCESSKEY, PROJECTTYPE) "
                        + "VALUES (-1, 'PrivateRole', 0, '111111111111', 0)");
                LOGGER.info("Inserted private role (PKEY = -1) into TROLE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TROLE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        LOGGER.info("NULL objects are okay.");

        if (isFirstStartEver) {
            LOGGER.info("Filling some sample data...");
            try {

                URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(populateSql);
                if (populateURL == null) {
                    ClassLoader cl = InitDatabase.class.getClassLoader();
                    populateURL = cl.getResource(populateSql);
                }
                InputStream in = populateURL.openStream();
                java.util.Scanner s = new java.util.Scanner(in, "UTF-8");
                s.useDelimiter(";");
                String st = null;
                StringBuffer stb = new StringBuffer();
                int line = 0;

                ApplicationStarter.getInstance().actualizePercentComplete(
                        ApplicationStarter.getInstance().INIT_DB_DATA_STEP,
                        ApplicationStarter.INIT_DB_DATA_TEXT);

                while (s.hasNext()) {
                    stb.append(s.nextLine().trim());
                    st = stb.toString();
                    ++line;
                    if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*")) {
                        if (st.endsWith(";")) {
                            stb = new StringBuffer(); // clear buffer
                            st = st.substring(0, st.length() - 1); // remove the semicolon
                            try {
                                ostmt.executeUpdate(st);
                            } catch (Exception exc) {
                                LOGGER.error("Problem inserting sample data: " + exc.getMessage());
                                LOGGER.error("Line " + line + ": " + st);
                            }
                        } else {
                            stb.append(" ");
                        }
                    } else {
                        stb = new StringBuffer();
                    }
                }
                s.close();
                in.close();

            } catch (Exception e) {
                LOGGER.error(ExceptionUtils.getStackTrace(e));
            }
            LOGGER.info("Sample data is okay.");

            ApplicationStarter.getInstance().actualizePercentComplete(
                    ApplicationStarter.getInstance().INIT_DB_DATA_STEP, ApplicationStarter.INIT_DB_DATA_TEXT);
        }
    } catch (Exception e) {
        LOGGER.error("Problem inserting null objects: " + e.getMessage());
        LOGGER.debug(STACKTRACE, e);
    } finally {
        if (coni != null) {
            try {
                coni.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
        if (cono != null) {
            try {
                cono.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}