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:org.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetriever.java

/**
 * Loads the portlet.xml file using the configured <tt>ResourceLoader</tt> and
 * parses the role-name elements from it, using these as the set of <tt>mappableAttributes</tt>.
 *//*  ww w  .  j  a  v a2s .  c  om*/
public void afterPropertiesSet() throws Exception {
    Resource portletXml = resourceLoader.getResource("/WEB-INF/portlet.xml");
    Document doc = getDocument(portletXml.getInputStream());

    final XPathExpression roleNamesExpression;
    if (portletConfig == null) {
        final XPathFactory xPathFactory = XPathFactory.newInstance();

        final XPath xPath = xPathFactory.newXPath();
        roleNamesExpression = xPath.compile("/portlet-app/portlet/security-role-ref/role-name");
    } else {
        final XPathFactory xPathFactory = XPathFactory.newInstance();
        xPathFactory.setXPathVariableResolver(new XPathVariableResolver() {
            @Override
            public Object resolveVariable(QName variableName) {
                if ("portletName".equals(variableName.getLocalPart())) {
                    return portletConfig.getPortletName();
                }

                return null;
            }
        });
        final XPath xPath = xPathFactory.newXPath();
        roleNamesExpression = xPath
                .compile("/portlet-app/portlet[portlet-name=$portletName]/security-role-ref/role-name");
    }

    final NodeList securityRoles = (NodeList) roleNamesExpression.evaluate(doc, XPathConstants.NODESET);
    final Set<String> roleNames = new HashSet<String>();

    for (int i = 0; i < securityRoles.getLength(); i++) {
        Element secRoleElt = (Element) securityRoles.item(i);
        String roleName = secRoleElt.getTextContent().trim();
        roleNames.add(roleName);
        logger.info("Retrieved role-name '" + roleName + "' from portlet.xml");
    }

    if (roleNames.isEmpty()) {
        logger.info("No security-role-ref elements found in " + portletXml
                + (portletConfig == null ? "" : " for portlet " + portletConfig.getPortletName()));
    }

    mappableAttributes = Collections.unmodifiableSet(roleNames);
}

From source file:br.com.edo.atmlist.controller.ATMController.java

