Java 类org.jdom2.transform.JDOMResult 实例源码

项目:mycore    文件:ItemTest.java   
@Test
public void toXML() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(MCRNavigationItem.class);
    Marshaller m = jc.createMarshaller();
    JDOMResult JDOMResult = new JDOMResult();
    m.marshal(this.item, JDOMResult);
    Element itemElement = JDOMResult.getDocument().getRootElement();

    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(itemElement, System.out);

    assertEquals("template_mysample", itemElement.getAttributeValue("template"));
    assertEquals("bold", itemElement.getAttributeValue("style"));
    assertEquals("_self", itemElement.getAttributeValue("target"));
    assertEquals("intern", itemElement.getAttributeValue("type"));
    assertEquals("true", itemElement.getAttributeValue("constrainPopUp"));
    assertEquals("false", itemElement.getAttributeValue("replaceMenu"));
    assertEquals("item.test.key", itemElement.getAttributeValue("i18nKey"));

    Element label1 = itemElement.getChildren().get(0);
    Element label2 = itemElement.getChildren().get(1);

    assertEquals("Deutschland", label1.getValue());
    assertEquals("England", label2.getValue());
}
项目:mycore    文件:NavigationTest.java   
@Test
public void toXML() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class);
    Marshaller m = jc.createMarshaller();
    JDOMResult JDOMResult = new JDOMResult();
    m.marshal(this.navigation, JDOMResult);
    Element navigationElement = JDOMResult.getDocument().getRootElement();

    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(navigationElement, System.out);

    // test attributes
    assertEquals("template_mysample", navigationElement.getAttributeValue("template"));
    assertEquals("/content", navigationElement.getAttributeValue("dir"));
    assertEquals("History Title", navigationElement.getAttributeValue("historyTitle"));
    assertEquals("/content/below/index.xml", navigationElement.getAttributeValue("hrefStartingPage"));
    assertEquals("Main Title", navigationElement.getAttributeValue("mainTitle"));
    // test children
    assertEquals(2, navigationElement.getChildren("menu").size());
    assertEquals(1, navigationElement.getChildren("insert").size());
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@Test
public void singleTransform()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/oneObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    //        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //        xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML);
    assertEquals(1, mycoreojectTags.size());

    List<Element> userFieldTags = XPathFactory.instance()
        .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML);
    assertEquals(1, userFieldTags.size());
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@Test
public void multiTransform()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/multiplObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    //        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //        xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML);
    assertEquals(3, mycoreojectTags.size());

    List<Element> userFieldTags = XPathFactory.instance()
        .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML);
    assertEquals(3, userFieldTags.size());
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@Test
public void derivates()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/xml/derivateObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    //        JDOMResult jdomResult = xslTransformation(testXMLAsStream, "/" + getClass().getSimpleName() + "/xsl/mcr2solrOld.xsl");
    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycorederivate", Filters.element()).evaluate(resultXML);
    assertEquals(1, mycoreojectTags.size());
}
项目:mycore    文件:MCRJAXBContent.java   
@Override
public Document asXML() throws JDOMException, IOException, SAXParseException {
    JDOMResult result = new JDOMResult();
    try {
        Marshaller marshaller = getMarshaller();
        marshaller.marshal(jaxbObject, result);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
    return result.getDocument();
}
项目:mycore    文件:MCRXSL2XMLTransformer.java   
@Override
protected MCRContent getTransformedContent(MCRContent source, XMLReader reader,
    TransformerHandler transformerHandler) throws IOException, SAXException {
    JDOMResult result = new JDOMResult();
    transformerHandler.setResult(result);
    // Parse the source XML, and send the parse events to the
    // TransformerHandler.
    reader.parse(source.getInputSource());
    Document resultDoc = getDocument(result);
    if (resultDoc == null) {
        throw new MCRConfigurationException("Stylesheets " + Arrays.asList(templateSources)
            + " does not return any content for " + source.getSystemId());
    }
    return new MCRJDOMContent(resultDoc);
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
private JDOMResult xslTransformation(InputStream testXMLAsStream, String styleSheetPath)
    throws TransformerFactoryConfigurationError, TransformerException {
    InputStream stylesheetAsStream = getClass().getResourceAsStream(styleSheetPath);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    URIResolver mockIncludeResolver = new MockURIResolver();
    transformerFactory.setURIResolver(mockIncludeResolver);
    Templates templates = transformerFactory.newTemplates(new StreamSource(stylesheetAsStream));
    Transformer transformer = templates.newTransformer();
    URIResolver resolver = new MockResolver();
    transformer.setURIResolver(resolver);
    JDOMResult jdomResult = new JDOMResult();
    transformer.transform(new StreamSource(testXMLAsStream), jdomResult);
    return jdomResult;
}
项目:easyxml    文件:JDom2Reader.java   
@Override
public TransformResult<Element> transform(TransformContext<Element, R> transformContext) {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;
    try {
        t = tf.newTransformer();
        JDOMResult result = new JDOMResult();
        t.transform(new StAXSource(transformContext.getStreamReader()), result);
        Document document = result.getDocument();
        return new JDom2TransformerResult(document.getRootElement());
    } catch (TransformerException e) {
        throw new IllegalStateException(e);
    }
}
项目:spring-saml-example-war    文件:HelloTest.java   
@Test
public void test() throws Exception {

    WebServiceTemplate template = new WebServiceTemplate();

    SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory();
    messageFactory.setSoapVersion(SoapVersion.SOAP_12);
    messageFactory.afterPropertiesSet();
    template.setMessageFactory(messageFactory);

    CryptoFactoryBean cryptoFactory = new CryptoFactoryBean();
    cryptoFactory.setKeyStoreLocation(new ClassPathResource("keystore.jks"));
    cryptoFactory.setKeyStorePassword("password");
    cryptoFactory.afterPropertiesSet();
    Crypto crypto = cryptoFactory.getObject();

    SAML2CallbackHandler samlCallbackHandler = new SAML2CallbackHandler(crypto, "selfsigned");

    SAMLIssuerImpl issuer = new SAMLIssuerImpl();
    issuer.setIssuerCrypto(crypto);
    issuer.setIssuerKeyName("selfsigned");
    issuer.setIssuerKeyPassword("password");
    issuer.setIssuerName("selfsigned");
    issuer.setSendKeyValue(false);
    issuer.setSignAssertion(true);
    issuer.setCallbackHandler(samlCallbackHandler);

    Wss4jSecurityInterceptor securityInterceptor = new Wss4jSecurityInterceptor();
    securityInterceptor.setSecurementActions("Timestamp SAMLTokenSigned");
    securityInterceptor.setSecurementSignatureCrypto(crypto);
    securityInterceptor.setSecurementUsername("selfsigned");
    securityInterceptor.setSecurementPassword("password");
    securityInterceptor.setSamlIssuer(issuer);
    securityInterceptor.afterPropertiesSet();

    template.setInterceptors(new ClientInterceptor[] {securityInterceptor});
    template.afterPropertiesSet();

    Element hello = new Element("Hello", "urn:jaminh:example");
    template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult());
    template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult());
    template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult());

}
项目:mycore    文件:MCRObjectCommands.java   
private static void xslt(String objectId, String xslFilePath, boolean force) throws IOException, JDOMException, SAXException,
        URISyntaxException, TransformerException, MCRPersistenceException, MCRAccessException {
    File xslFile = new File(xslFilePath);
    URL xslURL;
    if (!xslFile.exists()) {
        try {
            xslURL = new URL(xslFilePath);
        } catch (MalformedURLException e) {
            LOGGER.error("XSL parameter is not a file or URL: {}", xslFilePath);
            return;
        }
    } else {
        xslURL = xslFile.toURI().toURL();
    }
    MCRObjectID mcrId = MCRObjectID.getInstance(objectId);
    Document document = MCRXMLMetadataManager.instance().retrieveXML(mcrId);
    // do XSL transform
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setErrorListener(MCRErrorListener.getInstance());
    transformerFactory.setURIResolver(MCRURIResolver.instance());
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setEntityResolver(MCREntityResolver.instance());
    SAXSource styleSource = new SAXSource(xmlReader, new InputSource(xslURL.toURI().toString()));
    Transformer transformer = transformerFactory.newTransformer(styleSource);
    for (Entry<String, String> property : MCRConfiguration.instance().getPropertiesMap().entrySet()) {
        transformer.setParameter(property.getKey(), property.getValue());
    }
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    JDOMResult result = new JDOMResult();
    transformer.transform(new JDOMSource(document), result);
    Document resultDocument = Objects.requireNonNull(result.getDocument(), "Could not get transformation result");

    String originalName = document.getRootElement().getName();
    String resultName = resultDocument.getRootElement().getName();
    if (!force && !originalName.equals(resultName)) {
        LOGGER.error("{}: root name '{}' does not match result name '{}'.", objectId, originalName, resultName);
        return;
    }

    // update on diff
    if (MCRXMLHelper.deepEqual(document, resultDocument)) {
        return;
    }
    if(resultName.equals(MCRObject.ROOT_NAME)) {
        MCRMetadataManager.update(new MCRObject(resultDocument));
    } else if(resultName.equals(MCRDerivate.ROOT_NAME)) {
        MCRMetadataManager.update(new MCRDerivate(resultDocument));
    } else {
        LOGGER.error("Unable to transform '{}' because unknown result root name '{}'.", objectId, resultName);
    }
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
private JDOMResult xslTransformation(InputStream testXMLAsStream)
    throws TransformerFactoryConfigurationError, TransformerException {
    return xslTransformation(testXMLAsStream, "/xsl/mycoreobject-solr.xsl");
}
项目:wot_gateways    文件:XMLGenerator.java   
/**
 * Do the xsl transformation
 * 
 * @param p_KNXProjectPath
 *            The path to the unzipped project
 * @param p_TransformFile
 *            The stream to the xsl file
 * @param p_OutputFilePath
 *            The path where the xml file has to be written
 * @throws Exception
 */
private static void generateXML(String p_KNXProjectPath,
        InputStream p_TransformFile, String p_OutputFilePath) throws Exception {
    // Find the P-**** directory
    File l_path = new File(p_KNXProjectPath);
    File[] l_dirs = l_path.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            if (pathname.isDirectory()
                    && pathname.getName().startsWith("P-"))
                return true;
            return false;
        }
    });

    if (l_dirs.length == 0)
        throw new Exception("Config file 0.xml not found");

    JDOMResult l_documentResult = new JDOMResult();
    Document l_document = null;
    long first = System.currentTimeMillis();
    // Copy the xsl file into the KNX project directory
    copyfile(p_TransformFile, p_KNXProjectPath + "/KNXTransformer.xsl");

    // Load the xsl file to create a transformer
    TransformerFactory l_factory = TransformerFactory.newInstance();
    Transformer l_transformer = l_factory.newTransformer(new StreamSource(
            p_KNXProjectPath + "/KNXTransformer.xsl"));
    long second = System.currentTimeMillis();

    logger.debug("Load xsl " + (second - first));

    // Load the source xml document
    SAXBuilder l_sax = new SAXBuilder();
    Document l_input = l_sax.build(new File(l_dirs[0].getAbsolutePath()
            + "/0.xml"));
    long third = System.currentTimeMillis();

    logger.debug("Load xml " + (third - second));

    l_transformer.transform(new JDOMSource(l_input), l_documentResult);
    long fourth = System.currentTimeMillis();

    logger.debug("Transform xsl " + (fourth - third));

    // Write the result into the destination file
    l_document = l_documentResult.getDocument();
    XMLOutputter l_outputter = new XMLOutputter(Format.getPrettyFormat());
    l_outputter.output(l_document, new FileOutputStream(p_OutputFilePath));
    long fifth = System.currentTimeMillis();
    logger.debug("Write output " + (fifth - fourth));
}
项目:spring-saml-example-war    文件:HelloTest.java   
@Test
public void test() throws Exception {

    WebServiceTemplate template = new WebServiceTemplate();

    SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory();
    messageFactory.setSoapVersion(SoapVersion.SOAP_12);
    messageFactory.afterPropertiesSet();
    template.setMessageFactory(messageFactory);

    CryptoFactoryBean cryptoFactory = new CryptoFactoryBean();
    cryptoFactory.setKeyStoreLocation(new ClassPathResource("keystore.jks"));
    cryptoFactory.setKeyStorePassword("password");
    cryptoFactory.afterPropertiesSet();
    Crypto crypto = cryptoFactory.getObject();

    SAML2CallbackHandler samlCallbackHandler = new SAML2CallbackHandler(crypto, "selfsigned");

    SAMLIssuerImpl issuer = new SAMLIssuerImpl();
    issuer.setIssuerCrypto(crypto);
    issuer.setIssuerKeyName("selfsigned");
    issuer.setIssuerKeyPassword("password");
    issuer.setIssuerName("selfsigned");
    issuer.setSendKeyValue(false);
    issuer.setSignAssertion(true);
    issuer.setCallbackHandler(samlCallbackHandler);

    Wss4jSecurityInterceptor securityInterceptor = new Wss4jSecurityInterceptor();
    securityInterceptor.setSecurementActions("Timestamp SAMLTokenSigned");
    securityInterceptor.setSecurementSignatureCrypto(crypto);
    securityInterceptor.setSecurementUsername("selfsigned");
    securityInterceptor.setSecurementPassword("password");
    securityInterceptor.setSamlIssuer(issuer);
    securityInterceptor.afterPropertiesSet();

    template.setInterceptors(new ClientInterceptor[] {securityInterceptor});
    template.afterPropertiesSet();

    Element hello = new Element("Hello", "urn:jaminh:example");
    template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult());
    template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult());
    template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult());

}
项目:marmotta    文件:SPARQLBooleanHTMLWriter.java   
@Override
public void handleBoolean(boolean value) throws QueryResultHandlerException
{
    try
    {
        // Create a SPARQL/XML representation that will be transformed to HTML using a stylesheet
        ByteArrayOutputStream xmlOut = new ByteArrayOutputStream();
        QueryResultIO.writeBoolean(value, BooleanQueryResultFormat.SPARQL, xmlOut);
        byte[] queryResult = xmlOut.toByteArray();

        // get server uri
        String server_uri = CDIContext.getInstance(ConfigurationService.class).getServerUri();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

        Source input = new StreamSource(new ByteArrayInputStream(queryResult));

        Source s_stylesheet = new StreamSource(SPARQLBooleanHTMLWriter.class.getResourceAsStream("style.xsl"));
        Templates stylesheet = TransformerFactory.newInstance().newTemplates(s_stylesheet);
        Transformer transformer = stylesheet.newTransformer();
        transformer.setParameter("serverurl", server_uri);

        JDOMResult result = new JDOMResult();
        transformer.transform(input, result);
        Document output = result.getDocument();

        XMLOutputter printer = new XMLOutputter(Format.getPrettyFormat());
        printer.output(output, writer);
        writer.flush();
    }
    catch(TransformerConfigurationException e)
    {
        log.error("could not compile stylesheet for rendering SPARQL results; result display not available!");
        throw new QueryResultHandlerException("could not compile stylesheet for rendering SPARQL results; result display not available!", e);
    }
    catch(Exception ex)
    {
        throw new QueryResultHandlerException("error while transforming XML results to HTML", ex);
    }
    finally
    {
        // writer.close();
    }
}
项目:easyxml    文件:Writer.java   
public void writeAll()
    throws XMLStreamException,
    Exception {

    // Assert.notNull(documentFileResult);
    // Assert.notNull(outputFile);
    // Assert.notNull(packetDirection);

    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    TransformerFactory tf = TransformerFactory.newInstance();
    StAXStreamProcessor processor = new CustomStAXStreamProcessor(namespace);

    XMLStreamReader xsr = null;
    XMLStreamWriter writer = null;

    xsr = xif.createXMLStreamReader(inputStream, "UTF-8");

    writer = outputFactory.createXMLStreamWriter(outputStream, "UTF-8");

    ReaderToWriter readToWrite = new ReaderToWriter();
    readToWrite.setStreamWriter(writer);

    xsr.nextTag();

    Transformer t = tf.newTransformer();
    List<String> currentElementPath = new ArrayList<>();

    while (xsr.hasNext()) {
        if (xsr.isEndElement()) {
            if (currentElementPath.size() > 0)
                currentElementPath.remove(currentElementPath.size() - 1);
        }
        if (xsr.isStartElement()) {
            String localName = xsr.getLocalName();
            currentElementPath.add(localName);
            boolean handled = false;
            String joinPath = StringUtils.join(currentElementPath, "/");
            parseContext.setPath(joinPath);

            for (ItemReader<XMLStreamReader, Void> staxItemReader : staxItemReaders) {
                if(staxItemReader.shouldHandle(parseContext)) {
                    staxItemReader.read(new StaxTransformerResult(xsr).getContent());
                }
            }

            for (Jdom2ItemWriter itemWriter : this.itemWriter) {
                if (itemWriter.shouldHandle(parseContext)) {
                    JDOMResult result = new JDOMResult();
                    t.transform(new StAXSource(xsr), result);
                    if(!itemWriter.shouldRemove()) {
                        Document document = result.getDocument();
                        Element rootElement = document.getRootElement();

                        Jdom2WriterContext context = new Jdom2WriterContext(parseContext, rootElement);

                        itemWriter.handle(context);
                        processor.process(writer, Format.getPrettyFormat(), rootElement);
                    }
                    handled = true;
                    break;
                }
            }
            if (handled) {
                if (currentElementPath.size() > 0)
                    currentElementPath.remove(currentElementPath.size() - 1);
            } else {
                readToWrite.write(xsr);
            }
        } else {
            readToWrite.write(xsr);
        }
        if (xsr.hasNext()) {
            try {
                xsr.next();
            } catch (Exception e) {
                throw e;
            }
        }
    }
}
项目:mycore    文件:MCRXSLTransformation.java   
/**
 * transforms a jdom Document via XSLT.
 * 
 * @param in Document input
 * @param transformer Transformer handling the transformation process
 * @return the transformation result as jdom Document
 * @throws TransformerException if transformation fails
 */
public static Document transform(Document in, Transformer transformer) throws TransformerException {
    JDOMResult out = new JDOMResult();
    transformer.transform(new JDOMSource(in), out);
    return out.getDocument();
}