Example usage for java.lang ClassLoader getResourceAsStream

List of usage examples for java.lang ClassLoader getResourceAsStream

Introduction

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

Prototype

public InputStream getResourceAsStream(String name) 

Source Link

Document

Returns an input stream for reading the specified resource.

Usage

From source file:org.apache.kylin.common.BackwardCompatibilityConfig.java

public BackwardCompatibilityConfig() {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    init(loader.getResourceAsStream(KYLIN_BACKWARD_COMPATIBILITY + ".properties"));
    for (int i = 0; i < 10; i++) {
        init(loader.getResourceAsStream(KYLIN_BACKWARD_COMPATIBILITY + (i) + ".properties"));
    }//from  ww  w  .  j  av  a2s  .co m
}

From source file:de.speexx.jira.jan.service.issue.IssueCoreFieldConfigLoader.java

@Produces
@FieldConfig/*from  w w w.ja  v a  2 s.c  o  m*/
IssueCoreFieldConfig loadConfig() {

    final IssueCoreFieldConfig issueConfig = new IssueCoreFieldConfig();
    final ClassLoader cl = getClass().getClassLoader();

    try (final InputStream configStream = cl.getResourceAsStream(getConfigurationResourcePath());
            final InputStreamReader configReader = new InputStreamReader(configStream);
            final CSVParser configParser = RFC4180.withHeader().parse(configReader)) {

        configParser.forEach(record -> {
            final IssueCoreFieldConfig.IssueCoreFieldDescriptionEntry entry = createIssueFieldConfigEntry(
                    record, cl);
            issueConfig.addIssueFieldDescriptionEntry(entry);
        });

    } catch (final IOException e) {
        throw new JiraAnalyzeException(e);
    }

    return issueConfig;
}

From source file:com.envirover.spl.SPLDaemon.java

@Override
public void init(DaemonContext context) throws DaemonInitException, Exception {
    if (!config.init(context.getArguments()))
        throw new DaemonInitException("Invalid configuration.");

    ClassLoader loader = SPLDaemon.class.getClassLoader();
    InputStream params = loader.getResourceAsStream(DEFAULT_PARAMS_FILE);
    if (params != null) {
        MAVLinkShadow.getInstance().loadParams(params);
        params.close();//www .j  av  a 2 s.co m
    } else {
        logger.warn("File 'default.params' with initial parameters values not found.");
    }

    MAVLinkMessageQueue mtMessageQueue = new MAVLinkMessageQueue(config.getQueueSize());
    tcpServer = new MAVLinkTcpServer(config.getMAVLinkPort(), mtMessageQueue);

    MAVLinkMessageQueue moMessageQueue = new MAVLinkMessageQueue(config.getQueueSize());

    MOMessageHandler moHandler = new MOMessageHandler(moMessageQueue);

    httpServer = HttpServer.create(new InetSocketAddress(config.getRockblockPort()), 0);
    httpServer.createContext(config.getHttpContext(),
            new RockBlockHttpHandler(moHandler, config.getRockBlockIMEI()));
    httpServer.setExecutor(null);

    // TODO: Broadcast MO messages to all the connected clients.

    RockBlockClient rockblock = new RockBlockClient(config.getRockBlockIMEI(), config.getRockBlockUsername(),
            config.getRockBlockPassword(), config.getRockBlockURL());

    MTMessagePump mtMsgPump = new MTMessagePump(mtMessageQueue, rockblock);
    mtMsgPumpThread = new Thread(mtMsgPump, "mt-message-pump");

    WSEndpoint.setMTQueue(mtMessageQueue);
    wsServer = new Server("localhost", config.getWSPort(), "/gcs", WSEndpoint.class);
}

From source file:org.apache.oozie.service.TestXLogService.java

public void testLog4jReload() throws Exception {
    File log4jFile = new File(getTestCaseConfDir(), XLogService.DEFAULT_LOG4J_PROPERTIES);
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-oozie-log4j.properties");
    IOUtils.copyStream(is, new FileOutputStream(log4jFile));
    setSystemProperty(XLogService.LOG4J_RELOAD, "1");
    XLogService ls = new XLogService();
    ls.init(null);// w  ww.jav  a2s.  com
    assertTrue(LogFactory.getLog("a").isTraceEnabled());
    sleep(1 * 1000);
    is = cl.getResourceAsStream("test-custom-log4j.properties");
    IOUtils.copyStream(is, new FileOutputStream(log4jFile));
    float originalRatio = XTestCase.WAITFOR_RATIO;
    try {
        XTestCase.WAITFOR_RATIO = 1;

        waitFor(5 * 1000, new Predicate() {
            public boolean evaluate() throws Exception {
                return !LogFactory.getLog("a").isTraceEnabled();
            }
        });
        assertFalse(LogFactory.getLog("a").isTraceEnabled());
    } finally {
        XTestCase.WAITFOR_RATIO = originalRatio;
    }
    ls.destroy();
}

