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:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*from   w  w  w  .jav a  2 s  .co  m*/

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Source source = new DOMSource(doc);

    URI uri = new File("infilename.xml").toURI();
    source.setSystemId(uri.toString());

    DefaultHandler handler = new MyHandler();
    SAXResult result = new SAXResult(handler);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
}

From source file:com.smartitengineering.cms.spi.impl.type.validator.XMLSchemaBasedTypeValidator.java

protected boolean isValid(Document document) throws Exception {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final InputStream xsdStream = getClass().getClassLoader().getResourceAsStream(XSD_LOCATION);
    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(xsdStream);
    schemaFile.setSystemId(CONTENT_TYPE_SCHEMA_URI);
    Schema schema = factory.newSchema(schemaFile);
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    try {/*from  w w w  .j a v a 2  s . c o  m*/
        validator.validate(new DOMSource(document));
        return true;
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.XsltWriter.java

public void xsltWrite(File transformationSource, URI xsltMainFileUri, File transformationTarget) {

    try {/*from  w w w  .java2s . c  om*/

        // Set up input and output files

        InputStream stream = null;

        if (xsltMainFileUri.getScheme().startsWith("http")) {
            URL url = xsltMainFileUri.toURL();
            URLConnection urlConnection = url.openConnection();
            stream = urlConnection.getInputStream();
        } else {
            File xsl = new File(xsltMainFileUri);
            // FeatureCatalogue.java already checked that file exists
            stream = new FileInputStream(xsl);
        }

        Source xsltSource = new StreamSource(stream);
        xsltSource.setSystemId(xsltMainFileUri.toString());
        Source xmlSource = new StreamSource(transformationSource);
        Result res = new StreamResult(transformationTarget);

        // create an instance of TransformerFactory
        if (xslTransformerFactory != null) {
            // use TransformerFactory specified in configuration
            System.setProperty("javax.xml.transform.TransformerFactory", xslTransformerFactory);
        } else {
            // use TransformerFactory determined by system
        }
        TransformerFactory transFact = TransformerFactory.newInstance();

        /*
         * Set URI resolver for transformation, configured with standard
         * mappings (e.g. for the localization files) and possibly other
         * mappings.
         */
        transFact.setURIResolver(new XsltUriResolver(hrefMappings));

        Transformer trans = transFact.newTransformer(xsltSource);

        /*
         * Specify any standard transformation parameters (e.g. for
         * localization).
         */
        for (String key : transformationParameters.keySet()) {
            trans.setParameter(key, transformationParameters.get(key));
        }

        /* Execute the transformation. */
        trans.transform(xmlSource, res);

    } catch (Exception e) {

        String m = e.getMessage();
        if (m != null) {
            if (result != null) {
                result.addError(m);
            } else {
                System.err.println(m);
            }
        } else {
            String msg = "Exception occurred while processing the XSL transformation.";
            if (result != null) {
                result.addError(msg);
            } else {
                System.err.println(msg);
            }
        }
    }

}

From source file:de.betterform.xml.xslt.impl.CachingTransformerService.java

/**
 * Called by the processor when it encounters an xsl:include, xsl:import, or
 * document() function./*  w w  w . ja  va2 s.  c  o m*/
 *
 * @param href the href attribute, which may be relative or absolute.
 * @param base the base URI in effect when the href attribute was encountered.
 * @return a Source object, or null if the href cannot be resolved, and the
 * processor should try to resolve the URI itself.
 * @throws TransformerException if an error occurs when trying to resolve the URI.
 */
public Source resolve(String href, String base) throws TransformerException {
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("resolve: " + href + " against " + base);
        }

        // resolve uri
        URI uri = base != null ? new URI(base).resolve(href) : new URI(href);

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

            // load missing/dirty resource
            Resource resource = load(uri);
            if (resource == null) {
                // return null to let the xslt processor attempt to resolve the uri
                return null;
            }

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

            // store entry in cache
            this.resources.put(uri, entry);

            if (base != null) {
                // add dependency to parent entry
                CacheEntry parent = (CacheEntry) this.resources.get(new URI(base));
                parent.dependencies.add(entry);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("resolve: cache hit for " + uri);
            }
        }

        // create source
        Source source = entry.resource.getSource();
        source.setSystemId(uri.toString());
        return source;
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}

