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:edu.duke.cabig.c3pr.rules.deploy.SystemRulesDeployer.java

public SystemRulesDeployer(RuleDeploymentService ruleDeploymentService) {
    if (log.isInfoEnabled())
        log.info("Begining system rule loading......");
    try {/*from   w w w  .  java2 s.c  om*/

        // 1. create the base pattern.
        String pattern = "classpath*:" + SystemRulesDeployer.class.getPackage().getName().replace(".", "/")
                + "/*.xml";

        // 2. Load the rule files, that are to be loaded in repository
        // and load them only if they are not already loaded.
        for (Resource resource : getResources(pattern)) {
            if (log.isDebugEnabled())
                log.debug("Loading rule file :" + resource.getURL().toString());
            try {
                String ruleXml = getFileContext(resource.getInputStream());
                org.drools.rule.Package rulePackage = XMLUtil.unmarshalToPackage(ruleXml);
                String ruleBindUri = rulePackage.getName();
                // unregister the rules
                try {
                    ruleDeploymentService.deregisterRuleSet(ruleBindUri);
                } catch (Exception ignore) {
                }
                // register the rules
                if (log.isDebugEnabled())
                    log.debug("Registering at bindUri : " + ruleBindUri + "\r\n\r\n" + ruleXml);
                ruleDeploymentService.registerRulePackage(ruleBindUri, rulePackage);
                if (log.isDebugEnabled())
                    log.debug("Sucessfully deployed rule at bindUri :" + ruleBindUri);
            } catch (RuntimeException e) {
                log.debug("It seems the system rule is already available, so ignoring", e);
            }

        }

    } catch (Exception e) {
        log.warn("Error while loading system rules :", e);
    }
    if (log.isInfoEnabled())
        log.debug("Finished system rule loading......");
}

From source file:com.bluexml.side.Integration.alfresco.sql.synchronization.dictionary.PropertyFileDatabaseDictionary.java

private void _loadResource(Resource r) {
    Properties properties = new Properties();
    try {//from w w  w.  jav a  2  s .  c om
        properties.load(r.getInputStream());
    } catch (IOException e) {
        logger.error(e);
    }

    for (Object property : properties.keySet()) {
        String key = (String) property;
        String value = (String) properties.getProperty(key);
        _dictionary.put(key, value);
    }

}

From source file:org.cloudbyexample.dc.agent.command.ImageClientImpl.java

private DockerImageResponse buildFromArchive(DockerImageArchive request) {
    String id = null;/*from w  ww  .  j a v a2  s  . com*/
    String tag = null;

    if (request.getRepoTags().size() > 0) {
        tag = request.getRepoTags().get(0);
    }

    logger.debug("Build image.  tag='{}'  archiveUrl='{}', ", tag, request.getArchiveUrl());

    InputStream imageInput = null;
    InputStream responseInput = null;
    String log = "";

    try {
        Resource resource = new UrlResource(request.getArchiveUrl());

        imageInput = new BufferedInputStream(resource.getInputStream());

        // FIXME: need to add no cache option
        if (tag == null) {
            responseInput = client.buildImageCmd(imageInput).withRemove(true).exec();
        } else {
            responseInput = client.buildImageCmd(imageInput).withTag(tag).withRemove(true).exec();
        }

        //            responseInput = client.buildImageCmd(in).withNoCache().withTag(id).exec();

        log = convertInputStreamToString(responseInput);

        id = matcher.findId(log);
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } finally {
        IOUtils.closeQuietly(imageInput);
        IOUtils.closeQuietly(responseInput);
    }

    DockerImageResponse reponse = new DockerImageResponse()
            .withMessageList(new Message().withMessageType(MessageType.INFO).withMessage(log))
            .withResults(request.withId(id).withRepoTags(tag));

    return reponse;
}

From source file:org.bigtester.ate.model.data.TestDatabaseInitializer.java