@Secured("authenticated")
@RequestMapping(value = "/atmList", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody Object getATMListFromServer(ModelMap map) {
    map.put("greeting", "ING ATM List");

    try {/*  w w w.  j a v  a 2  s . c om*/
        ApplicationContext appContext = new ClassPathXmlApplicationContext();
        System.out.println("----");
        Resource resource = appContext.getResource("url:https://www.ing.nl/api/locator/atms/");

        BufferedReader streamReader = new BufferedReader(
                new InputStreamReader(resource.getInputStream(), "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        // Skip first line
        inputStr = streamReader.readLine();
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }
        ObjectMapper mapper = new ObjectMapper();
        atmServerList = mapper.readValue(responseStrBuilder.toString(), List.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return atmServerList;
}

From source file:org.kuali.maven.plugins.graph.processor.StyleProcessor.java

protected Properties getProperties() {
    String location = "classpath:dot.properties";
    ResourceLoader loader = new DefaultResourceLoader();
    Resource resource = loader.getResource(location);
    InputStream in = null;/*  ww w. ja v  a2s  .  co m*/
    try {
        Properties properties = new Properties();
        in = resource.getInputStream();
        properties.load(in);
        return properties;
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.sakaiproject.imagegallery.springutil.SqlScriptRunner.java

public void executeScript() {
    if (log.isInfoEnabled())
        log.info("Executing SQL script '" + sqlResourcePath + "'");
    Resource sqlResource = resourceLoader.getResource(sqlResourcePath);
    String[] sqlStatements;/*from  www . ja v a 2 s.c o m*/
    try {
        sqlStatements = SqlScriptParser.parse(new InputStreamReader(sqlResource.getInputStream()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    for (int i = 0; i < sqlStatements.length; i++) {
        try {
            getJdbcTemplate().execute(sqlStatements[i]);
        } catch (DataAccessException e) {
            if (continueOnError) {
                if (log.isDebugEnabled()) {
                    log.debug("SQL: " + sqlStatements[i] + " failed; continuing", e);
                } else if (log.isInfoEnabled()) {
                    log.info("SQL: " + sqlStatements[i] + " failed on exeception; " + e.getMessage()
                            + ", continuing");
                }
            } else if (failQuietlyOnError) {
                if (log.isDebugEnabled()) {
                    log.debug("SQL: " + sqlStatements[i] + " failed; stopping", e);
                } else if (log.isInfoEnabled()) {
                    log.info("SQL: " + sqlStatements[i] + " failed on exeception; " + e.getMessage()
                            + ", stopping");
                }
                return;
            } else {
                throw e;
            }
        }
    }
    if (log.isInfoEnabled())
        log.info("Done executing SQL script '" + sqlResourcePath + "'");
}

From source file:org.globus.security.stores.ResourceProxyCredential.java

protected X509Credential create(Resource resource) throws ResourceStoreException {

    InputStream keyInputStream = null;
    InputStream certInputStream = null;
    try {//from w w  w.  ja  v  a  2  s .  c  om
        keyInputStream = new BufferedInputStream(resource.getInputStream());
        certInputStream = new BufferedInputStream(resource.getInputStream());
        return new X509Credential(keyInputStream, certInputStream);
    } catch (IOException e) {
        throw new ResourceStoreException(e);
    } catch (CredentialException e) {
        throw new ResourceStoreException(e);
    } finally {

        if (keyInputStream != null) {
            try {
                keyInputStream.close();
            } catch (Exception e) {
                logger.warning("Unable to close stream.");
            }
        }
        if (certInputStream != null) {
            try {
                certInputStream.close();
            } catch (Exception e) {
                logger.warning("Unable to close stream.");
            }
        }
    }
}

From source file:org.jasig.schedassist.model.ICalendarDataTest.java

@Test
public void testParseCalendarDataWithRDateList() throws IOException, ParserException {
    Resource exampleData = new ClassPathResource("org/jasig/schedassist/model/example-reflection-2.ics");
    CalendarBuilder builder = new CalendarBuilder();
    Calendar result = builder.build(new InputStreamReader(exampleData.getInputStream()));
    Assert.assertNotNull(result);/* w  w w . ja v  a  2 s.  c o m*/
    ComponentList components = result.getComponents(VEvent.VEVENT);
    Assert.assertEquals(1, components.size());
    VEvent event = (VEvent) components.get(0);

    Property rdate = event.getProperty(RDate.RDATE);
    Assert.assertNotNull(rdate);
    Assert.assertEquals("20110921,20110923,20110926,20110928,20110930", rdate.getValue());

}

From source file:edu.cmu.lti.oaqa.framework.eval.gs.PassageGoldStandardFilePersistenceProvider.java

@Override
public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams)
        throws ResourceInitializationException {
    boolean ret = super.initialize(aSpecifier, aAdditionalParams);
    String dataset = (String) getParameterValue("DataSet");
    Pattern lineSyntaxPattern = Pattern.compile((String) getParameterValue("LineSyntax"));
    try {//from w  w w  .j a  v a 2s . co m
        Resource[] resources = resolver.getResources((String) getParameterValue("PathPattern"));
        for (Resource resource : resources) {
            Scanner scanner = new Scanner(resource.getInputStream());
            while (scanner.findInLine(lineSyntaxPattern) != null) {
                MatchResult result = scanner.match();
                DatasetSequenceId id = new DatasetSequenceId(dataset, result.group(1));
                List<GoldStandardSpan> list = id2gsSpans.get(id);
                if (list == null) {
                    list = new ArrayList<GoldStandardSpan>();
                    id2gsSpans.put(id, list);
                }
                GoldStandardSpan annotation = new GoldStandardSpan(result.group(2),
                        Integer.parseInt(result.group(3)), Integer.parseInt(result.group(4)), result.group(5));
                list.add(annotation);
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                } else {
                    break;
                }
            }
            scanner.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:org.brekka.stillingar.spring.version.ApplicationVersionFromMaven.java

/**
 * Identify the version. Should only need to be invoked once.
 * //from   w w  w  . jav a  2  s  . c om
 * @return the version or null if it cannot be identified
 */
@Override
public String identifyVersion() {
    String version = null;
    String path = format(POM_CLASSPATH_FORMAT, groupId, artifactId);
    InputStream is = resolveClassloader.getResourceAsStream(path);

    if (is == null && applicationContext != null) {
        // Not found on classpath
        Resource resource = applicationContext.getResource(path);
        if (resource != null) {
            try {
                is = resource.getInputStream();
            } catch (IOException e) {
                if (log.isWarnEnabled()) {
                    log.warn(format("Failed to load 'pom.properties' from application "
                            + "context for group '%s', artifact '%s'.", groupId, artifactId));
                }
            }
        }
    }

    if (is != null) {
        Properties props = new Properties();
        try {
            props.load(is);
            version = props.getProperty(POM_PROPS_VERSION);
        } catch (IOException e) {
            if (log.isWarnEnabled()) {
                log.warn(format(
                        "Failed to load 'pom.properties' from classpath for group '%s', artifact '%s'. "
                                + "No version will be included in the resource file names.",
                        groupId, artifactId));
            }
        } finally {
            closeQuietly(is);
        }
    } else {
        if (log.isWarnEnabled()) {
            log.warn(format("Unable to locate 'pom.properties' for group '%s', artifact '%s'. "
                    + "No version will be included in the resource file names.", groupId, artifactId));
        }
    }
    return version;
}

From source file:com.enonic.cms.business.SitePropertiesServiceImpl.java

private Properties loadSiteProperties(SiteKey siteKey) {
    Properties siteProperties = new Properties(defaultProperties);
    siteProperties.setProperty("sitekey", String.valueOf(siteKey));

    String relativePathToCmsHome = "/config/site-" + siteKey + ".properties";
    try {//from  ww  w.j  a  va  2  s . c o  m
        String resourcePath = homeService.getHomeDir().getURL() + relativePathToCmsHome;
        Resource resource = resourceLoader.getResource(resourcePath);
        boolean useCustomProperties = resource.exists();
        if (useCustomProperties) {
            InputStream stream = resource.getInputStream();
            siteProperties.load(stream);
            siteProperties.setProperty("customSiteProperties", "true");
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to load site properties file: " + relativePathToCmsHome, e);
    }

    siteProperties.setProperty(SitePropertyNames.URL_DEFAULT_CHARACTER_ENCODING,
            VerticalProperties.getVerticalProperties().getUrlCharacterEncoding());
    sitePropertiesMap.put(siteKey, siteProperties);

    return siteProperties;
}

From source file:de.alpharogroup.mystic.crypt.actions.ShowLicenseFrameAction.java

/**
 * Load license./*from   www. j  a v  a  2 s. c o m*/
 *
 * @return the string
 */
private String loadLicense() {

    final ApplicationContext ctx = SpringApplicationContext.getInstance().getApplicationContext();
    final Resource resource = ctx.getResource("classpath:LICENSE.txt");
    InputStream is = null;
    final StringBuffer license = new StringBuffer();
    try {
        String thisLine;
        is = resource.getInputStream();
        final BufferedReader br = new BufferedReader(new InputStreamReader(is));
        while ((thisLine = br.readLine()) != null) {
            license.append(thisLine + "\n");
        }
    } catch (final IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            StreamExtensions.close(is);
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    return license.toString();
}