From source file:com.mec.Services.VoteroService.java

private Map<String, List<Establecimiento>> getFromExcel() throws IOException {
    Map<String, List<Establecimiento>> s = new HashMap<>();
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("votero.xlsx");
    Workbook workbook = new XSSFWorkbook(is);
    Sheet datatypeSheet = workbook.getSheetAt(0);
    for (Row row : datatypeSheet) {
        Cell cue = row.getCell(0);/*  w  w  w . j a  v a2  s. c  o m*/
        Cell anexo = row.getCell(1);
        Cell circuito = row.getCell(3);
        Cell desde = row.getCell(4);
        Cell hasta = row.getCell(5);
        Cell total = row.getCell(6);
        if (cue != null && anexo != null && !cue.toString().isEmpty()) {
            cue.setCellType(Cell.CELL_TYPE_STRING);
            anexo.setCellType(Cell.CELL_TYPE_STRING);
            circuito.setCellType(Cell.CELL_TYPE_STRING);
            desde.setCellType(Cell.CELL_TYPE_STRING);
            hasta.setCellType(Cell.CELL_TYPE_STRING);
            total.setCellType(Cell.CELL_TYPE_STRING);

            if (s.containsKey(circuito.toString())) {
                EstablecimientoPost est = establecimientosDAO.getByCueAnexo(Integer.parseInt(cue.toString()),
                        Integer.parseInt(anexo.toString()));
                setGeo(est);
                s.get(circuito.toString()).add(new Establecimiento(est, Integer.parseInt(desde.toString()),
                        Integer.parseInt(hasta.toString()), Integer.parseInt(total.toString())));
            } else {
                List<Establecimiento> aux = new ArrayList<>();
                EstablecimientoPost est = establecimientosDAO.getByCueAnexo(Integer.parseInt(cue.toString()),
                        Integer.parseInt(anexo.toString()));
                setGeo(est);
                aux.add(new Establecimiento(est, Integer.parseInt(desde.toString()),
                        Integer.parseInt(hasta.toString()), Integer.parseInt(total.toString())));
                s.put(circuito.toString(), aux);
            }
        }
    }
    return s;
}

From source file:com.arsdigita.util.parameter.ResourceParameter.java

protected Object unmarshal(String value, final ErrorList errors) {
    File file = new File(value);

    if (!file.exists()) {
        // it is not a standard file so lets try to see if it
        // is a resource
        if (value.startsWith("/")) {
            value = value.substring(1);//from w  w w  .  j a v a 2s  .  c o m
        }

        ClassLoader cload = Thread.currentThread().getContextClassLoader();
        URL url = cload.getResource(value);
        InputStream stream = cload.getResourceAsStream(value);
        if (stream == null && isRequired()) {
            s_log.error(value + " is not a valid file and is required");

            final ParameterError error = new ParameterError(this, "Resource not found");
            errors.add(error);
        }
        return stream;
    } else {
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException ioe) {
            // we know the file exists so this should not
            // be an issue
            s_log.error(value + " is not a valid file and is required", ioe);

            errors.add(new ParameterError(this, ioe));

            return null;
        }
    }
}

From source file:com.axibase.tsd.driver.jdbc.AtsdDriver.java

@Override
protected DriverVersion createDriverVersion() {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try (final InputStream is = classLoader.getResourceAsStream(DRIVER_PROPERTIES)) {
        if (is != null) {
            final Properties properties = new Properties();
            properties.load(is);/*w w  w. j a  v a2  s . c  o  m*/
            return getDriverVersion(properties);
        }
    } catch (final IOException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("[createDriverVersion] " + e.getMessage());
        }
    }
    return getDefaultDriverVersion();
}

From source file:com.redhat.satellite.search.db.DatabaseManager.java

