Example usage for javax.xml.transform.stream StreamSource StreamSource

List of usage examples for javax.xml.transform.stream StreamSource StreamSource

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamSource StreamSource.

Prototype

public StreamSource(File f) 

Source Link

Document

Construct a StreamSource from a File.

Usage

From source file:de.awtools.xml.TransformerUtils.java

/**
 * Eine <code>InputStream</code> mit XSL Daten.
 *
 * @param xsltStream <code>InputStream</code> mit XSL Daten.
 * @param resolver Ein <code>URIResolver</code>. Darf <code>null</code>
 *  sein.//from  w ww. j a v  a 2s.c  o  m
 * @return Ein <code>Transformer</code>
 */
public static Transformer getTransformer(final InputStream xsltStream, final URIResolver resolver) {

    Validate.notNull(xsltStream, "xsltStream not set");

    Source source = new StreamSource(xsltStream);
    TransformerFactory factory = TransformerFactory.newInstance();
    if (resolver != null) {
        factory.setURIResolver(resolver);
    }

    try {
        return factory.newTransformer(source);
    } catch (TransformerConfigurationException ex) {
        log.debug("Fehler:", ex);
        throw new UnhandledException(ex);
    }
}

From source file:com.manydesigns.elements.pdf.TableFormPdfExporter.java

public void export(OutputStream outputStream) throws FOPException, IOException, TransformerException {
    FopFactory fopFactory = FopFactory.newInstance();

    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputStream);

    // Setup XSLT
    TransformerFactory Factory = TransformerFactory.newInstance();
    Transformer transformer = Factory.newTransformer(xsltSource);

    // Set the value of a <param> in the stylesheet
    transformer.setParameter("versionParam", "2.0");

    // Setup input for XSLT transformation
    Reader reader = composeXml();
    Source src = new StreamSource(reader);

    // Resulting SAX events (the generated FO) must be piped through to
    // FOP//from   ww w .  j  av a  2s.c  o m
    Result res = new SAXResult(fop.getDefaultHandler());

    // Start XSLT transformation and FOP processing
    transformer.transform(src, res);
    reader.close();

    outputStream.flush();
}

From source file:edu.lternet.pasta.client.SubscriptionUtility.java

/**
 * Transforms a quality report XML document to an HTML table.
 * //w  ww  . jav a  2 s.co  m
 * @param xslPath
 *          The path to the quality report XSL stylesheet.
 * 
 * @return The HTML table as a String object.
 */
