Example usage for javax.xml.transform Result getSystemId

List of usage examples for javax.xml.transform Result getSystemId

Introduction

In this page you can find the example usage for javax.xml.transform Result getSystemId.

Prototype

public String getSystemId();

Source Link

Document

Get the system identifier that was set with setSystemId.

Usage

From source file:com.betfair.cougar.marshalling.impl.databinding.xml.XMLUtils.java

public static Schema getSchema(JAXBContext context) {
    Result result = new ResultImplementation();
    SchemaOutputResolver outputResolver = new SchemaOutputResolverImpl(result);
    File tempFile = null;// w w  w .  j  a  va2 s  . c o m
    try {
        context.generateSchema(outputResolver);
        String schemaFile = result.getSystemId();
        if (schemaFile != null) {
            tempFile = new File(URI.create(schemaFile));
            String content = FileUtils.readFileToString(tempFile);

            // JAXB nicely generates a schema with element refs, unfortunately it also adds the nillable attribute to the
            // referencing element, which is invalid, it has to go on the target. this string manipulation is to move the
            // nillable attribute to the correct place, preserving it's value.
            Map<String, Boolean> referenceElementsWithNillable = new HashMap<>();
            BufferedReader br = new BufferedReader(new StringReader(content));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("<xs:element") && line.contains(" ref=\"") && line.contains(" nillable=\"")) {
                    // we've got a reference element with nillable set
                    int refStartIndex = line.indexOf(" ref=\"") + 6;
                    int refEndIndex = line.indexOf("\"", refStartIndex);
                    int nillableStartIndex = line.indexOf(" nillable=\"") + 11;
                    int nillableEndIndex = line.indexOf("\"", nillableStartIndex);
                    String ref = line.substring(refStartIndex, refEndIndex);
                    if (ref.startsWith("tns:")) {
                        ref = ref.substring(4);
                    }
                    String nillable = line.substring(nillableStartIndex, nillableEndIndex);
                    referenceElementsWithNillable.put(ref, Boolean.valueOf(nillable));
                }
            }
            // if we got some hits, then we need to rewrite this schema
            if (!referenceElementsWithNillable.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                br = new BufferedReader(new StringReader(content));
                while ((line = br.readLine()) != null) {
                    // these we need to remove the nillable section from
                    if (line.contains("<xs:element") && line.contains(" ref=\"")
                            && line.contains(" nillable=\"")) {
                        int nillableStartIndex = line.indexOf(" nillable=\"");
                        int nillableEndIndex = line.indexOf("\"", nillableStartIndex + 11);
                        line = line.substring(0, nillableStartIndex) + line.substring(nillableEndIndex + 1);
                    } else if (line.contains("<xs:element name=\"")) {
                        for (String key : referenceElementsWithNillable.keySet()) {
                            // this we need to add the nillable back to
                            String elementTagWithName = "<xs:element name=\"" + key + "\"";
                            if (line.contains(elementTagWithName)) {
                                int endOfElementName = line.indexOf(elementTagWithName)
                                        + elementTagWithName.length();
                                line = line.substring(0, endOfElementName) + " nillable=\""
                                        + referenceElementsWithNillable.get(key) + "\""
                                        + line.substring(endOfElementName);
                                break;
                            }
                        }
                    }
                    sb.append(line).append("\n");
                }
                content = sb.toString();
            }

            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            return sf.newSchema(new StreamSource(new StringReader(content)));
        }
    } catch (IOException e) {
        throw new PanicInTheCougar(e);
    } catch (SAXException e) {
        throw new PanicInTheCougar(e);
    } finally {
        if (tempFile != null)
            tempFile.delete();
    }
    return null;
}

From source file:net.sf.joost.trax.TransformerHandlerImpl.java

/**
 * Helpermethod//from w  w  w .j  a va 2s. co m
 */
