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.github.mrstampy.gameboot.messages.context.GameBootContextLoader.java

/**
 * Gets the for locale.//from  www .  ja  v  a2 s  . c o m
 *
 * @param suffix
 *          the suffix
 * @return the for locale
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public Map<Integer, ResponseContext> getForLocale(String suffix) throws IOException {
    Resource r = getOverridableErrorResource(suffix);

    if (r == null || !r.exists()) {
        log.trace("No error.properties for {}", suffix);
        return null;
    }

    Properties p = new Properties();
    p.load(r.getInputStream());

    List<String> codes = getCodes(p);

    Map<Integer, ResponseContext> map = new ConcurrentHashMap<>();

    codes.forEach(c -> createError(c, p, map));
    return map;
}

From source file:org.obiba.onyx.print.impl.DefaultPdfTemplateEngine.java

public InputStream applyTemplate(Locale locale, Map<String, String> fieldToVariableMap,
        LocalizedResourceLoader reportTemplateLoader, ActiveInterviewService activeInterviewService) {

    // Get report template
    Resource resource = reportTemplateLoader.getLocalizedResource(locale);

    // Read report template
    PdfReader pdfReader;//from   ww  w .  j  a v a  2  s .c  om
    try {
        pdfReader = new PdfReader(resource.getInputStream());
    } catch (Exception ex) {
        throw new RuntimeException("Report to participant template cannot be read", ex);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = null;

    // Set the values in the report data fields
    try {
        stamper = new PdfStamper(pdfReader, output);
        stamper.setFormFlattening(true);

        AcroFields form = stamper.getAcroFields();
        Participant participant = activeInterviewService.getParticipant();

        setVariableDataFields(participant, form, fieldToVariableMap);
        setAdditionalDataFields(form);

    } catch (Exception ex) {
        throw new RuntimeException("An error occured while preparing the report to participant", ex);
    } finally {
        try {
            stamper.close();
        } catch (Exception e) {
            log.warn("Could not close PdfStamper", e);
        }
        try {
            output.close();
        } catch (IOException e) {
            log.warn("Could not close OutputStream", e);
        }
        pdfReader.close();
    }

    return new ByteArrayInputStream(output.toByteArray());
}

From source file:com.github.eddumelendez.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration.java

private void populateDirectoryServer() throws LDAPException {
    String location = this.embeddedProperties.getLdif();
    if (StringUtils.hasText(location)) {
        try {/*from   w w w  .  j  av a  2  s .com*/
            Resource resource = this.applicationContext.getResource(this.embeddedProperties.getLdif());
            if (resource.exists()) {
                File tempFile = File.createTempFile("ldap_test_data", ".ldif");
                try {
                    InputStream inputStream = resource.getInputStream();
                    FileCopyUtils.copy(inputStream, new FileOutputStream(tempFile));
                    this.server.importFromLDIF(true, new LDIFReader(tempFile));
                } catch (LDAPException e) {
                    e.printStackTrace();
                } finally {
                    tempFile.delete();
                }
            }
        } catch (IOException ex) {
            throw new IllegalStateException("Unable to load resource from " + location, ex);
        }
    }
}

From source file:org.jasig.schedassist.impl.caldav.xml.ReportResponseHandlerImplTest.java

@Test
public void testBedworkSchedulingAssistant() throws IOException {
    Resource controlExample = new ClassPathResource(
            "caldav-examples/report-response-bedework-scheduling-assistant.xml");

    ReportResponseHandlerImpl handler = new ReportResponseHandlerImpl();
    List<CalendarWithURI> calendars = handler.extractCalendars(controlExample.getInputStream());
    Assert.assertEquals(1, calendars.size());

    CalendarWithURI withUri = calendars.get(0);
    Assert.assertEquals("/ucaldav/user/schwag/calendar/68b9d022-7a39-41ec-97c7-0e0e7fca74a6.ics",
            withUri.getUri());/*w w  w . j  av  a2s  .  co m*/
    Assert.assertEquals("\"20110505T173152Z-0\"", withUri.getEtag());
    Calendar cal = withUri.getCalendar();
    ProdId prodId = cal.getProductId();
    Assert.assertNotNull(prodId);
    Assert.assertEquals("//Bedework.org//BedeWork V3.7//EN", prodId.getValue());

    ComponentList components = cal.getComponents(VEvent.VEVENT);
    Assert.assertEquals(1, components.size());
    VEvent event = (VEvent) components.get(0);
    Assert.assertEquals("test appointment with Johnson, Arlen", event.getSummary().getValue());
    Organizer organizer = event.getOrganizer();
    Assert.assertNotNull(organizer);
    Assert.assertEquals("mailto:schwag@mysite.org", organizer.getValue());
    Assert.assertEquals(1, organizer.getParameters().size());
    Assert.assertEquals("Schwartz, Gary", organizer.getParameter(Cn.CN).getValue());
    Assert.assertEquals("need help picking classes", event.getDescription().getValue());
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            event.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
}

From source file:com.haulmont.restapi.config.RestQueriesConfiguration.java

protected void init() {
    String configName = AppContext.getProperty(CUBA_REST_QUERIES_CONFIG_PROP_NAME);
    StrTokenizer tokenizer = new StrTokenizer(configName);
    for (String location : tokenizer.getTokenArray()) {
        Resource resource = resources.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                loadConfig(Dom4j.readDocument(stream).getRootElement());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(stream);
            }/*from w  w w . j  a  v  a  2  s . c  o m*/
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }
}