public String xmlToHtml(String xslPath) {

    String html = null;

    File styleSheet = new File(xslPath);

    StringReader stringReader = new StringReader(this.subscription);
    StringWriter stringWriter = new StringWriter();
    StreamSource styleSource = new StreamSource(styleSheet);
    Result result = new StreamResult(stringWriter);
    Source source = new StreamSource(stringReader);

    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(styleSource);
        t.transform(source, result);
        html = stringWriter.toString();
    } catch (TransformerConfigurationException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (TransformerException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    return html;

}

From source file:eu.trentorise.smartcampus.permissionprovider.manager.AttributesAdapter.java

/**
 * Load attributes from the XML descriptor.
 * @throws JAXBException//from   ww  w  .ja  v  a  2s . c  om
 */
protected void init() throws JAXBException {
    JAXBContext jaxb = JAXBContext.newInstance(AuthorityMapping.class, Authorities.class);
    Unmarshaller unm = jaxb.createUnmarshaller();
    JAXBElement<Authorities> element = (JAXBElement<Authorities>) unm
            .unmarshal(new StreamSource(getClass().getResourceAsStream("authorities.xml")), Authorities.class);
    Authorities auths = element.getValue();
    authorities = new HashMap<String, AuthorityMapping>();
    authorityMatches = ArrayListMultimap.create();//new HashMap<String, AuthorityMatching>();
    identityAttributes = new HashMap<String, Set<String>>();
    for (AuthorityMapping mapping : auths.getAuthorityMapping()) {
        Authority auth = authorityRepository.findOne(mapping.getName());
        if (auth == null) {
            auth = new Authority();
            auth.setName(mapping.getName());
            auth.setRedirectUrl(mapping.getUrl());
            authorityRepository.saveAndFlush(auth);
        }
        authorities.put(mapping.getName(), mapping);
        Set<String> identities = new HashSet<String>();
        if (mapping.getIdentifyingAttributes() != null) {
            identities.addAll(mapping.getIdentifyingAttributes());
        }
        identityAttributes.put(auth.getName(), identities);
    }
    if (auths.getAuthorityMatching() != null) {
        for (AuthorityMatching am : auths.getAuthorityMatching()) {
            for (Match match : am.getAuthority()) {
                authorityMatches.put(match.getName(), am);
            }
        }
    }
}

From source file:net.javacrumbs.airline.server.VanillaTest.java

private Document getDocument(String name) throws TransformerException {

    DOMResult result = new DOMResult();
    new TransformerHelper().transform(new StreamSource(getStream(name)), result);
    return (Document) result.getNode();

}

From source file:org.mage.server.rest.GameService.java

@RequestMapping(method = RequestMethod.POST, value = "/game/{id}")
public ModelAndView newGame(@RequestBody String body, @PathVariable String id)
        throws XmlMappingException, IOException, JAXBException {
    Source source = new StreamSource(new StringReader(body));
    Game game = (Game) jaxb2Unmarshaller.unmarshal(source);

    gameDao.save(game);/*from  w  w  w  .  j  a va2s.  c o m*/

    GameCreateResponse response = new GameCreateResponse();
    response.setValue(true);
    Response responseOuter = new Response();
    responseOuter.setGameCreated(response);

    return new ModelAndView(GAME_VIEW_NAME, "object", responseOuter);
}

From source file:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;/*from   w  ww.  j a  v  a  2 s.c  om*/

    // parse source
    try {

        JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config");
        Unmarshaller u = jc.createUnmarshaller();
        //Schedule
        Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd"));

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(schemaSource);
        u.setSchema(schema);
        ValidationEventCollector vec = new ValidationEventCollector();
        u.setEventHandler(vec);

        JAXBElement<?> rootElement;
        try {
            rootElement = ((JAXBElement<?>) u.unmarshal(source));
        } catch (UnmarshalException ex) {
            if (!vec.hasEvents()) {
                throw ex;
            } else {
                for (ValidationEvent ve : vec.getEvents()) {
                    ValidationEventLocator vel = ve.getLocator();
                    log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                }
                throw new JseException("Validation failed for source publicId='" + source.getPublicId()
                        + "'; systemId='" + source.getSystemId() + "';");
            }
        }

        schedule = (Schedule) rootElement.getValue();

        if (vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                ValidationEventLocator vel = ve.getLocator();
                log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                        + ve.getMessage());
            }
        }

    } catch (JseException e) {
        throw e;
    } catch (Exception e) {
        throw new JseException("Cannot parse " + source + ".", e);
    }

    SpringHelper springHelper = new SpringHelper();

    ////////////////
    //
    // Configure Spring and Create Beans
    //
    ////////////////

    TimeZone defaultTimeZone;

    if (schedule.isSetTimeZone()) {
        defaultTimeZone = getTimeZone(schedule.getTimeZone());
    } else {
        defaultTimeZone = TimeZone.getDefault();
    }

    if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) {
        for (Config config : schedule.getSpringContext().getConfig()) {
            springHelper.addXmlClassPathConfigLocation(config.getClassPathResource());
        }
    }

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {
        for (Job job : jobGroup.getJob()) {
            if (job.isSetBeanRef()) {
                if (job.isSetBean() || job.isSetClassName()) {
                    throw new JseException("Cannot set bean or class attribute for job when beanRef is set.");
                } // else config ok
            } else {
                if (!job.isSetClassName()) {
                    throw new JseException("must set either class or beanRef for job.");
                }
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                MutablePropertyValues propertyValues = new MutablePropertyValues();

                if (!job.isSetBean()) {
                    job.setBean(UUID.randomUUID().toString());
                }

                if (springHelper.containsBean(job.getBean())) {
                    throw new JseException(
                            "Bean name already used; overriding not allowed here: " + job.getBean());
                }

                beanDef.setBeanClassName(job.getClassName());

                for (Property prop : job.getProperty()) {
                    String value = null;
                    if (prop.isSetSystemProperty()) {
                        value = System.getProperty(prop.getSystemProperty());
                    }
                    if (null == value) {
                        value = prop.getValue();
                    }

                    propertyValues.addPropertyValue(prop.getName(), value);
                }

                beanDef.setPropertyValues(propertyValues);
                springHelper.registerBean(job.getBean(), beanDef);
                job.setBeanRef(job.getBean());
            }
        }
    }

    springHelper.init();

    ////////////////
    //
    // Configure Timer Services
    //
    ////////////////

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {

        String jobGroupName;
        JseTimerService service = new JseTimerService();

        timerServices.add(service);

        if (jobGroup.isSetName()) {
            jobGroupName = jobGroup.getName();
        } else {
            jobGroupName = UUID.randomUUID().toString();
        }

        if (jobGroup.isSetMaxConcurrent()) {
            service.setMaxConcurrent(jobGroup.getMaxConcurrent());
        }

        for (Job job : jobGroup.getJob()) {

            TimeZone jobTimeZone = defaultTimeZone;

            if (job.isSetTimeZone()) {
                jobTimeZone = getTimeZone(job.getTimeZone());
            } else {
                jobTimeZone = defaultTimeZone;
            }

            Object obj;

            Date notBefore = null;
            Date notAfter = null;

            if (job.isSetNotBefore()) {
                notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }
            if (job.isSetNotAfter()) {
                notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }

            CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(),
                    job.getMaxQueue(), notBefore, notAfter);

            obj = springHelper.getBean(job.getBeanRef());
            log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean "
                    + job.getBeanRef());
            if (obj instanceof CronJob) {
                ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs));
            }
            if (obj instanceof JseDateAwareJob) {
                service.createTimer((JseDateAwareJob) obj, cs);
            } else if (obj instanceof Runnable) {
                service.createTimer((Runnable) obj, cs);
            } else {
                throw new JseException("Job must implement Runnable or JseDateAwareJob");
            }
        }
    }
}

