Example usage for javax.xml.transform Source setSystemId

List of usage examples for javax.xml.transform Source setSystemId

Introduction

In this page you can find the example usage for javax.xml.transform Source setSystemId.

Prototype

public void setSystemId(String systemId);

Source Link

Document

Set the system identifier for this Source.

Usage

From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method updates existing Spring bean definitions in a XML application context file. Bean definition is
 * identified by its type defining class.
 *
 * @param project//from  w ww.  j a v a2  s.c o m
 * @param type
 * @param jaxbElement
 */
public void updateBeanDefinitions(File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
        xsltSource.setSystemId("update-bean");

        List<File> configFiles = new ArrayList<>();
        configFiles.add(configFile);
        configFiles.addAll(getConfigImports(configFile, project));

        LSParser parser = XMLUtils.createLSParser();
        GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
        parser.setFilter(getBeanFilter);

        for (File file : configFiles) {
            parser.parseURI(file.toURI().toString());
            if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
                xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

                String beanElement = type.getAnnotation(XmlRootElement.class).name();
                String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

                //create transformer
                Transformer transformer = transformerFactory.newTransformer(xsltSource);
                transformer.setParameter("bean_element", beanElement);
                transformer.setParameter("bean_namespace", beanNamespace);
                transformer.setParameter("bean_content", getXmlContent(jaxbElement)
                        .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                        .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

                //transform
                StringResult result = new StringResult();
                transformer.transform(xmlSource, result);
                FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
                return;
            }
        }
    } catch (IOException e) {
        throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
        throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
}

From source file:com.evolveum.midpoint.prism.schema.SchemaDescription.java

public Source getSource() {
    Source source = null;
    if (canInputStream()) {
        InputStream inputStream = openInputStream();
        // Return stream source as a first option. It is less effcient,
        // but it provides information about line numbers
        source = new StreamSource(inputStream);
    } else {/*from   w  w w.j  ava2s. c  om*/
        source = new DOMSource(node);
    }
    source.setSystemId(path);
    return source;
}

From source file:org.toobsframework.transformpipeline.domain.XSLUriResolverImpl.java

public Source resolve(String xslFile, String base) throws TransformerException {
    if (log.isDebugEnabled()) {
        log.debug("ENTER XSLUriResolverImpl.resolve('" + xslFile + "', '" + base + "');");
    }//from  w  w  w.ja  v a2 s.  co  m

    Source xslSource = null;
    URL xslUrl = sourceMap.get(xslFile);
    try {
        if (xslUrl == null || doReload) {
            if (applicationContext != null) {
                xslUrl = resolveContextResource(xslFile, "");
            }
            if (xslUrl == null) {
                xslUrl = resolveClasspathResource(xslFile, "");
            }
            if (xslUrl == null) {
                throw new TransformerException("xsl " + xslFile + " not found");
            }
            sourceMap.put(xslFile, xslUrl);
        }

        xslSource = new StreamSource(xslUrl.openStream());
        xslSource.setSystemId(xslUrl.getPath());
    } catch (IOException e) {
        log.error("XSL File " + xslFile + " had IOException " + e.getMessage(), e);
        throw new TransformerException("xsl " + xslFile + " cannot be loaded");
    }

    if (log.isDebugEnabled()) {
        log.debug("EXIT XSLUriResolverImpl.resolve('" + xslFile + "', '" + base + "');");
    }
    return xslSource;
}

From source file:com.wooki.services.parsers.XHTMLToFormattingObjects.java

