Example usage for org.springframework.core.io Resource getInputStream

List of usage examples for org.springframework.core.io Resource getInputStream

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream for the content of an underlying resource.

Usage

From source file:com.sinnerschrader.s2b.accounttool.logic.component.licences.LicenseSummary.java

private List<Dependency> loadFromXML(Resource licenseFile) throws Exception {
    List<Dependency> deps = new LinkedList<>();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(licenseFile.getInputStream());

    NodeList dependencyNodes = doc.getElementsByTagName("dependency");
    for (int di = 0; di < dependencyNodes.getLength(); di++) {
        Node nNode = dependencyNodes.item(di);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element dependency = (Element) nNode;
            String groupId = getElementsByTagName(dependency, "groupId");
            String artifactId = getElementsByTagName(dependency, "artifactId");
            String version = getElementsByTagName(dependency, "version");
            List<License> licenses = new ArrayList<>();

            log.trace("Found dependency {}:{}:{} ", groupId, artifactId, version);

            NodeList licenseNodes = dependency.getElementsByTagName("license");
            for (int li = 0; li < licenseNodes.getLength(); li++) {
                Node lNode = licenseNodes.item(li);
                if (lNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element license = (Element) lNode;
                    String name = getElementsByTagName(license, "name");
                    String distribution = getElementsByTagName(license, "distribution");
                    String url = getElementsByTagName(license, "url");
                    String comments = getElementsByTagName(license, "comments");

                    log.trace("Found license {} for dependency {}:{}:{} ", name, groupId, artifactId, version);
                    licenses.add(new License(name, url, distribution, comments));
                }//from   w  w w. j  a  v a  2s  .com
            }
            deps.add(new Dependency(groupId, artifactId, version, licenses));
        }
    }
    Collections.sort(deps);
    return deps;
}

From source file:com.diaimm.april.db.jpa.hibernate.multidbsupport.PersistenceUnitReader.java

/**
 * Parse and build all persistence unit infos defined in the given XML files.
 * @param persistenceXmlLocations the resource locations (can be patterns)
 * @return the resulting PersistenceUnitInfo instances
 *//*from   ww  w .  j  a  v a  2 s  .c o  m*/
public SpringPersistenceUnitInfo[] readPersistenceUnitInfos(String[] persistenceXmlLocations) {
    ErrorHandler handler = new SimpleSaxErrorHandler(logger);
    List<SpringPersistenceUnitInfo> infos = new LinkedList<SpringPersistenceUnitInfo>();
    String resourceLocation = null;
    try {
        for (String location : persistenceXmlLocations) {
            Resource[] resources = this.resourcePatternResolver.getResources(location);
            for (Resource resource : resources) {
                resourceLocation = resource.toString();
                InputStream stream = resource.getInputStream();
                try {
                    Document document = buildDocument(handler, stream);
                    parseDocument(resource, document, infos);
                } finally {
                    stream.close();
                }
            }
        }
    } catch (IOException ex) {
        throw new IllegalArgumentException("Cannot parse persistence unit from " + resourceLocation, ex);
    } catch (SAXException ex) {
        throw new IllegalArgumentException("Invalid XML in persistence unit from " + resourceLocation, ex);
    } catch (ParserConfigurationException ex) {
        throw new IllegalArgumentException("Internal error parsing persistence unit from " + resourceLocation);
    }

    return infos.toArray(new SpringPersistenceUnitInfo[infos.size()]);
}

From source file:com.fns.grivet.api.GrivetApiClientIT.java