From source file:XmlUtils.java

private static Transformer getTransformer(String xsltFile, boolean inClassPath)
        throws TransformerConfigurationException, IOException {
    Templates tpl = XmlUtils.templates.get(xsltFile);
    if (tpl == null) {
        InputStream stream;//  w  ww.j a  v  a  2s  .c  o  m
        if (inClassPath)
            stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsltFile);
        else
            stream = new FileInputStream(xsltFile);
        Source xsltSource = new StreamSource(stream);
        tpl = XmlUtils.transFact.newTemplates(xsltSource);
        XmlUtils.templates.put(xsltFile, tpl);
    }
    return tpl.newTransformer();

}

From source file:com.oxiane.maven.xqueryMerger.Merger.java

@Override
public void execute() throws MojoExecutionException {
    Path sourceRootPath = inputSources.toPath();
    Path destinationRootPath = outputDirectory.toPath();
    IOFileFilter filter = buildFilter();
    Iterator<File> it = FileUtils.iterateFiles(inputSources, filter, FileFilterUtils.directoryFileFilter());
    if (!it.hasNext()) {
        getLog().warn("No file found matching " + filter.toString() + " in " + inputSources.getAbsolutePath());
    }/*from   ww  w . java 2  s .c o m*/
    while (it.hasNext()) {
        File sourceFile = it.next();
        Path fileSourcePath = sourceFile.toPath();
        Path relativePath = sourceRootPath.relativize(fileSourcePath);
        getLog().debug("[Merger] found source: " + fileSourcePath.toString());
        getLog().debug("[Merger]    relative path is " + relativePath.toString());
        StreamSource source = new StreamSource(sourceFile);
        XQueryMerger merger = new XQueryMerger(source);
        merger.setMainQuery();
        File destinationFile = destinationRootPath.resolve(relativePath).toFile();
        getLog().debug("[Merger]    destination will be " + destinationFile.getAbsolutePath());
        try {
            String result = merger.merge();
            destinationFile.getParentFile().mkdirs();
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destinationFile),
                    merger.getEncoding());
            osw.write(result);
            osw.flush();
            osw.close();
            getLog().debug("[Merger] " + relativePath.toString() + " merged into "
                    + destinationFile.getAbsolutePath());
        } catch (ParsingException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException("Merge of " + sourceFile.getAbsolutePath() + " fails", ex);
        } catch (FileNotFoundException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException(
                    "Unable to create destination " + destinationFile.getAbsolutePath(), ex);
        } catch (IOException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException("While writing " + destinationFile.getAbsolutePath(), ex);
        }
    }
}

From source file:eu.europa.esig.dss.validation.ValidationResourceManager.java

/**
 * This is the utility method that loads the data from the inputstream determined by the inputstream parameter into
 * a/*w ww  .  j a v  a  2  s . c o m*/
 * {@link ConstraintsParameters}.
 *
 * @param inputStream
 * @return
 */
public static ConstraintsParameters load(final InputStream inputStream) throws DSSException {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new StreamSource(
                ValidationResourceManager.class.getResourceAsStream(defaultPolicyXsdLocation)));

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);

        return (ConstraintsParameters) unmarshaller.unmarshal(inputStream);
    } catch (Exception e) {
        throw new DSSException("Unable to load policy : " + e.getMessage(), e);
    }
}