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:com.garyclayburg.attributes.AttributeService.java

public void setScriptRunner(ScriptRunner runner) {
    log.info("setting scriptrunner...");
    this.runner = runner;
    if (runner.getRoots() != null) {
        initiallyScanned = false;/*from w  w w. ja va  2  s.  c om*/
        Runnable runnable = new Runnable() {
            public void run() {
                /*
                loading scripts in a background thread improves startup performance, especially when scripts
                are located on a slow file system such as S3
                 */
                synchronized (groovyClassMap) {
                    initiallyScanned = true;
                    scanGroovyClasses();
                }
            }
        };
        Thread t = new Thread(runnable);
        t.setName("pre-load" + String.valueOf(Math.random()).substring(2, 6));
        log.info("starting pre-load thread: " + t.getName());
        t.start();
    } else { // use read-only embedded scripts
        log.warn(
                "Custom groovy policy scripts not found.  Defaulting to read-only embedded groovy policy scripts");
        initiallyScanned = true;
        ClassLoader parent = getClass().getClassLoader();
        String scriptName = "embeddedgroovy/com/embedded/DefaultAttributes.groovy";
        InputStream groovyIS = parent.getResourceAsStream(scriptName);
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new BufferedReader(
                new InputStreamReader(groovyIS, Charset.forName(StandardCharsets.UTF_8.name())))) {
            int c;
            while ((c = reader.read()) != -1) {
                sb.append((char) c);
            }
            //                log.debug("complete default embedded groovy class:\n{}",sb.toString());
            GroovyClassLoader loader = new GroovyClassLoader(parent);
            Class parsedDefaultClass = loader.parseClass(sb.toString(), scriptName);
            groovyClassMap.clear();
            groovyClassMap.put(scriptName, parsedDefaultClass);
        } catch (IOException e) {
            log.warn("could not load embedded groovy scripts", e);
        }
        log.debug("finished reading embedded groovy");
    }
}

From source file:org.openlmis.fulfillment.web.ProofOfDeliveryController.java

/**
 * Prints proofOfDelivery in PDF format.
 *
 * @param id UUID of ProofOfDelivery to print
 *///w ww  . j  av  a2 s .  c o m
