Example usage for javax.xml.transform.dom DOMResult DOMResult

List of usage examples for javax.xml.transform.dom DOMResult DOMResult

Introduction

In this page you can find the example usage for javax.xml.transform.dom DOMResult DOMResult.

Prototype

public DOMResult() 

Source Link

Document

Zero-argument default constructor.

Usage

From source file:ambit.data.qmrf.QMRFObject.java

public void export2PDF(InputStream xsltfo, OutputStream pdf) throws Exception {
    Document doc = buildDocument();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xslt = builder.parse(xsltfo);
    DOMResult result = new DOMResult();
    transform(new DOMSource(doc), new DOMSource(xslt), result);
    Document foDom = (Document) result.getNode();
    convertDOM2PDF(foDom, pdf);//from  w  w  w  .j av a 2  s.co  m
}

From source file:eu.betaas.service.securitymanager.service.impl.AuthorizationService.java

/**
 * Check the condition specified in the token with the condition saved in the 
 * GW (concerning the specific thingService)
 * @param ct: extracted Condition from the token
 * @param req: RequestCtx (required by XACML API)
 * @return boolean true or false (true if the condition matches)
 *//*  w ww.j a va 2 s. c o m*/
private boolean checkCondition(ConditionType ct, RequestCtx req) {
    boolean access = false;

    JAXBElement<ConditionType> jaxbCT = of.createCondition(ct);
    JAXBContext jc = null;
    try {
        jc = JAXBContext.newInstance(ConditionType.class);
        Marshaller mar = jc.createMarshaller();

        // create DOM Document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();

        mar.marshal(jaxbCT, doc);

        // convert ConditionType to XML Node (org.w3c.dom.Node)
        DOMResult res = new DOMResult();
        res.setNode(doc.getDocumentElement());
        Node conditionNode = res.getNode();

        // prepare for the Condition
        PolicyMetaData metadata = new PolicyMetaData(2, 0);
        VariableManager vm = new VariableManager(new HashMap(), metadata);
        Condition condition = Condition.getInstance(conditionNode, metadata, vm);

        // evaluate condition -- first convert RequestCtx into EvaluationCtx
        EvaluationCtx context = new BasicEvaluationCtx(req);
        EvaluationResult result = condition.evaluate(context);
        BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue());
        // get the condition evaluation result in boolean
        access = bool.getValue();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParsingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    log.info("Checking Condition in the Access Right return: " + access);

    return access;
}

From source file:ambit.data.qmrf.QMRFObject.java

public void transform_and_read(Reader in, boolean appendHelp) throws Exception {

    DOMResult result = new DOMResult();
    String filename = "ambit/data/qmrf/qmrf_insert_help.xsl";
    if (!appendHelp)
        filename = "ambit/data/qmrf/qmrf_delete_help.xsl";
    InputStream xslt = this.getClass().getClassLoader().getResourceAsStream(filename);
    xsltTransform(in, xslt, result);/*from   w ww  .  j  ava2  s  .c  om*/
    xslt.close();

    Document doc = (Document) result.getNode();
    doc.normalize();

    fromXML(doc.getDocumentElement());
    setNotModified();
    fireAmbitObjectEvent();
}

From source file:com.evolveum.midpoint.testing.model.client.sample.Main.java

private static QueryType createUserQuery2(String username) throws JAXBException {
    QueryType query = new QueryType();

    SearchFilterType filter = new SearchFilterType();

    PropertyComplexValueFilterClauseType fc = new PropertyComplexValueFilterClauseType();
    ItemPathType path = new ItemPathType();
    path.setValue("declare namespace c=\"http://midpoint.evolveum.com/xml/ns/public/common/common-3\"; c:name");
    fc.setPath(path);/*from w  w w . ja  v a 2s .co m*/
    fc.setValue(username);

    ObjectFactory factory = new ObjectFactory();
    JAXBElement<PropertyComplexValueFilterClauseType> equal = factory.createEqual(fc);

    JAXBContext jaxbContext = JAXBContext.newInstance("com.evolveum.midpoint.xml.ns._public.common.api_types_3:"
            + "com.evolveum.midpoint.xml.ns._public.common.common_3:"
            + "com.evolveum.prism.xml.ns._public.annotation_3:" + "com.evolveum.prism.xml.ns._public.query_3:"
            + "com.evolveum.prism.xml.ns._public.types_3:");
    Marshaller marshaller = jaxbContext.createMarshaller();
    DOMResult result = new DOMResult();
    marshaller.marshal(equal, result);
    filter.setFilterClause(((Document) result.getNode()).getDocumentElement());

    query.setFilter(filter);
    return query;
}