private void init(Result result) throws TransformerException {

    if (DEBUG)
        log.debug("init emitter-class according to result");

    if (this.transformer instanceof TransformerImpl) {
        this.processor = ((TransformerImpl) this.transformer).getStxProcessor();

        // initialize Emitter --> DOM-, SAX- or StreamEmitter
        stxEmitter = TrAXHelper.initStxEmitter(result, processor, null);
        stxEmitter.setSystemId(result.getSystemId());
        // setting Handler
        this.processor.setContentHandler(stxEmitter);
        this.processor.setLexicalHandler(stxEmitter);
    }
}

From source file:net.sf.joost.trax.TransformerImpl.java

/**
 * Transforms a xml-source : SAXSource, DOMSource, StreamSource to SAXResult,
 * DOMResult and StreamResult//w w w.  j a v a2 s  .  co m
 *
 * @param xmlSource A <code>Source</code>
 * @param result A <code>Result</code>
 * @throws TransformerException
 */
public void transform(Source xmlSource, Result result) throws TransformerException {

    StxEmitter out = null;
    SAXSource saxSource = null;

    // should be synchronized
    synchronized (reentryGuard) {
        if (DEBUG)
            log.debug("perform transformation from " + "xml-source(SAXSource, DOMSource, StreamSource) "
                    + "to SAXResult, DOMResult or StreamResult");
        try {

            // init StxEmitter
            out = TrAXHelper.initStxEmitter(result, processor, null);
            out.setSystemId(result.getSystemId());

            this.processor.setContentHandler(out);
            this.processor.setLexicalHandler(out);

            // register ErrorListener
            if (this.errorListener != null) {
                this.processor.setErrorListener(errorListener);
            }

            // construct from source a SAXSource
            saxSource = TrAXHelper.getSAXSource(xmlSource, errorListener);

            InputSource isource = saxSource.getInputSource();

            if (isource != null) {
                if (DEBUG)
                    log.debug("perform transformation");

                if (saxSource.getXMLReader() != null) {
                    // should not be an DOMSource
                    if (xmlSource instanceof SAXSource) {

                        XMLReader xmlReader = ((SAXSource) xmlSource).getXMLReader();

                        /**
                         * URIs for Identifying Feature Flags and Properties :
                         * There is no fixed set of features or properties
                         * available for SAX2, except for two features that all XML
                         * parsers must support. Implementors are free to define
                         * new features and properties as needed, using URIs to
                         * identify them.
                         *
                         * All XML readers are required to recognize the
                         * "http://xml.org/sax/features/namespaces" and the
                         * "http://xml.org/sax/features/namespace-prefixes"
                         * features (at least to get the feature values, if not set
                         * them) and to support a true value for the namespaces
                         * property and a false value for the namespace-prefixes
                         * property. These requirements ensure that all SAX2 XML
                         * readers can provide the minimal required Namespace
                         * support for higher-level specs such as RDF, XSL, XML
                         * Schemas, and XLink. XML readers are not required to
                         * recognize or support any other features or any
                         * properties.
                         *
                         * For the complete list of standard SAX2 features and
                         * properties, see the {@link org.xml.sax} Package
                         * Description.
                         */
                        if (xmlReader != null) {
                            try {
                                // set the required
                                // "http://xml.org/sax/features/namespaces" Feature
                                xmlReader.setFeature(FEAT_NS, true);
                                // set the required
                                // "http://xml.org/sax/features/namespace-prefixes"
                                // Feature
                                xmlReader.setFeature(FEAT_NSPREFIX, false);
                                // maybe there would be other features
                            } catch (SAXException sE) {
                                getErrorListener().warning(new TransformerException(sE.getMessage(), sE));
                            }
                        }
                    }
                    // set the the SAXSource as the parent of the STX-Processor
                    this.processor.setParent(saxSource.getXMLReader());
                }

                // perform transformation
                this.processor.parse(isource);
            } else {
                TransformerException tE = new TransformerException(
                        "InputSource is null - could not perform transformation");
                getErrorListener().fatalError(tE);
            }
            // perform result
            performResults(result, out);
        } catch (SAXException ex) {
            TransformerException tE;
            Exception emb = ex.getException();
            if (emb instanceof TransformerException) {
                tE = (TransformerException) emb;
            } else {
                tE = new TransformerException(ex.getMessage(), ex);
            }
            getErrorListener().fatalError(tE);
        } catch (IOException ex) {
            // will this ever happen?
            getErrorListener().fatalError(new TransformerException(ex.getMessage(), ex));
        }
    }
}