public Source resolve(String href, String base) throws TransformerException {
    Source toReturn = null;
    if (base != null && base.contains("file://")) {
        String newPath = base.substring("file:///".length()).replace('/', File.separatorChar);
        newPath = newPath.substring(0, newPath.lastIndexOf(File.separatorChar));
        File baseFile = new File(newPath);
        baseFile = new File(
                baseFile.getAbsolutePath() + File.separatorChar + href.replace('/', File.separatorChar));
        try {/*from  www  .  ja v  a 2 s  .  c  om*/
            toReturn = new StreamSource(new FileInputStream(baseFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
            return null;
        }
    } else {
        if (base.contains("http://")) {
            String newUrl = base.substring(0, base.lastIndexOf('/') + 1);
            newUrl += href;
            HttpMethod get = new GetMethod(newUrl);
            try {
                httpClient.executeMethod(get);
                byte[] body = get.getResponseBody();
                Element element = new Element(newUrl, body);
                cache.put(element);
                toReturn = new StreamSource(new BufferedInputStream(new ByteArrayInputStream(body)));
            } catch (HttpException e) {
                e.printStackTrace();
                logger.error(e.getLocalizedMessage());
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e.getLocalizedMessage());
                return null;
            }
            toReturn.setSystemId(newUrl);
        } else {
            toReturn = new StreamSource(XHTMLToFormattingObjects.class.getResourceAsStream(href));
        }
    }
    return toReturn;
}

From source file:nl.b3p.kaartenbalie.struts.Mailer.java

protected String createHTML() throws FileNotFoundException, Exception, TransformerConfigurationException,
        TransformerException, ParserConfigurationException {

    Document xml = createFormDOM();
    if (xml == null) {
        throw new Exception("No XML created!");
    }/*w w  w  .j a v  a  2s  . com*/

    TransformerFactory tf = TransformerFactory.newInstance();

    File xslFile = new File(MyEMFDatabase.localPath(xsl));
    File xmlPath = new File(xslFile.getParent());
    Source xslSource = new SAXSource(new InputSource(new FileInputStream(xslFile)));
    /* Zorg ervoor dat in de XSL met relatieve URL's bestanden kunnen worden
     * geinclude
     */
    xslSource.setSystemId(xmlPath.toURI().toString());

    Transformer transformer = tf.newTransformer(xslSource);
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    transformer.transform(new DOMSource(xml), new StreamResult(output));

    return output.toString();
}

From source file:nl.b3p.viewer.print.PrintGenerator.java

public static void createOutput(PrintInfo info, String mimeType, InputStream xslIs, String basePath,
        OutputStream out, String filename) throws URISyntaxException, IOException {

    /* Setup fopfactory */
    FopFactory fopFactory = FopFactory.newInstance(new URI(basePath));

    try {// w  ww .j  a v a 2 s  .  co m
        /* Construct fop */
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        String fop_creator_text = "Webgis";
        foUserAgent.setCreator(fop_creator_text);
        foUserAgent.setProducer(fop_creator_text);

        Date now = new Date();
        foUserAgent.setCreationDate(now);
        foUserAgent.setTitle("Map");

        Fop fop = fopFactory.newFop(mimeType, foUserAgent, out);

        /* Setup Jaxb */
        JAXBContext jc = JAXBContext.newInstance(PrintInfo.class);
        JAXBSource src = new JAXBSource(jc, info);

        if (log.isDebugEnabled()) {
            log.debug("Print XML:\n" + PrintUtil.printInfoToString(info));
        }
        /* Setup xslt */
        Source xsltSrc = new StreamSource(xslIs);
        xsltSrc.setSystemId(basePath);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(xsltSrc);

        Result res = new SAXResult(fop.getDefaultHandler());

        transformer.transform(src, res);

    } catch (FOPException | JAXBException | TransformerException ex) {
        log.error("Error during print output: ", ex);
    } finally {
        out.close();
    }
}

From source file:nl.b3p.viewer.stripes.PrintActionBean.java

/**
 * Create the output pdf./*from   w w w  .  j a v a2 s  .  co m*/
 * @param info the print info
 * @param mimeType mimeType of the result
 * @param xslIs inputstream for xsl sheet
 * @param basePath the base path of that sheet
 * @param addJavascript addJavascript?
 * @param response the response for the outputstream
 * @throws MalformedURLException
 * @throws IOException 
 */
private void createOutput(PrintInfo info, String mimeType, InputStream xslIs, String basePath,
        boolean addJavascript, HttpServletResponse response) throws MalformedURLException, IOException {

    /* Setup fopfactory */
    FopFactory fopFactory = FopFactory.newInstance();

    /* Set BaseUrl so that fop knows paths to images etc... */
    fopFactory.setBaseURL(basePath);

    /* Setup output stream */
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        /* Construct fop */
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        foUserAgent.setCreator("Flamingo");
        foUserAgent.setProducer("Flamingo");

        Date now = new Date();
        foUserAgent.setCreationDate(now);
        foUserAgent.setTitle("Kaart");

        Fop fop = fopFactory.newFop(mimeType, foUserAgent, out);

        //String s=printInfoToString(info);
        /* Setup Jaxb */
        JAXBContext jc = JAXBContext.newInstance(PrintInfo.class);
        JAXBSource src = new JAXBSource(jc, info);

        JAXBContext jaxbContext = JAXBContext.newInstance(PrintInfo.class);
        if (log.isDebugEnabled()) {
            StringWriter sw = new StringWriter();
            jaxbContext.createMarshaller().marshal(info, sw);
            log.debug("Print XML: " + sw.toString());
        }
        /* Setup xslt */
        Source xsltSrc = new StreamSource(xslIs);
        xsltSrc.setSystemId(basePath);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(xsltSrc);

        Result res = new SAXResult(fop.getDefaultHandler());

        transformer.transform(src, res);

        /* Setup response */
        response.setContentType(mimeType);
        response.setContentLength(out.size());

        /* Set filename and extension */
        String filename = "Kaart_" + info.getDate();

        if (mimeType.equals(MimeConstants.MIME_PDF)) {
            filename += ".pdf";
        } else if (mimeType.equals(MimeConstants.MIME_RTF)) {
            filename += ".rtf";
        }

        response.setHeader("Content-Disposition", "attachment; filename=" + filename);

        //TODO: Postprocess pages to add javascript print
        /* use postprocessing with itext to add Javascript to output 
        if (addJavascript) {
        addJsToPdfOutput(out, response);
        } else {
        response.getOutputStream().write(out.toByteArray());
        }*/
        response.getOutputStream().write(out.toByteArray());

        response.getOutputStream().flush();

    } catch (Exception ex) {
        log.error("Fout tijdens print output: ", ex);
    } finally {
        out.close();
    }
}