From source file:de.betterform.agent.web.WebProcessor.java

private void doIncludes() {
    try {//ww w .  ja v  a  2 s  .c o m
        Node input = getXForms();
        String xsltPath = RESOURCE_DIR + "xslt/";
        URI styleURI = new File(WebFactory.getRealPath(xsltPath, getContext())).toURI()
                .resolve(new URI("include.xsl"));
        XSLTGenerator xsltGenerator = WebFactory.setupTransformer(styleURI, getContext());
        String baseURI = getBaseURI();
        String uri = baseURI.substring(0, baseURI.lastIndexOf("/") + 1);

        xsltGenerator.setParameter("root", uri);
        DOMResult result = new DOMResult();
        DOMSource source = new DOMSource(input);
        xsltGenerator.setInput(source);
        xsltGenerator.setOutput(result);
        xsltGenerator.generate();
        setXForms(result.getNode());

    } catch (XFormsException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

}

From source file:org.geowebcache.config.XMLConfiguration.java

private static Node applyTransform(Node oldRootNode, String xslFilename) {
    DOMResult result = new DOMResult();
    Transformer transformer;// w ww . j  a va2 s. co m

    InputStream is = XMLConfiguration.class.getResourceAsStream(xslFilename);

    try {
        transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(is));
        transformer.transform(new DOMSource(oldRootNode), result);
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    return result.getNode();
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

/**
 * Run the zip file through the xsl stylesheet
 *
 * @param zip          the zip archive containing the items to ingest
 * @param zipInfo      the document describing the zip archive (adheres to zip.dtd)
 * @param articleXml      the stylesheet to run on <var>zipInfo</var>; this is the main script
 * @param doiUrlPrefix DOI URL prefix//from ww  w  .  ja va2 s.  c  o  m
 * @return a document describing the fedora objects to create (must adhere to fedora.dtd)
 * @throws javax.xml.transform.TransformerException
 *          if an error occurs during the processing
 */
private Document transformZip(ZipFile zip, String zipInfo, Document articleXml, String doiUrlPrefix)
        throws TransformerException, URISyntaxException {
    Transformer t = getTranslet(articleXml);
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setURIResolver(new ZipURIResolver(zip));

    // override the doi url prefix if one is specified in the config
    if (doiUrlPrefix != null)
        t.setParameter("doi-url-prefix", doiUrlPrefix);

    /*
     * Note: it would be preferable (and correct according to latest JAXP specs) to use
     * t.setErrorListener(), but Saxon does not forward <xls:message>'s to the error listener.
     * Hence we need to use Saxon's API's in order to get at those messages.
     */
    final StringWriter msgs = new StringWriter();
    MessageWarner em = new MessageWarner();
    ((Controller) t).setMessageEmitter(em);
    t.setErrorListener(new ErrorListener() {
        public void warning(TransformerException te) {
            log.warn("Warning received while processing zip", te);
        }

        public void error(TransformerException te) {
            log.warn("Error received while processing zip", te);
            msgs.write(te.getMessageAndLocation() + '\n');
        }

        public void fatalError(TransformerException te) {
            log.warn("Fatal error received while processing zip", te);
            msgs.write(te.getMessageAndLocation() + '\n');
        }
    });

    Source inp = new StreamSource(new StringReader(zipInfo), "zip:/");
    DOMResult res = new DOMResult();

    try {
        t.transform(inp, res);
    } catch (TransformerException te) {
        if (msgs.getBuffer().length() > 0) {
            log.error(msgs.getBuffer().toString());
            throw new TransformerException(msgs.toString(), te);
        } else
            throw te;
    }
    if (msgs.getBuffer().length() > 0)
        throw new TransformerException(msgs.toString());
    return (Document) res.getNode();
}

From source file:de.betterform.xml.xforms.model.submission.Submission.java

private void submitReplaceEmbedXForms(Map response) throws XFormsException {
    // check for targetid
    String targetid = getXFormsAttribute(TARGETID_ATTRIBUTE);
    String resource = getResource();
    Map eventInfo = new HashMap();
    String error = null;//from www . j ava 2  s . c o  m
    if (targetid == null) {
        error = "targetId";
    } else if (resource == null) {
        error = "resource";
    }

    if (error != null && error.length() > 0) {
        eventInfo.put(XFormsConstants.ERROR_TYPE, "no " + error + "defined for submission resource");
        this.container.dispatch(this.target, XFormsEventNames.SUBMIT_ERROR, eventInfo);
        return;
    }

    Document result = getResponseAsDocument(response);
    Node embedElement = result.getDocumentElement();

    if (resource.indexOf("#") != -1) {
        // detected a fragment so extract that from our result Document

        String fragmentid = resource.substring(resource.indexOf("#") + 1);
        if (fragmentid.indexOf("?") != -1) {
            fragmentid = fragmentid.substring(0, fragmentid.indexOf("?"));
        }
        embedElement = DOMUtil.getById(result, fragmentid);
    }

    Element embeddedNode = null;
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("get target element for id: " + targetid);
    }
    Element targetElem = this.container.getElementById(targetid);
    DOMResult domResult = new DOMResult();
    //Test if targetElem exist.
    if (targetElem != null) {
        // destroy existing embedded form within targetNode
        if (targetElem.hasChildNodes()) {
            // destroyembeddedModels(targetElem);
            Initializer.disposeUIElements(targetElem);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("destroyed any existing ui elements for target elem");
        }

        // import referenced embedded form into host document
        embeddedNode = (Element) this.container.getDocument().importNode(embedElement, true);

        //import namespaces
        NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(),
                (Element) embeddedNode);

        // keep original targetElem id within hostdoc
        embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id"));
        //copy all Attributes that might have been on original mountPoint to embedded node
        DOMUtil.copyAttributes(targetElem, embeddedNode, null);
        targetElem.getParentNode().replaceChild(embeddedNode, targetElem);
        //create model for it
        Initializer.initializeUIElements(model, embeddedNode, null, null);

        try {
            CachingTransformerService transformerService = new CachingTransformerService(
                    new ClasspathResourceResolver("unused"));
            // TODO: MUST BE GENERIFIED USING USERAGENT MECHANISM
            //TODO: check exploded mode!!!
            String path = getClass().getResource("/META-INF/resources/xslt/xhtml.xsl").getPath();

            //String xslFilePath = "file:" + path;
            transformerService.getTransformer(new URI(path));
            XSLTGenerator generator = new XSLTGenerator();
            generator.setTransformerService(transformerService);
            generator.setStylesheetURI(new URI(path));
            generator.setInput(embeddedNode);
            generator.setOutput(domResult);
            generator.generate();
        } catch (TransformerException e) {
            throw new XFormsException(
                    "Transformation error while executing 'Submission.submitReplaceEmbedXForms'", e);
        } catch (URISyntaxException e) {
            throw new XFormsException(
                    "Malformed URI throwed URISyntaxException in 'Submission.submitReplaceEmbedXForms'", e);
        }
    }

    // Map eventInfo = constructEventInfo(response);
    OutputStream outputStream = new ByteArrayOutputStream();
    try {
        DOMUtil.prettyPrintDOM(domResult.getNode(), outputStream);
    } catch (TransformerException e) {
        throw new XFormsException(e);
    }

    eventInfo.put(EMBEDNODE, outputStream.toString());
    eventInfo.put("embedTarget", targetid);
    eventInfo.put("embedXForms", true);

    // dispatch xforms-submit-done
    this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, eventInfo);

}