/**
 * Constructor/*from  w  ww . j  a  v  a2s.c o  m*/
 * @param config
 * @throws IOException
 */
public DatabaseManager(Configuration config) throws IOException {
    String configPath = config.getString("search.db_config_path", "classpath");
    Reader reader = null;
    if (configPath.equals("classpath")) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream stream = cl.getResourceAsStream("com/redhat/satellite/search/db/config.xml");
        if (stream == null) {
            throw new IllegalArgumentException(
                    "com/redhat/satellite/search/db/" + "config.xml resource missing");
        }
        reader = new InputStreamReader(stream);
    } else {
        reader = new FileReader(configPath);
    }
    Properties overrides = config.getNamespaceProperties("search");

    String[] options = { "db_name", "db_password", "db_user" };
    for (String option : options) {
        overrides.setProperty(option, config.getString(option));
    }
    isOracle = config.getString("db_backend").equals("oracle");
    if (isOracle) {
        overrides.setProperty("db_name", "@" + overrides.getProperty("db_name"));
    } else {
        String dbHost = config.getString("db_host");
        if (!StringUtils.isEmpty(dbHost)) {
            String connectionUrl = "//" + dbHost;
            String dbPort = config.getString("db_port");
            if (!StringUtils.isEmpty(dbPort)) {
                connectionUrl += ":" + dbPort;
            }
            connectionUrl += "/" + overrides.getProperty("db_name");

            if (config.getBoolean("db_ssl_enabled")) {
                connectionUrl += "?ssl=true";
                String trustStore = config.getString("java.ssl_truststore");
                if (trustStore == null || !new File(trustStore).isFile()) {
                    throw new ConfigException("Can not find java truststore at " + trustStore
                            + ". Path can be changed with java.ssl_truststore option.");
                }
                System.setProperty("javax.net.ssl.trustStore", trustStore);
            }
            overrides.setProperty("db_name", connectionUrl);
        }
    }

    sessionFactory = new SqlSessionFactoryBuilder().build(reader, overrides);
}

From source file:com.sulistionoadi.belajar.service.ExecutorService.java

public void runJob() {
    try {//from   w w w  .j  a  v a2s  .  c o  m
        ClassLoader classLoader = getClass().getClassLoader();
        String contentFile = IOUtils.toString(classLoader.getResourceAsStream("data.csv"), "UTF-8");
        String[] arrContent = contentFile.split("\n");

        ReadWriteLock fileLock = new ReadWriteLock();
        File logFile = new File(pathlog);
        if (!logFile.exists()) {
            logFile.createNewFile();
        }

        JsonLogFile jsonLog = new JsonLogFile();

        fileLock.lockWrite();
        mapper.writerWithDefaultPrettyPrinter().writeValue(logFile, jsonLog);
        fileLock.unlockWrite();

        System.out.println("Running Process Insert into Batch Queue");
        for (String line : arrContent) {
            if (StringUtils.hasText(line)) {
                while (true) {
                    try {
                        boolean inserted = taskExecutor.getThreadPoolExecutor().getQueue()
                                .offer(new WriteLogTask(line, logFile, fileLock), 60, TimeUnit.SECONDS);
                        if (inserted) {
                            break;
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ExecutorService.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }
                taskExecutor.execute(taskExecutor.getThreadPoolExecutor().getQueue().poll());
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ExecutorService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(ExecutorService.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.agilejava.docbkx.maven.AbstractPdfMojo.java

private Configuration loadFOPConfig() throws MojoExecutionException {
    ClassLoader loader = this.getClass().getClassLoader();
    InputStream in = loader.getResourceAsStream("fonts.stg");
    Reader reader = new InputStreamReader(in);
    StringTemplateGroup group = new StringTemplateGroup(reader);
    StringTemplate template = group.getInstanceOf("config");
    template.setAttribute("fonts", fonts);
    DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
    final String config = template.toString();
    if (getLog().isDebugEnabled()) {
        getLog().debug(config);/*from   w  ww .  j  ava 2 s  . co m*/
    }
    try {
        return builder.build(IOUtils.toInputStream(config));
    } catch (IOException ioe) {
        throw new MojoExecutionException("Failed to load FOP config.", ioe);
    } catch (SAXException saxe) {
        throw new MojoExecutionException("Failed to parse FOP config.", saxe);
    } catch (ConfigurationException e) {
        throw new MojoExecutionException("Failed to do something Avalon requires....", e);
    }
}