@Test
public void testRegisterAndLinkAndStoreAndGetTypeHappyPath() {
    registerTestType();/*w  w w.j av a2  s .c o m*/
    Resource r = resolver.getResource("classpath:TestTypeSchema.json");
    try {
        String schema = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        given().contentType("application/json").request().body(schema).then().expect().statusCode(equalTo(200))
                .when().post("/api/v1/schema");
        r = resolver.getResource("classpath:TestTypeData.json");
        String type = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        given().contentType("application/json").request().header("Type", "TestType").body(type).then().expect()
                .statusCode(equalTo(201)).when().post("/api/v1/type");

        // GET (default)
        Response response = given().contentType("application/json").request().then().expect()
                .statusCode(equalTo(200)).when().get("/api/v1/type/TestType");
        JSONArray result = new JSONArray(response.body().asString());
        JsonAssert.assertJsonEquals(type, result.get(0).toString());

        // GET (with equals constraint that is a boolean)
        response = given().param("c", "boolean|equals|false").contentType("application/json").request().then()
                .expect().statusCode(equalTo(200)).when().get("/api/v1/type/TestType");
        result = new JSONArray(response.body().asString());
        JsonAssert.assertJsonEquals(type, result.get(0).toString());

        // GET (with equals constraint that is a varchar)
        response = given().param("c", "varchar|equals|Rush").contentType("application/json").request().then()
                .expect().statusCode(equalTo(200)).when().get("/api/v1/type/TestType");
        result = new JSONArray(response.body().asString());
        JsonAssert.assertJsonEquals(type, result.get(0).toString());

        // GET (with startsWith constraint)
        response = given().param("c", "text|startsWith|Grim-faced").contentType("application/json").request()
                .then().expect().statusCode(equalTo(200)).when().get("/api/v1/type/TestType");
        result = new JSONArray(response.body().asString());
        JsonAssert.assertJsonEquals(type, result.get(0).toString());

        // GET (with lessThanOrEqualTo constraint)
        response = given().param("c", "datetime|lessThanOrEqualTo|2016-01-01T00:00:00Z")
                .contentType("application/json").request().then().expect().statusCode(equalTo(200)).when()
                .get("/api/v1/type/TestType");
        result = new JSONArray(response.body().asString());
        JsonAssert.assertJsonEquals(type, result.get(0).toString());

        // GET (with multiple constraints)
        response = given().param("c", "datetime|lessThanOrEqualTo|2016-01-01T00:00:00Z")
                .param("c", "text|endsWith|city").contentType("application/json").request().then().expect()
                .statusCode(equalTo(200)).when().get("/api/v1/type/TestType");
        result = new JSONArray(response.body().asString());
        JsonAssert.assertJsonEquals(type, result.get(0).toString());
    } catch (IOException e) {
        fail(e.getMessage());
    }

    deregisterType();
}

From source file:com.gfactor.jpa.core.MyPersistenceUnitReader.java

/**
 * Parse and build all persistence unit infos defined in the given XML files.
 * @param persistenceXmlLocations the resource locations (can be patterns)
 * @return the resulting PersistenceUnitInfo instances
 *//*from w w w  . j a v a  2 s.  c o m*/
public MySpringPersistenceUnitInfo[] readPersistenceUnitInfos(String[] persistenceXmlLocations) {
    ErrorHandler handler = new SimpleSaxErrorHandler(logger);
    List<MySpringPersistenceUnitInfo> infos = new LinkedList<MySpringPersistenceUnitInfo>();
    String resourceLocation = null;
    try {
        for (String location : persistenceXmlLocations) {
            Resource[] resources = this.resourcePatternResolver.getResources(location);
            for (Resource resource : resources) {
                resourceLocation = resource.toString();
                InputStream stream = resource.getInputStream();
                try {
                    Document document = buildDocument(handler, stream);
                    parseDocument(resource, document, infos);
                } finally {
                    stream.close();
                }
            }
        }
    } catch (IOException ex) {
        throw new IllegalArgumentException("Cannot parse persistence unit from " + resourceLocation, ex);
    } catch (SAXException ex) {
        throw new IllegalArgumentException("Invalid XML in persistence unit from " + resourceLocation, ex);
    } catch (ParserConfigurationException ex) {
        throw new IllegalArgumentException("Internal error parsing persistence unit from " + resourceLocation);
    }

    return infos.toArray(new MySpringPersistenceUnitInfo[infos.size()]);
}

From source file:dk.teachus.backend.test.CreateMysqlTestDatabase.java

public CreateMysqlTestDatabase(Resource property) {
    System.out.print("Ensuring database exists... ");
    // Create connection
    Connection connection = null;
    try {/* ww w.  j a va  2  s  .c  om*/

        Properties properties = new Properties();
        properties.load(property.getInputStream());

        String driverClass = properties.getProperty("db.driverClassName");
        String jdbcUrl = properties.getProperty("db.url");
        jdbcUrl += "?allowMultiQueries=true";
        String jdbcUser = properties.getProperty("db.username");
        String jdbcPass = properties.getProperty("db.password");
        String jdbcHost = properties.getProperty("db.host");
        String jdbcDatabase = properties.getProperty("db.database");

        Class.forName(driverClass);

        // Create database if not exists
        connection = DriverManager.getConnection("jdbc:mysql://" + jdbcHost + "/" + jdbcDatabase, jdbcUser,
                jdbcPass);
        Statement statement = connection.createStatement();
        statement.executeUpdate("DROP DATABASE " + jdbcDatabase);
        statement.close();
        statement = connection.createStatement();
        statement.executeUpdate("CREATE DATABASE " + jdbcDatabase);
        statement.close();
        connection.close();

        // Connect to database
        connection = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPass);

        // Drop existing tables
        dropTable(connection, "booking");
        dropTable(connection, "message_recipient");
        dropTable(connection, "message");
        dropTable(connection, "application_configuration");
        dropTable(connection, "period");
        dropTable(connection, "teacher_attribute");

        // To drop the person table we first need to remove all person references
        try {
            executeUpdateSql(connection, "UPDATE person SET teacher_id = NULL");
        } catch (SQLException e) {
            // The person table might not exist, so it's ok
        }
        dropTable(connection, "person");
    } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        System.out.println("Done");
    }
}