/**
 * @param singleInitXmlFile/*  www. ja v  a2 s  .  com*/
 *            the singleInitXmlFile to set
 * @throws IOException
 */
public void setSingleInitXmlFile(Resource singleInitXmlFile) throws IOException {
    this.singleInitXmlFile = singleInitXmlFile.getInputStream();
}

From source file:org.eclipse.gemini.blueprint.test.AbstractConfigurableBundleCreatorTests.java

/**
 * Returns the settings used for creating this jar. This method tries to
 * locate and load the settings from the location indicated by
 * {@link #getSettingsLocation()}. If no file is found, the default
 * settings will be used.//from   w w w.  j a  v a  2  s .c o  m
 * 
 * <p/> A non-null properties object will always be returned.
 * 
 * @return settings for creating the on the fly jar
 * @throws Exception if loading the settings file fails
 */
protected Properties getSettings() throws Exception {
    Properties settings = new Properties(getDefaultSettings());
    // settings.setProperty(ROOT_DIR, getRootPath());
    Resource resource = new ClassPathResource(getSettingsLocation());

    if (resource.exists()) {
        InputStream stream = resource.getInputStream();
        try {
            if (stream != null) {
                settings.load(stream);
                logger.debug("Loaded jar settings from " + getSettingsLocation());
            }
        } finally {
            IOUtils.closeStream(stream);
        }
    } else
        logger.info(getSettingsLocation() + " was not found; using defaults");

    return settings;
}

From source file:edu.kit.scc.DevelopmentConfiguration.java

/**
 * Initializes in-memory LDAP and redis.
 * //from  w w  w.jav a 2s.co  m
 * @throws LDAPException in case in-memory LDAP couldn't be created
 * @throws IOException in case in-memory redis couldn't be created
 */