From source file:de.betterform.xml.xslt.impl.CachingTransformerService.java

/**
 * Returns a transformer for the specified stylesheet.
 * <p/>//  w w  w  . j  ava2  s  .c  om
 * 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 (nocache == true || 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);
            this.name2URI.put(getXsltName(uri), uri);
        } 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);
    }
}

From source file:com.netspective.commons.xml.ParseContext.java

public void doExternalTransformations() throws TransformerConfigurationException, TransformerException,
        ParserConfigurationException, SAXException, IOException {
    // re-create the input source because the original stream is already closed
    InputSource inputSource = recreateInputSource();

    Source activeSource = inputSource.getByteStream() != null ? new StreamSource(inputSource.getByteStream())
            : new StreamSource(inputSource.getCharacterStream());
    activeSource.setSystemId(inputSource.getSystemId());

    Writer activeResultBuffer = new StringWriter();
    Result activeResult = new StreamResult(activeResultBuffer);
    activeResult.setSystemId(activeResultBuffer.getClass().getName());

    TransformerFactory factory = TransformerFactory.newInstance();
    int lastTransformer = transformSources.length - 1;
    for (int i = 0; i <= lastTransformer; i++) {
        Transformer transformer = factory.newTransformer(transformSources[i]);
        transformer.transform(activeSource, activeResult);

        if (i < lastTransformer) {
            activeSource = new StreamSource(new StringReader(activeResultBuffer.toString()));
            activeResultBuffer = new StringWriter();
            activeResult = new StreamResult(activeResultBuffer);
        }/*  w w w .j av a 2s  .co  m*/
    }

    // now that all the transformations have been performed, we want to reset our input source to the final
    // transformation
    init(createInputSource(activeResultBuffer.toString()));
}

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

/**
 * Method adds a new Spring bean definition to the XML application context file.
 * @param project//from  w w w  . ja v  a 2 s .  c o m
 * @param jaxbElement
 */
public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
        xsltSource.setSystemId("add-bean");
        xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

        //create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_content", getXmlContent(jaxbElement).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()), configFile);
        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.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method removes a Spring bean definition from the XML application context file. Bean definition is
 * identified by its id or bean name./*from ww w  . j av a 2 s. co  m*/
 * @param project
 * @param id
 */
public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream());
        xsltSource.setSystemId("delete-bean");

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

        for (File file : configFiles) {
            xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

            //create transformer
            Transformer transformer = transformerFactory.newTransformer(xsltSource);
            transformer.setParameter("bean_id", id);

            //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.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method removes all Spring bean definitions of given type from the XML application context file.
 * @param project/* www.  jav a 2s .c  o  m*/
 * @param type
 */
public void removeBeanDefinitions(File configFile, Project project, Class<?> type) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean-type.xsl").getInputStream());
        xsltSource.setSystemId("delete-bean");

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

        for (File file : configFiles) {
            xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

            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);

            //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.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method updates an existing Spring bean definition in a XML application context file. Bean definition is
 * identified by its id or bean name./*from   w  w w  . j  a  va 2s.  co m*/
 * @param project
 * @param id
 * @param jaxbElement
 */
public void updateBeanDefinition(File configFile, Project project, String id, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/update-bean.xsl").getInputStream());
        xsltSource.setSystemId("update-bean");

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

        LSParser parser = XMLUtils.createLSParser();
        GetSpringBeanFilter getBeanFilter = new GetSpringBeanFilter(id, jaxbElement.getClass());
        parser.setFilter(getBeanFilter);

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

                //create transformer
                Transformer transformer = transformerFactory.newTransformer(xsltSource);
                transformer.setParameter("bean_id", id);
                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);
    }
}