From source file:org.mitre.openid.connect.config.JsonMessageSource.java

/**
 * @param locale//w ww .j a  va  2 s .  com
 * @return
 */
private List<JsonObject> getLanguageMap(Locale locale) {

    if (!languageMaps.containsKey(locale)) {
        try {
            List<JsonObject> set = new ArrayList<>();
            for (String namespace : config.getLanguageNamespaces()) {
                String filename = locale.getLanguage() + File.separator + namespace + ".json";

                Resource r = getBaseDirectory().createRelative(filename);

                logger.info("No locale loaded, trying to load from " + r);

                JsonParser parser = new JsonParser();
                JsonObject obj = (JsonObject) parser.parse(new InputStreamReader(r.getInputStream(), "UTF-8"));

                set.add(obj);
            }
            languageMaps.put(locale, set);
        } catch (JsonIOException | JsonSyntaxException | IOException e) {
            logger.error("Unable to load locale", e);
        }
    }

    return languageMaps.get(locale);

}

From source file:org.jasig.portlet.weather.dao.worldwide.WorldWeatherOnlineDaoImpl.java

public void setImageMapping(Resource imageMapping) {
    this.imageMapping = new Properties();
    InputStream is = null;/*ww  w  .  jav  a2  s .  com*/
    try {
        is = imageMapping.getInputStream();
        this.imageMapping.load(is);
    } catch (IOException e) {
        throw new RuntimeException("Failed to load image mapping", e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.wavemaker.tools.util.CFClassLoader.java

@Override
public InputStream getResourceAsStream(String name) {
    List<Resource> files = new ArrayList<Resource>();
    for (int i = 0; i < this.resources.length; i++) {
        files.addAll(this.fileSystem.listAllChildren(this.resources[i], null));
    }/*from w  w w.j ava  2 s.c om*/

    InputStream ret;

    try {
        for (Resource entry : files) {
            String resourcePath = getPath(entry);
            int len1 = resourcePath.length();
            int len2 = name.length();
            if (len1 > len2) {
                if (resourcePath.substring(len1 - len2, len1).equals(name)) {
                    return entry.getInputStream();
                }
            }
        }
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }

    ret = this.parentClassLoader.getResourceAsStream(name);

    return ret;
}

From source file:com.haulmont.cuba.web.testsupport.TestContainer.java

protected void initAppProperties() {
    final Properties properties = new Properties();

    List<String> locations = getAppPropertiesFiles();
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    for (String location : locations) {
        Resource resource = resourceLoader.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                properties.load(stream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(stream);
            }/*  w w w . ja  v a2s. co m*/
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }

    StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() {
        @Override
        public String lookup(String key) {
            String subst = properties.getProperty(key);
            return subst != null ? subst : System.getProperty(key);
        }
    });
    for (Object key : properties.keySet()) {
        String value = substitutor.replace(properties.getProperty((String) key));
        appProperties.put((String) key, value);
    }

    File dir;
    dir = new File(appProperties.get("cuba.confDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.logDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.tempDir"));
    dir.mkdirs();
    dir = new File(appProperties.get("cuba.dataDir"));
    dir.mkdirs();

    AppContext.setProperty(AppConfig.CLIENT_TYPE_PROP, ClientType.WEB.toString());
}

From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java

private void load(final Resource source, final StringBuilder target) throws IOException {

    final char[] buffer = new char[4096];
    int bytesRead = 0;
    try (Reader reader = new InputStreamReader(source.getInputStream(), UTF_8)) {
        while ((bytesRead = reader.read(buffer)) > 0) {
            target.append(buffer, 0, bytesRead);
        }//from www . jav a 2  s  . c  o m
    }
}