From source file:com.opengamma.examples.livedata.ExampleLiveDataServer.java

private void readInitialValues(Resource initialValuesFile) {
    CSVReader reader = null;/*from www  .  ja  v  a2s . c o  m*/
    try {
        reader = new CSVReader(new BufferedReader(new InputStreamReader(initialValuesFile.getInputStream())));
        // Read header row
        @SuppressWarnings("unused")
        String[] headers = reader.readNext();
        String[] line;
        int lineNum = 1;
        while ((line = reader.readNext()) != null) {
            lineNum++;
            if (line.length > 0 && line[0].startsWith("#")) {
                continue;
            }
            if (line.length != NUM_FIELDS) {
                s_logger.error("Not enough fields in CSV on line " + lineNum);
            } else {
                String identifier = line[0];
                String fieldName = line[1];
                String valueStr = line[2];
                Double value = Double.parseDouble(valueStr);
                addTicks(identifier, fieldName, value);
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.iflytek.edu.cloud.frame.support.jdbc.CustomSQL.java

public void init() {
    reloadSQLFiles = Boolean.valueOf(System.getProperty("reloadSQLFiles"));

    try {//from w w w  . j  av a  2 s. c  o  m
        engine = Engine.getEngine();

        Resource[] configs = loadConfigs();
        for (Resource _config : configs) {
            logger.info("Loading " + _config.getURL().getPath());
            configMap.put(_config.getURL().getPath(), _config.lastModified());
            read(_config.getInputStream());
        }
    } catch (Exception e) {
        logger.error("", e);
    }
}

From source file:nl.surfnet.coin.selfservice.service.impl.PersonAttributeLabelServiceJsonImpl.java

private void populate() throws IOException {
    Resource jsonResource;
    if (attributeJsonFile.startsWith("classpath:")) {
        jsonResource = new ClassPathResource(attributeJsonFile.substring("classpath:".length()));
    } else {/*from  w  ww  .j  ava  2  s.  co  m*/
        jsonResource = new FileSystemResource(attributeJsonFile);
    }
    labelMap = parseStreamToAttributeLabelMap(IOUtils.toString(jsonResource.getInputStream()));
}

From source file:edu.unc.lib.dl.schematron.SchematronValidator.java

/**
 * Use this to initialize the configured schemas. Generate stylesheet
 * implementations of ISO Schematron files and preload them into Transformer
 * Templates for quick use.//from www.j a  v a  2 s.  c o m
 */
public void loadSchemas() {
    templates = new HashMap<String, Templates>();
    // Load up a transformer and the ISO Schematron to XSL templates.
    Templates isoSVRLTemplates = null;
    ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl",
            SchematronValidator.class);
    Source svrlrc;
    try {
        svrlrc = new StreamSource(svrlRes.getInputStream());
    } catch (IOException e1) {
        throw new Error("Cannot load iso_svrl.xsl", e1);
    }
    TransformerFactory factory = null;
    try {
        factory = new TransformerFactoryImpl();
        // enable relative classpath-based URIs
        factory.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class);
                Source result;
                try {
                    result = new StreamSource(svrlRes.getInputStream());
                } catch (IOException e1) {
                    throw new TransformerException("Cannot resolve " + href, e1);
                }
                return result;
            }
        });
        isoSVRLTemplates = factory.newTemplates(svrlrc);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Error setting up transformer factory.", e);
        throw new Error("Error setting up transformer factory", e);
    } catch (TransformerConfigurationException e) {
        log.error("Error setting up transformer.", e);
        throw new Error("Error setting up transformer", e);
    }

    // Get a transformer
    Transformer t = null;
    try {
        t = isoSVRLTemplates.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Error("There was a problem configuring the transformer.", e);
    }

    for (String schema : schemas.keySet()) {
        // make XSLT out of Schematron for each schema
        Resource resource = schemas.get(schema);
        Source schematron = null;
        try {
            schematron = new StreamSource(resource.getInputStream());
        } catch (IOException e) {
            throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription()
                    + resource.toString());
        }
        JDOMResult res = new JDOMResult();
        try {
            t.transform(schematron, res);
        } catch (TransformerException e) {
            throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e);
        }

        // compile templates object for each profile
        try {
            Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument()));
            templates.put(schema, schemaTemplates);
        } catch (TransformerConfigurationException e) {
            throw new Error("There was a problem configuring the transformer.", e);
        }
    }

}

From source file:org.paxml.launch.LaunchModelBuilder.java

/**
 * Build from spring resource that points to xml.
 * //from  www  . j  a  v  a2 s.co  m
 * @param res
 *            the resource
 * @param props
 *            the initial properties to execute the plan file with
 * @return the launch model, never null.
 */
public LaunchModel build(Resource res, Properties props) {
    OMElement root = null;
    InputStream in = null;
    try {
        model = new LaunchModel();
        planFile = res;

        in = res.getInputStream();

        model.setResource(res);

        root = AxiomUtils.getRootElement(in);

        // build the primitive parts
        buildLibraries(root, true);
        buildListeners(root, true);
        buildResources(root, true);

        model.setName(AxiomUtils.getAttribute(root, NAME));

        model.setPlanEntity(processPlan(root, props));

        return model;
    } catch (IOException e) {
        throw new PaxmlRuntimeException("Cannot open stream from resource: " + res, e);
    } finally {
        planFile = null;
        model = null;

        IOUtils.closeQuietly(in);
        if (root != null) {
            root.close(false);
        }
    }
}