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:se.berazy.api.client.PoSInvoiceClient.java

/**
 * Loads the .properties file and sets authToken, customerNo
 * and ipAddress.//from   w  w  w  .j  ava2  s .c om
 * 
 * @throws IOException 
 */
void loadProperties() throws IOException {
    if (getCustomerNo() == null || getAuthToken() == null || getIpAddress() == null) {
        if (properties == null) {
            synchronized (readLock) {
                if (properties == null) {
                    log.debug(String.format("Loading properties from %s.", defaultPropertiesFile));
                    ClassLoader loader = PoSInvoiceClient.class.getClassLoader();
                    InputStream in = loader.getResourceAsStream(defaultPropertiesFile);
                    properties = new Properties();
                    properties.load(in);
                    this.setCustomerNo(Integer.parseInt(properties.getProperty("customerNo")));
                    this.setAuthToken(properties.getProperty("authToken"));
                    this.setIpAddress(properties.getProperty("ipAddress"));
                }
            }
        }
    }
}

From source file:org.apache.hadoop.util.TestApplicationClassLoader.java

@Test
public void testGetResource() throws IOException {
    URL testJar = makeTestJar().toURI().toURL();

    ClassLoader currentClassLoader = getClass().getClassLoader();
    ClassLoader appClassloader = new ApplicationClassLoader(new URL[] { testJar }, currentClassLoader, null);

    assertNull("Resource should be null for current classloader",
            currentClassLoader.getResourceAsStream("resource.txt"));

    InputStream in = appClassloader.getResourceAsStream("resource.txt");
    assertNotNull("Resource should not be null for app classloader", in);
    assertEquals("hello", IOUtils.toString(in));
}

From source file:info.estebanluengo.alfrescoAPI.test.AlfrescoAPITest.java

/**
 * Returns a byte[] that contain the data of the file located int src/test/resources directory
 * //from  w w w  . ja v a 2s .  c  om
 * @return a byte[] that contain the file data     
 * @throws IOException if there is not any file in the path
 */
protected byte[] getFile() throws IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream(testProperties.getFilename());
    return org.apache.commons.io.IOUtils.toByteArray(input);
}

From source file:com.edgenius.wiki.service.impl.WidgetServiceImpl.java

/**
 * This method is executed in Spring init-method.
 *///w  w  w  .j a v  a  2  s  .  co m