@RequestMapping(value = "/proofsOfDelivery/{id}/print", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ModelAndView printProofOfDelivery(HttpServletRequest request, @PathVariable("id") UUID id,
        OAuth2Authentication authentication) throws IOException {

    XLOGGER.entry(id, authentication);
    Profiler profiler = new Profiler("GET_POD");
    profiler.setLogger(XLOGGER);

    ProofOfDelivery proofOfDelivery = findProofOfDelivery(id, profiler);
    canViewPod(authentication, profiler, proofOfDelivery);

    profiler.start("LOAD_JASPER_TEMPLATE");
    String filePath = "jasperTemplates/proofOfDelivery.jrxml";
    ClassLoader classLoader = getClass().getClassLoader();

    Template template = new Template();
    template.setName("ordersJasperTemplate");

    try (InputStream fis = classLoader.getResourceAsStream(filePath)) {
        templateService.createTemplateParameters(template, fis);
    }
    profiler.start("GENERATE_JASPER_VIEW");
    JasperReportsMultiFormatView jasperView = jasperReportsViewService.getJasperReportsView(template, request);

    Map<String, Object> params = new HashMap<>();
    params.put("format", "pdf");
    params.put("id", proofOfDelivery.getId());

    ModelAndView modelAndView = new ModelAndView(jasperView, params);

    profiler.stop().log();
    XLOGGER.exit(modelAndView);

    return modelAndView;
}

From source file:com.mgmtp.perfload.core.client.config.LtProcessModule.java

/**
 * Provides the version of perfLoad as specified in the Maven pom.
 * //from   www  . j  a  va2s  .c o m
 * @return the version string
 */
@Provides
@Singleton
@PerfLoadVersion
protected String providePerfLoadVersion() {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream is = loader.getResourceAsStream("com/mgmtp/perfload/core/common/version.txt");
    try {
        return IOUtils.toString(is, "UTF-8");
    } catch (IOException ex) {
        throw new IllegalStateException("Could not read perfLoad version.", ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.apache.nifi.processors.elasticsearch.TestPutElasticsearchHttp.java

@Before
public void once() throws IOException {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    docExample = IOUtils.toString(classloader.getResourceAsStream("DocumentExample.json")).getBytes();
}

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

public void testTuncateLog() throws Exception {
    File log4jFile = new File(getTestCaseConfDir(), "test-log4j.properties");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-no-dash-log4j.properties");
    Properties log4jProps = new Properties();
    log4jProps.load(is);/*from  w w  w  . ja  v a 2s .  co m*/
    log4jProps.setProperty("log4j.appender.oozie.File", getTestCaseDir() + "/oozie.log");
    log4jProps.store(new FileOutputStream(log4jFile), "");
    setSystemProperty(XLogService.LOG4J_FILE, log4jFile.getName());

    new Services().init();
    ConfigurationService.set(XLogFilter.MAX_SCAN_DURATION, "10");
    Date startDate = new Date();
    Date endDate = new Date(startDate.getTime() + FIFTEEN_HOURS);
    String log = doStreamLog(new XLogFilter(), startDate, endDate);
    assertTrue(log.contains("Truncated logs to max log scan duration"));
    log = doStreamErrorLog(new XLogFilter(), startDate, endDate);
    assertFalse(log.contains("Truncated logs to max log scan duration"));
    log = doStreamAuditLog(new XLogFilter(), startDate, endDate);
    assertFalse(log.contains("Truncated logs to max log scan duration"));
}

From source file:SecuritySupport.java

InputStream getResourceAsStream(final ClassLoader cl, final String name) {
    return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            InputStream ris;//  w w  w . j  a  v a2 s  .  c  o  m
            if (cl == null) {
                ris = ClassLoader.getSystemResourceAsStream(name);
            } else {
                ris = cl.getResourceAsStream(name);
            }
            return ris;
        }
    });
}

From source file:Data.java

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor./* w w  w . ja  v a  2s .  com*/
 * @throws ClassNotFoundException 
 * @throws IOException 
 * @throws SQLException 
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() throws ClassNotFoundException, IOException, SQLException {
    Connection dataFridge = getDbConnection();
    Statement stmt = dataFridge.createStatement();

    GridBagConstraints gridBagConstraints;

    panelPrincipal = new JPanel();
    panelCenter = new JPanel();
    panelHeader = new JPanel();
    btnHome = new JButton();
    dataList = new JComboBox();
    btnOk = new JButton();
    panelData = new JScrollPane();
    panelRealTime = new JPanel();
    tempRealTime = new JLabel();
    humRealTime = new JLabel();

    // Set unit temperature
    switch (param.tempUnitList.getSelectedIndex()) {
    case 0:
        tempUnit = "C";
        break;

    case 1:
        tempUnit = "F";
        break;

    default:
        break;
    }

    setPreferredSize(new Dimension(512, 400));
    setLayout(null);

    panelPrincipal.setPreferredSize(new Dimension(512, 400));
    panelPrincipal.setLayout(new BorderLayout());

    panelHeader.setPreferredSize(new Dimension(512, 40));
    panelHeader.setLayout(new GridBagLayout());

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("home.png");
    Image iconeHome = ImageIO.read(input);

    btnHome.setIcon(new ImageIcon(iconeHome));
    btnHome.setPreferredSize(new Dimension(40, 40));
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.anchor = GridBagConstraints.LINE_START;
    gridBagConstraints.insets = new Insets(0, 0, 0, 50);
    panelHeader.add(btnHome, gridBagConstraints);

    dataList.setModel(
            new DefaultComboBoxModel(new String[] { "Donnes en temps rel", "Graphique des temperatures" }));
    dataList.setPreferredSize(new Dimension(250, 40));
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.anchor = GridBagConstraints.LINE_END;
    gridBagConstraints.insets = new Insets(0, 0, 0, 10);
    panelHeader.add(dataList, gridBagConstraints);

    btnOk.setFont(new Font("Tahoma", 0, 10)); // NOI18N
    btnOk.setText("OK");
    btnOk.setPreferredSize(new Dimension(60, 40));
    btnOk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            btnOKActionPerformed(evt);
        }
    });
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.anchor = GridBagConstraints.LINE_START;
    gridBagConstraints.insets = new Insets(0, 5, 0, 70);
    panelHeader.add(btnOk, gridBagConstraints);

    panelPrincipal.add(panelHeader, BorderLayout.NORTH);
    panelCenter.setLayout(new BorderLayout());

    JFreeChart chart = createChart(createDataset(stmt));
    panelChart = new ChartPanel(chart);
    panelChart.setVisible(true);

    panelData = new JScrollPane(getTbleData(stmt));

    tempRealTime.setFont(new java.awt.Font("Meiryo UI", 1, 18)); // NOI18N
    humRealTime.setFont(new java.awt.Font("Meiryo UI", 1, 18)); // NOI18N

    panelRealTime.setLayout(new GridBagLayout());
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.insets = new Insets(18, 0, 0, 0);
    gridBagConstraints.anchor = GridBagConstraints.LINE_START;
    panelRealTime.add(tempRealTime, gridBagConstraints);

    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.insets = new Insets(0, 0, 10, 0);
    gridBagConstraints.anchor = GridBagConstraints.LINE_START;
    panelRealTime.add(humRealTime, gridBagConstraints);

    panelCenter.add(panelRealTime, BorderLayout.NORTH);
    panelCenter.add(panelData, BorderLayout.CENTER);

    panelPrincipal.add(panelCenter, BorderLayout.CENTER);

    add(panelPrincipal);
    panelPrincipal.setBounds(0, 0, 512, 340);

    stmt.close();
    dataFridge.close();
}

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