From source file:nl.nn.adapterframework.parameters.Parameter.java

private Object transform(Source xmlSource, ParameterResolutionContext prc)
        throws ParameterException, TransformerException, IOException {
    TransformerPool pool = getTransformerPool();
    if (TYPE_NODE.equals(getType()) || TYPE_DOMDOC.equals(getType())) {

        DOMResult transformResult = new DOMResult();
        pool.transform(xmlSource, transformResult, prc.getValueMap(paramList));
        Node result = transformResult.getNode();
        if (result != null && TYPE_NODE.equals(getType())) {
            result = result.getFirstChild();
        }// w  w w  .  j  a v a 2 s  .  co  m
        if (log.isDebugEnabled()) {
            if (result != null)
                log.debug("Returning Node result [" + result.getClass().getName() + "][" + result + "]: "
                        + ToStringBuilder.reflectionToString(result));
        }
        return result;

    } else {
        return pool.transform(xmlSource, prc.getValueMap(paramList));
    }
}

From source file:org.apache.bsf.engines.xslt.XSLTEngine.java

/**
 * Evaluate an expression. In this case, an expression is assumed
 * to be a stylesheet of the template style (see the XSLT spec).
 *///from  ww  w.  ja v  a2  s . c o m
public Object eval(String source, int lineNo, int columnNo, Object oscript) throws BSFException {
    // get the style base URI (the place from where Xerces XSLT will
    // look for imported/included files and referenced docs): if a
    // bean named "xslt:styleBaseURI" is registered, then cvt it
    // to a string and use that. Otherwise use ".", which means the
    // base is the directory where the process is running from
    Object sbObj = mgr.lookupBean("xslt:styleBaseURI");
    String styleBaseURI = (sbObj == null) ? "." : sbObj.toString();

    // Locate the stylesheet.
    StreamSource styleSource;

    styleSource = new StreamSource(new StringReader(oscript.toString()));
    styleSource.setSystemId(styleBaseURI);

    try {
        transformer = tFactory.newTransformer(styleSource);
    } catch (Exception e) {
        logger.error("Exception from Xerces XSLT:", e);
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "Exception from Xerces XSLT: " + e, e);
    }

    // get the src to work on: if a bean named "xslt:src" is registered
    // and its a Node, then use it as the source. If its not a Node, then
    // if its a URL parse it, if not treat it as a file and make a URL and
    // parse it and go. If no xslt:src is found, use an empty document
    // (stylesheet is treated as a literal result element stylesheet)
    Object srcObj = mgr.lookupBean("xslt:src");
    Object xis = null;
    if (srcObj != null) {
        if (srcObj instanceof Node) {
            xis = new DOMSource((Node) srcObj);
        } else {
            try {
                String mesg = "as anything";
                if (srcObj instanceof Reader) {
                    xis = new StreamSource((Reader) srcObj);
                    mesg = "as a Reader";
                } else if (srcObj instanceof File) {
                    xis = new StreamSource((File) srcObj);
                    mesg = "as a file";
                } else {
                    String srcObjstr = srcObj.toString();
                    xis = new StreamSource(new StringReader(srcObjstr));
                    if (srcObj instanceof URL) {
                        mesg = "as a URL";
                    } else {
                        ((StreamSource) xis).setPublicId(srcObjstr);
                        mesg = "as an XML string";
                    }
                }

                if (xis == null) {
                    throw new Exception("Unable to get input from '" + srcObj + "' " + mesg);
                }
            } catch (Exception e) {
                throw new BSFException(BSFException.REASON_EXECUTION_ERROR,
                        "BSF:XSLTEngine: unable to get " + "input from '" + srcObj + "' as XML", e);
            }
        }
    } else {
        // create an empty document - real src must come into the 
        // stylesheet using "doc(...)" [see XSLT spec] or the stylesheet
        // must be of literal result element type
        xis = new StreamSource();
    }

    // set all declared beans as parameters.
    for (int i = 0; i < declaredBeans.size(); i++) {
        BSFDeclaredBean b = (BSFDeclaredBean) declaredBeans.elementAt(i);
        transformer.setParameter(b.name, new XObject(b.bean));
    }

    // declare a "bsf" parameter which is the BSF handle so that 
    // the script can do BSF stuff if it wants to
    transformer.setParameter("bsf", new XObject(new BSFFunctions(mgr, this)));

    // do it
    try {
        DOMResult result = new DOMResult();
        transformer.transform((StreamSource) xis, result);
        return new XSLTResultNode(result.getNode());
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception while eval'ing XSLT script" + e,
                e);
    }
}