From source file:net.sf.joost.trax.TrAXHelper.java

/**
 * HelperMethod for initiating StxEmitter.
 * @param result A <code>Result</code> object.
 * @return An <code>StxEmitter</code>.
 * @throws javax.xml.transform.TransformerException
 *///w  w w.  j a  v  a  2 s. c om
public static StxEmitter initStxEmitter(Result result, Processor processor, Properties outputProperties)
        throws TransformerException {

    if (outputProperties == null)
        outputProperties = processor.outputProperties;

    if (DEBUG)
        log.debug("init StxEmitter");
    // Return the content handler for this Result object
    try {
        // Result object could be SAXResult, DOMResult, or StreamResult
        if (result instanceof SAXResult) {
            final SAXResult target = (SAXResult) result;
            final ContentHandler handler = target.getHandler();
            if (handler != null) {
                if (DEBUG)
                    log.debug("return SAX specific Implementation for " + "StxEmitter");
                //SAX specific Implementation
                return new SAXEmitter(handler);
            }
        } else if (result instanceof DOMResult) {
            if (DEBUG)
                log.debug("return DOM specific Implementation for " + "StxEmitter");
            //DOM specific Implementation
            return new DOMEmitter((DOMResult) result);
        } else if (result instanceof StreamResult) {
            if (DEBUG)
                log.debug("return StreamResult specific Implementation " + "for StxEmitter");
            // Get StreamResult
            final StreamResult target = (StreamResult) result;
            // StreamResult may have been created with a java.io.File,
            // java.io.Writer, java.io.OutputStream or just a String
            // systemId.
            // try to get a Writer from Result object
            final Writer writer = target.getWriter();
            if (writer != null) {
                if (DEBUG)
                    log.debug("get a Writer object from Result object");
                return StreamEmitter.newEmitter(writer, DEFAULT_ENCODING, outputProperties);
            }
            // or try to get an OutputStream from Result object
            final OutputStream ostream = target.getOutputStream();
            if (ostream != null) {
                if (DEBUG)
                    log.debug("get an OutputStream from Result object");
                return StreamEmitter.newEmitter(ostream, outputProperties);
            }
            // or try to get just a systemId string from Result object
            String systemId = result.getSystemId();
            if (DEBUG)
                log.debug("get a systemId string from Result object");
            if (systemId == null) {
                if (DEBUG)
                    log.debug("JAXP_NO_RESULT_ERR");
                throw new TransformerException("JAXP_NO_RESULT_ERR");
            }
            // System Id may be in one of several forms, (1) a uri
            // that starts with 'file:', (2) uri that starts with 'http:'
            // or (3) just a filename on the local system.
            OutputStream os = null;
            URL url = null;
            if (systemId.startsWith("file:")) {
                url = new URL(systemId);
                os = new FileOutputStream(url.getFile());
                return StreamEmitter.newEmitter(os, outputProperties);
            } else if (systemId.startsWith("http:")) {
                url = new URL(systemId);
                URLConnection connection = url.openConnection();
                os = connection.getOutputStream();
                return StreamEmitter.newEmitter(os, outputProperties);
            } else {
                // system id is just a filename
                File tmp = new File(systemId);
                url = tmp.toURL();
                os = new FileOutputStream(url.getFile());
                return StreamEmitter.newEmitter(os, outputProperties);
            }
        }
        // If we cannot create the file specified by the SystemId
    } catch (IOException iE) {
        if (DEBUG)
            log.debug(iE);
        throw new TransformerException(iE);
    } catch (ParserConfigurationException pE) {
        if (DEBUG)
            log.debug(pE);
        throw new TransformerException(pE);
    }
    return null;
}