public void testNoDashInConversionPattern() throws Exception {
    setupXLog();// w w w  . j  a va  2 s  .c  o  m
    XLogFilter xf = new XLogFilter(new XLogUserFilterParam(null));
    xf.setParameter("USER", "oozie");
    xf.setLogLevel("DEBUG|INFO");
    // Previously, a dash ("-") was always required somewhere in a line in order for that line to pass the filter; this test
    // checks that this condition is no longer required for log streaming to work
    File log4jFile = new File(getTestCaseConfDir(), "test-log4j.properties");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-no-dash-log4j.properties");
    Properties log4jProps = new Properties();
    log4jProps.load(is);
    // prevent conflicts with other tests by changing the log file location
    log4jProps.setProperty("log4j.appender.oozie.File", getTestCaseDir() + "/oozie.log");
    log4jProps.store(new FileOutputStream(log4jFile), "");
    setSystemProperty(XLogService.LOG4J_FILE, log4jFile.getName());
    try {
        new Services().init();
        assertFalse(doStreamDisabledCheck());
        LogFactory.getLog("a")
                .info("2009-06-24 02:43:14,505 INFO _L1_:317 - SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] "
                        + "APP[-] JOB[-] ACTION[-] Released Lock");
        LogFactory.getLog("a")
                .info("2009-06-24 02:43:14,505 INFO _L2_:317 - SERVER[foo] USER[blah] GROUP[oozie] TOKEN[-]"
                        + "APP[-] JOB[-] ACTION[-] Released Lock");
        LogFactory.getLog("a").info(
                "2009-06-24 02:43:14,505 INFO _L3_:317 SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] APP[-]"
                        + " JOB[-] ACTION[-] Released Lock");
        LogFactory.getLog("a").info(
                "2009-06-24 02:43:14,505 INFO _L4_:317 SERVER[foo] USER[blah] GROUP[oozie] TOKEN[-] APP[-] "
                        + "JOB[-] ACTION[-] Released Lock");
        String out = doStreamLog(xf);
        String outArr[] = out.split("\n");
        // Lines 2 and 4 are filtered out because they have the wrong user
        assertEquals(2, outArr.length);
        assertTrue(outArr[0].contains("_L1_"));
        assertFalse(out.contains("_L2_"));
        assertTrue(outArr[1].contains("_L3_"));
        assertFalse(out.contains("_L4_"));
    } finally {
        Services.get().destroy();
    }
}

From source file:org.collectionspace.services.client.AbstractServiceClientImpl.java

/**
 * readProperties reads properties from system class path as well as it
 * overrides properties made available using command line
 *
 * @exception RuntimeException// w  ww.  j  ava2 s.co m
 */
private void readProperties() {

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = null;
    try {
        is = cl.getResourceAsStream("collectionspace-client.properties");
        properties.load(is);
        if (logger.isDebugEnabled()) {
            printProperties();
        }
        String spec = System.getProperty(URL_PROPERTY);
        if (spec != null && !"".equals(spec)) {
            properties.setProperty(URL_PROPERTY, spec);
        }

        spec = properties.getProperty(URL_PROPERTY);
        url = new URL(spec);
        logger.debug("readProperties() using url=" + url);

        String auth = System.getProperty(AUTH_PROPERTY);
        if (auth != null && !"".equals(auth)) {
            properties.setProperty(AUTH_PROPERTY, auth);
        }
        String ssl = System.getProperty(SSL_PROPERTY);
        if (ssl != null && !"".equals(ssl)) {
            properties.setProperty(AUTH_PROPERTY, ssl);
        }
        String user = System.getProperty(USER_PROPERTY);
        if (user != null && !"".equals(user)) {
            properties.setProperty(USER_PROPERTY, user);
        }
        String password = System.getProperty(PASSWORD_PROPERTY);
        if (password != null && !"".equals(password)) {
            properties.setProperty(PASSWORD_PROPERTY, password);
        }
        String tenant = System.getProperty(TENANT_PROPERTY);
        if (tenant != null && !"".equals(tenant)) {
            properties.setProperty(TENANT_PROPERTY, tenant);
        }
        if (logger.isDebugEnabled()) {
            printProperties();
        }
    } catch (Exception e) {
        logger.debug("Caught exception while reading properties", e);
        throw new RuntimeException(e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                if (logger.isDebugEnabled() == true) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.cisco.dvbu.ps.common.util.PropertyManager.java

/**
 * an internal method to load the properties of a given resource on the classpath
 * //  w  w  w . j  a va2s .  c o m
 * @param properties - object to load the properties in (must not be null)
 * @param resourceName - the name of the properties file that contains the property
 * @return true if the pass properties object was updated, otherwise false
 */
private boolean loadPropertiesFromClassPath(Properties properties, String resourceName) {
    boolean status = false;
    if (resourceName == null || resourceName.length() == 0 || properties == null) {
        return false;
    }
    InputStream inpStream = null;
    try {
        ClassLoader cl = getClass().getClassLoader();
        inpStream = cl.getResourceAsStream(resourceName);
        if (inpStream != null) {
            properties.load(inpStream);
            status = true;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (inpStream != null) {
            try {
                inpStream.close();
            } catch (IOException e) {
                // TODO log exception
            }
        }
    }
    return status;
}