@PostConstruct
public void init() throws LDAPException, IOException {
    log.debug("Set-up in-memory LDAP...");
    // set-up in-memory LDAP
    InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=springframework,dc=org");

    // schema config only necessary if the standard
    // schema provided by the library doesn't suit your needs
    config.setSchema(null);

    // listener config only necessary if you want to make sure that the
    // server listens on port 33389, otherwise a free random port will
    // be picked at runtime - which might be even better for tests btw
    config.addAdditionalBindCredentials("cn=admin", "password");
    config.setListenerConfigs(new InMemoryListenerConfig("myListener", null, ldapPort, null, null, null));

    ds = new InMemoryDirectoryServer(config);

    try {
        ds.startListening();
    } catch (LDAPException ex) {
        log.warn("LDAP server already running?");
    }

    // import your test data from ldif files
    Resource resource = new ClassPathResource("test-server.ldif");
    BufferedReader br = null;
    LDIFReader reader = null;
    try {
        br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        reader = new LDIFReader(br);
        ds.importFromLDIF(true, reader);
    } catch (IOException ex) {
        log.error("Could not read test data from ldif file");
    } finally {
        if (br != null) {
            br.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
    log.debug("Set-up in-memory redis...");
    redisServer = new RedisServer(redisPort);
    try {
        redisServer.start();
    } catch (Exception ex) {
        log.warn("Redis servier already running?");
    }
}

From source file:org.alfresco.util.resource.HierarchicalResourceLoaderTest.java

private void checkResource(Resource resource, String check) throws Throwable {
    assertNotNull("Resource not found", resource);
    assertTrue("Resource doesn't exist", resource.exists());
    InputStream is = resource.getInputStream();
    StringBuilder builder = new StringBuilder(128);
    byte[] bytes = new byte[128];
    InputStream tempIs = null;/*from  w w  w  .j  av a 2  s. co  m*/
    try {
        tempIs = new BufferedInputStream(is, 128);
        int count = -2;
        while (count != -1) {
            // do we have something previously read?
            if (count > 0) {
                String toWrite = new String(bytes, 0, count, "UTF-8");
                builder.append(toWrite);
            }
            // read the next set of bytes
            count = tempIs.read(bytes);
        }
    } catch (IOException e) {
        throw new AlfrescoRuntimeException("Unable to read stream", e);
    } finally {
        // close the input stream
        try {
            is.close();
        } catch (Exception e) {
        }
    }
    // The string
    String fileValue = builder.toString();
    assertEquals("Incorrect file retrieved: ", check, fileValue);
}

From source file:org.eclipse.gemini.blueprint.test.provisioning.internal.MavenPackagedArtifactFinder.java

/**
 * Returns the <tt>groupId</tt> setting in a <tt>pom.xml</tt> file.
 * //w  ww.  ja  va 2  s .  c o m
 * @return a <tt>pom.xml</tt> <tt>groupId</tt>.
 */
String getGroupIdFromPom(Resource pomXml) {
    try {
        DocumentLoader docLoader = new DefaultDocumentLoader();
        Document document = docLoader.loadDocument(new InputSource(pomXml.getInputStream()), null, null,
                XmlValidationModeDetector.VALIDATION_NONE, false);

        String groupId = DomUtils.getChildElementValueByTagName(document.getDocumentElement(), GROUP_ID_ELEM);
        // no groupId specified, try the parent definition
        if (groupId == null) {
            if (log.isTraceEnabled())
                log.trace("No groupId defined; checking for the parent definition");
            Element parent = DomUtils.getChildElementByTagName(document.getDocumentElement(), "parent");
            if (parent != null)
                return DomUtils.getChildElementValueByTagName(parent, GROUP_ID_ELEM);
        } else {
            return groupId;
        }
    } catch (Exception ex) {
        throw (RuntimeException) new RuntimeException(
                new ParserConfigurationException("error parsing resource=" + pomXml).initCause(ex));
    }

    throw new IllegalArgumentException(
            "no groupId or parent/groupId defined by resource [" + pomXml.getDescription() + "]");

}

From source file:org.mifos.tools.service.ConsoleReaderService.java

private void printCountries() {
    if (this.countries == null) {
        this.countries = new ArrayList<>();
        final Resource countriesResource = this.resourceLoader.getResource("classpath:template/countries.json");

        try {//  w  w  w .  jav  a 2 s . c o  m
            final JsonReader reader = new JsonReader(new InputStreamReader(countriesResource.getInputStream()));
            final List<Country> foundCountries = this.gson.fromJson(reader, new TypeToken<List<Country>>() {
            }.getType());
            this.countries.addAll(foundCountries);
        } catch (IOException e) {
            System.out.println("Could not load available countries, exit!");
            System.exit(-1);
        }
    }
    for (Country country : this.countries) {
        System.out.println(country.getCountryCode() + " (" + country.getName() + ")");
    }
}

From source file:org.openlmis.fulfillment.Resource2Db.java

Pair<List<String>, List<Object[]>> resourceCsvToBatchedPair(final Resource resource) throws IOException {
    XLOGGER.entry(resource.getDescription());

    // parse CSV/*from   w  ww .j  a v  a  2s .  co  m*/
    try (InputStreamReader isReader = new InputStreamReader(
            new BOMInputStream(resource.getInputStream(), ByteOrderMark.UTF_8))) {
        CSVParser parser = CSVFormat.DEFAULT.withHeader().withNullString("").parse(isReader);

        // read header row
        MutablePair<List<String>, List<Object[]>> readData = new MutablePair<>();
        readData.setLeft(new ArrayList<>(parser.getHeaderMap().keySet()));
        XLOGGER.info("Read header: " + readData.getLeft());

        // read data rows
        List<Object[]> rows = new ArrayList<>();
        for (CSVRecord record : parser.getRecords()) {
            if (!record.isConsistent()) {
                throw new IllegalArgumentException("CSV record inconsistent: " + record);
            }

            List theRow = IteratorUtils.toList(record.iterator());
            rows.add(theRow.toArray());
        }
        readData.setRight(rows);

        XLOGGER.exit("Records read: " + readData.getRight().size());
        return readData;
    }
}