public void loadWidgetTemplates() {
    ClassLoader classLoader = WidgetTemplate.class.getClassLoader();
    BufferedReader is = null;
    try {
        is = new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream(widgetResource)));
        String widgetClz;
        while ((widgetClz = is.readLine()) != null) {
            //get macro class
            if (StringUtils.isBlank(widgetClz) || widgetClz.trim().startsWith("#")) {
                //skip comment
                continue;
            }
            try {
                Object obj = classLoader.loadClass(widgetClz.trim()).newInstance();
                if (obj instanceof WidgetTemplate) {
                    WidgetTemplate widget = ((WidgetTemplate) obj);
                    widget.init(applicationContext);
                    String type = widget.getType();
                    container.put(type, widget);
                    log.info("Widget class loading success:" + type);
                }
            } catch (Exception e) {
                log.error("Initial widget class " + widgetClz + " failed. This widget is ignored!!!", e);
            }
        }
    } catch (IOException e) {
        log.error("Widget resource file " + widgetResource + " not found.", e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.hybris.datahub.service.impl.DefaultJsonServiceTest.java

/**
 * convertTmallAuthJson//from w  w w  . java2s  . c o m
 */
@Test
public void convertTmallAuthJson() {
    final Class<? extends DefaultJsonServiceTest> instance = getClass();
    if (instance != null) {
        final ClassLoader classLoader = instance.getClassLoader();
        if (classLoader != null) {
            String json = "";
            InputStream resourceAsStream = null;
            try {
                resourceAsStream = classLoader.getResourceAsStream(SAMPLE_TMALL_AUTH_JSON);
                json = IOUtils.toString(resourceAsStream);
            } catch (final IOException e) {
                LOG.error(e.getMessage(), e);
            } finally {
                if (resourceAsStream != null) {
                    try {
                        resourceAsStream.close();
                    } catch (final IOException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            }
            final List<Map<String, String>> csv = service.parse(json);
            final Map<String, String> raw = csv.get(0);

            Assert.assertTrue(raw.containsKey("marketplaceStoreName"));
            Assert.assertTrue(raw.containsKey("integrationId"));
            Assert.assertTrue(raw.containsKey("authorized"));
            Assert.assertEquals("TmallStore", raw.get("marketplaceStoreName"));
            Assert.assertEquals("1234567890", raw.get("integrationId"));
            Assert.assertEquals("true", raw.get("authorized"));
        }
    } else {
        Assert.fail("Class not found.");
    }
}

From source file:com.ar.dev.tierra.api.controller.UsuariosController.java

@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@RequestMapping(value = "/addUsuario", method = RequestMethod.POST)
public ResponseEntity<?> addNewUsuario(@RequestBody Usuarios usuarios) throws IOException {
    String ptoEnc = usuarios.getPassword();
    String bCrypt = passwordEncoder.encode(ptoEnc);
    usuarios.setPassword(bCrypt);/*from w w  w  . j  ava2  s.  co m*/
    usuarios.setEstado(false);
    usuarios.setFechaCreacion(new Date());
    Usuarios replyUsername;
    Usuarios replyDNI;
    replyUsername = facadeService.getUsuariosDAO().findUsuarioByUsername(usuarios.getUsername());
    replyDNI = facadeService.getUsuariosDAO().findUsuarioByDNI(usuarios.getDni());
    ResponseEntity responseEntity;
    if (replyDNI == null && replyUsername == null) {
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream is = classloader.getResourceAsStream("dd.png");
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] bytes = new byte[16384];
        while ((nRead = is.read(bytes, 0, bytes.length)) != -1) {
            buffer.write(bytes, 0, nRead);
        }
        buffer.flush();
        usuarios.setImagen(buffer.toByteArray());
        facadeService.getUsuariosDAO().addUsuario(usuarios);
        responseEntity = new ResponseEntity(HttpStatus.OK);
    } else {
        JsonResponse msj;
        if (replyDNI != null && replyUsername == null) {
            msj = new JsonResponse("Error", "D.N.I. ya existe.");
        } else if (replyUsername != null && replyDNI == null) {
            msj = new JsonResponse("Error", "Nombre de usuario ya existe.");
        } else {
            msj = new JsonResponse("Error", "Nombre de usuario y D.N.I. ya existen.");
        }
        responseEntity = new ResponseEntity(msj, HttpStatus.BAD_REQUEST);
    }
    return responseEntity;
}

From source file:org.alfresco.repo.node.ConcurrentNodeServiceTest.java

protected void setUp() throws Exception {
    DictionaryDAO dictionaryDao = (DictionaryDAO) ctx.getBean("dictionaryDAO");
    // load the system model
    ClassLoader cl = BaseNodeServiceTest.class.getClassLoader();
    InputStream modelStream = cl.getResourceAsStream("alfresco/model/systemModel.xml");
    assertNotNull(modelStream);// w  w  w .  ja v  a 2  s.  c  o m
    M2Model model = M2Model.createModel(modelStream);
    dictionaryDao.putModel(model);
    // load the test model
    modelStream = cl.getResourceAsStream("org/alfresco/repo/node/BaseNodeServiceTest_model.xml");
    assertNotNull(modelStream);
    model = M2Model.createModel(modelStream);
    dictionaryDao.putModel(model);

    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    nodeService = serviceRegistry.getNodeService();
    nodeDAO = (NodeDAO) ctx.getBean("nodeDAO");
    transactionService = serviceRegistry.getTransactionService();
    authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");

    this.authenticationComponent.setSystemUserAsCurrentUser();

    // create a first store directly
    RetryingTransactionCallback<Object> createRootNodeCallback = new RetryingTransactionCallback<Object>() {
        public Object execute() throws Exception {
            StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE,
                    "Test_" + System.currentTimeMillis());
            rootNodeRef = nodeService.getRootNode(storeRef);
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(createRootNodeCallback);
}

From source file:com.hybris.datahub.service.impl.DefaultJsonServiceTest.java

/**
 * convertTmallTradesJson// www  . j  a  v  a2 s.c  o m
 *
 * @throws Exception
 */
@Test
public void convertTmallTradesJson() throws Exception {
    final Class<? extends DefaultJsonServiceTest> instance = getClass();
    if (instance != null) {
        final ClassLoader classLoader = instance.getClassLoader();
        if (classLoader != null) {

            String json = "";
            InputStream resourceAsStream = null;
            try {
                resourceAsStream = classLoader.getResourceAsStream(SAMPLE_TMALL_TRADES_JSON);
                json = IOUtils.toString(resourceAsStream);
            } catch (final IOException e) {
                LOG.error(e.getMessage(), e);
            } finally {
                if (resourceAsStream != null) {
                    try {
                        resourceAsStream.close();
                    } catch (final IOException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            }
            final List<Map<String, String>> csv = service.parse(json);
            final Map<String, String> raw = csv.get(0);

            Assert.assertTrue(raw.containsKey("marketplaceStoreName"));
            Assert.assertTrue(raw.containsKey("currency"));
            Assert.assertTrue(raw.containsKey("productCatalogVersion"));
            Assert.assertTrue(raw.containsKey("trades"));

            Assert.assertEquals("CNY", raw.get("currency"));
            Assert.assertEquals("electronics-cnProductCatalog:Online", raw.get("productCatalogVersion"));

            final Map<String, String> rawTrade = service.parse(raw.get("trades")).get(0);

            Assert.assertEquals("2100703549093", rawTrade.get("numIid"));
            Assert.assertEquals("TRADE_CLOSED_BY_TAOBAO", rawTrade.get("status"));
        }
    } else {
        Assert.fail("Class not found.");
    }
}

From source file:SecuritySupport.java

InputStream getResourceAsStream(ClassLoader cl, String name) {
    InputStream ris;/*from   w ww  .  j  ava 2s  .  c  o  m*/
    if (cl == null) {
        ris = ClassLoader.getSystemResourceAsStream(name);
    } else {
        ris = cl.getResourceAsStream(name);
    }
    return ris;
}

From source file:jp.aegif.nemaki.util.impl.PropertyManagerImpl.java

private String override(String key, String value) {
    String result = value;/*w w w  . j  av  a 2 s. c  o  m*/
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    for (String file : overrideFiles) {
        //Load file
        InputStream is = cl.getResourceAsStream(file);
        if (is == null) {
            continue;
        }
        Properties properties = new Properties();
        try {
            properties.load(is);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String _value = properties.getProperty(key);
        if (_value != null) {
            result = _value;
        }
    }
    return result;
}