From source file:nl.nn.adapterframework.util.TransformerPool.java

private void initTransformerPool(Source source, String sysId) throws TransformerConfigurationException {
    if (StringUtils.isNotEmpty(sysId)) {
        source.setSystemId(sysId);
        log.debug("setting systemId to [" + sysId + "]");
    }/*from   w  w  w  . j a v  a 2s.  c o m*/
    templates = tFactory.newTemplates(source);
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsModule.java

/**
 * Initializes the EPCIS schema used for validating incoming capture
 * requests. Loads the WSDL and XSD files from the classpath (the schema is
 * bundled with epcis-commons.jar).// w ww  . j  av  a 2 s.c om
 * 
 * @return An instantiated schema validation object.
 */
private Schema initEpcisSchema(String xsdFile) {
    InputStream is = this.getClass().getResourceAsStream(xsdFile);
    if (is != null) {
        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source schemaSrc = new StreamSource(is);
            schemaSrc.setSystemId(CaptureOperationsServlet.class.getResource(xsdFile).toString());
            Schema schema = schemaFactory.newSchema(schemaSrc);
            LOG.debug("EPCIS schema file initialized and loaded successfully");
            return schema;
        } catch (Exception e) {
            LOG.warn("Unable to load or parse the EPCIS schema", e);
        }
    } else {
        LOG.error("Unable to load the EPCIS schema file from classpath: cannot find resource " + xsdFile);
    }
    LOG.warn("Schema validation will not be available!");
    return null;
}

From source file:org.chiba.xml.xslt.impl.CachingTransformerService.java

/**
 * Returns a transformer for the specified stylesheet.
 * <p/>/*from ww w. jav  a  2  s . com*/
 * If the URI is null, an identity transformer is created.
 *
 * @param uri the URI identifying the stylesheet.
 * @return a transformer for the specified stylesheet.
 * @throws TransformerException if the transformer couldn't be created.
 */
public Transformer getTransformer(URI uri) throws TransformerException {
    if (uri == null) {
        return getTransformer();
    }

    try {
        // lookup cache entry
        CacheEntry entry = (CacheEntry) this.resources.get(uri);
        if (entry == null || entry.isDirty()) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("get transformer: cache " + (entry == null ? "miss" : "dirty") + " for " + uri);
            }

            // load missing/dirty resource
            Resource resource = load(uri);
            if (resource == null) {
                // complain if resource couldn't be loaded
                throw new IllegalArgumentException(uri.toString());
            }

            // sync entry with resource
            entry = sync(entry, resource);

            // store entry in cache
            this.resources.put(uri, entry);
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("get transformer: cache hit for " + uri);
            }
        }

        if (entry.templates == null) {
            // create source and templates object (this might trigger uri resolution)
            Source source = new StreamSource(entry.resource.getInputStream());
            source.setSystemId(uri.toString());
            entry.templates = getTransformerFactory().newTemplates(source);
        }

        return entry.templates.newTransformer();
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}