javax.xml.transform.dom.DOMSource Java Examples

The following examples show how to use javax.xml.transform.dom.DOMSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocumentResolver.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public XMLSignatureInput engineResolveURI(ResourceResolverContext context) throws ResourceResolverException {
   String id = context.attr.getNodeValue();
   if (id.startsWith("#")) {
      id = id.substring(1);
   }

   if (LOG.isDebugEnabled()) {
      try {
         LOG.debug("Selected document: " + ConnectorXmlUtils.flatten(ConnectorXmlUtils.toString((Source)(new DOMSource(this.doc)))));
      } catch (TechnicalConnectorException var5) {
         LOG.error(var5.getMessage());
      }
   }

   Node selectedElem = this.doc.getElementById(id);
   if (LOG.isDebugEnabled()) {
      LOG.debug("Try to catch an Element with ID " + id + " and Element was " + selectedElem);
   }

   this.processElement(context.attr, context.baseUri, selectedElem, id);
   XMLSignatureInput result = new XMLSignatureInput(selectedElem);
   result.setExcludeComments(true);
   result.setMIMEType("text/xml");
   result.setSourceURI(context.baseUri != null ? context.baseUri.concat(context.attr.getNodeValue()) : context.attr.getNodeValue());
   return result;
}
 
Example #2
Source File: XmlUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String asString(Node node, boolean formatted) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (formatted) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
        }
        if (!(node instanceof Document)) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // NOI18N
        }
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(node);
        transformer.transform(source, result);

        return result.getWriter().toString();
    } catch (TransformerException ex) {
        LOGGER.log(Level.INFO, null, ex);
    }
    return null;
}
 
Example #3
Source File: WadlGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String copyDOMToString(Document wadlDoc) throws Exception {
    DOMSource domSource = new DOMSource(wadlDoc);
    // temporary workaround
    StringWriter stringWriter = new StringWriter();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
    try {
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
    } catch (IllegalArgumentException ex) {
        // ignore
    }

    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, new StreamResult(stringWriter));
    return stringWriter.toString();
}
 
Example #4
Source File: AbstractDOMDocumentSerializer.java    From jettison with Apache License 2.0 6 votes vote down vote up
public void serialize(Element el) throws IOException {
	if (output == null)
		throw new IllegalStateException("OutputStream cannot be null");

	try {
		DOMSource source = new DOMSource(el);
		XMLInputFactory readerFactory = XMLInputFactory.newInstance();
		XMLStreamReader streamReader = readerFactory
				.createXMLStreamReader(source);
		XMLEventReader eventReader = readerFactory
				.createXMLEventReader(streamReader);

		XMLEventWriter eventWriter = writerFactory
				.createXMLEventWriter(output);
		eventWriter.add(eventReader);
		eventWriter.close();
	} catch (XMLStreamException ex) {
		IOException ioex = new IOException("Cannot serialize: " + el);
		ioex.initCause(ex);
		throw ioex;
	}
}
 
Example #5
Source File: LibertyServerConfigGenerator.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Write the server.xml and bootstrap.properties to the server config
 * directory
 *
 * @throws TransformerException
 * @throws IOException
 */
public void writeToServer() throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    // Replace auto-generated server.xml
    DOMSource server = new DOMSource(serverXml);
    StreamResult serverResult = new StreamResult(new File(serverPath + "/server.xml"));
    transformer.transform(server, serverResult);

    // Create configDropins/default path
    Path configDropins = Paths.get(serverPath + CONFIG_DROPINS_DIR);
    Files.createDirectories(configDropins);

    // Write variables.xml to configDropins
    DOMSource variables = new DOMSource(variablesXml);
    StreamResult variablesResult = new StreamResult(new File(serverPath + CONFIG_DROPINS_DIR + "/variables.xml"));
    transformer.transform(variables, variablesResult);

}
 
Example #6
Source File: AbstractMarshaller.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Unmarshals the given provided {@code javax.xml.transform.Source} into an object graph.
 * <p>This implementation inspects the given result, and calls {@code unmarshalDomSource},
 * {@code unmarshalSaxSource}, or {@code unmarshalStreamSource}.
 * @param source the source to marshal from
 * @return the object graph
 * @throws IOException if an I/O Exception occurs
 * @throws XmlMappingException if the given source cannot be mapped to an object
 * @throws IllegalArgumentException if {@code source} is neither a {@code DOMSource},
 * a {@code SAXSource}, nor a {@code StreamSource}
 * @see #unmarshalDomSource(javax.xml.transform.dom.DOMSource)
 * @see #unmarshalSaxSource(javax.xml.transform.sax.SAXSource)
 * @see #unmarshalStreamSource(javax.xml.transform.stream.StreamSource)
 */
@Override
public final Object unmarshal(Source source) throws IOException, XmlMappingException {
	if (source instanceof DOMSource) {
		return unmarshalDomSource((DOMSource) source);
	}
	else if (StaxUtils.isStaxSource(source)) {
		return unmarshalStaxSource(source);
	}
	else if (source instanceof SAXSource) {
		return unmarshalSaxSource((SAXSource) source);
	}
	else if (source instanceof StreamSource) {
		return unmarshalStreamSource((StreamSource) source);
	}
	else {
		throw new IllegalArgumentException("Unknown Source type: " + source.getClass());
	}
}
 
Example #7
Source File: SVGRendererImpl.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Writes the XML document to an output stream
 * 
 * @param svgDocument
 * @param outputStream
 * @throws Exception
 */
private void writeDocumentToOutputStream( Document svgDocument,
		OutputStream outputStream ) throws Exception
{
	if ( svgDocument != null && outputStream != null )
	{
		OutputStreamWriter writer = null;

		writer = SecurityUtil.newOutputStreamWriter( outputStream, "UTF-8" ); //$NON-NLS-1$

		DOMSource source = new DOMSource( svgDocument );
		StreamResult result = new StreamResult( writer );

		// need to check if we should use sun's implementation of the
		// transform factory. This is needed to work with jdk1.4 and jdk1.5
		// with tomcat
		checkForTransformFactoryImpl( );
		TransformerFactory transFactory = SecurityUtil.newTransformerFactory( );
		Transformer transformer = transFactory.newTransformer( );

		transformer.transform( source, result );
	}

}
 
Example #8
Source File: XmlParserStream.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
        final DOMSource source) {
    final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
    if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
        final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
        if (optName.isPresent()) {
            mount.setContainer(optName.get(), child);
            return;
        }

        LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
    } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
        mount.setSchemaMounts(child);
        return;
    }

    mount.addChild(child);
}
 
Example #9
Source File: SoapUtils.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
   * A method to create a SOAP message and retrieve it as byte.
   * 
   * @param version
   *            the SOAP version to be used (1.1 or 1.2).
   * @param headerBlocks
   *            the list of Header Blocks to be included in the SOAP Header .
   * @param body
   *            the XML message to be included in the SOAP BODY element.
   * @param encoding
   *            the encoding to be used for the message creation.
   * 
   * @return The created SOAP message as byte.
   * 
   * @author Simone Gianfranceschi
   */
  public static byte[] getSoapMessageAsByte(String version,
          List headerBlocks, Element body, String encoding) throws Exception {
      Document message = createSoapMessage(version, headerBlocks, body);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      TransformerFactory tf = TransformerFactory.newInstance();
        // Fortify Mod: prevent external entity injection
      tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      Transformer t = tf.newTransformer();
// End Fortify Mod
      t.setOutputProperty(OutputKeys.ENCODING, encoding);
      t.transform(new DOMSource(message), new StreamResult(baos));

      // System.out.println("SOAP MESSAGE : " + baos.toString());

      return baos.toByteArray();
  }
 
Example #10
Source File: UnmarshallerImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal0(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal0(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #11
Source File: RaftProperties.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
/**
 * Write out the non-default properties in this configuration to the given
 * {@link Writer}.
 *
 * @param out the writer to write to.
 */
public void writeXml(Writer out) throws IOException {
  Document doc = asXmlDocument();

  try {
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    // Important to not hold Configuration log while writing result, since
    // 'out' may be an HDFS stream which needs to lock this configuration
    // from another thread.
    transformer.transform(source, result);
  } catch (TransformerException te) {
    throw new IOException(te);
  }
}
 
Example #12
Source File: StandardFlowSerializer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(final Document flowConfiguration, final OutputStream os) throws FlowSerializationException {
    try {
        final DOMSource domSource = new DOMSource(flowConfiguration);
        final StreamResult streamResult = new StreamResult(new BufferedOutputStream(os));

        // configure the transformer and convert the DOM
        final TransformerFactory transformFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformFactory.newTransformer();
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // transform the document to byte stream
        transformer.transform(domSource, streamResult);

    } catch (final DOMException | TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
        throw new FlowSerializationException(e);
    }
}
 
Example #13
Source File: JaxpIssue43Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private Source[] getSchemaSources() throws Exception {
    List<Source> list = new ArrayList<Source>();
    String file = getClass().getResource("hello_literal.wsdl").getFile();
    Source source = new StreamSource(new FileInputStream(file), file);

    Transformer trans = TransformerFactory.newInstance().newTransformer();
    DOMResult result = new DOMResult();
    trans.transform(source, result);

    // Look for <xsd:schema> element in wsdl
    Element e = ((Document) result.getNode()).getDocumentElement();
    NodeList typesList = e.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "types");
    NodeList schemaList = ((Element) typesList.item(0)).getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema");
    Element elem = (Element) schemaList.item(0);
    list.add(new DOMSource(elem, file + "#schema0"));

    // trans.transform(new DOMSource(elem), new StreamResult(System.out));

    return list.toArray(new Source[list.size()]);
}
 
Example #14
Source File: XmlUtils.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
/**
 * XML Node to string
 * @param node XML node
 * @return XML node string representation
 */
public static String nodeToString(Node node)
{
    StringWriter sw = new StringWriter();
    try
    {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "no");
        /* CB - Since everything is already stored as strings in memory why shoud an encoding be required here? */
        t.setOutputProperty(OutputKeys.ENCODING, RuntimeConstants.ENCODING_DEFAULT);
        t.transform(new DOMSource(node), new StreamResult(sw));
    }
    catch (TransformerException te)
    {
        LOGGER.error("could not convert XML node to string", te);
    }
    return sw.toString();
}
 
Example #15
Source File: EndpointReferenceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceGetPortUsingEndpointReference() throws Exception {
    BusFactory.setDefaultBus(getBus());
    GreeterImpl greeter1 = new GreeterImpl();
    try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter1, (String)null)) {
        endpoint.publish("http://localhost:8080/test");

        javax.xml.ws.Service s = javax.xml.ws.Service
            .create(new QName("http://apache.org/hello_world_soap_http", "SoapPort"));

        InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
        Document doc = StaxUtils.read(is);
        DOMSource erXML = new DOMSource(doc);
        EndpointReference endpointReference = EndpointReference.readFrom(erXML);

        WebServiceFeature[] wfs = new WebServiceFeature[] {};

        Greeter greeter = s.getPort(endpointReference, Greeter.class, wfs);

        String response = greeter.greetMe("John");

        assertEquals("Hello John", response);
    }
}
 
Example #16
Source File: XmlSupport.java    From java-ocr-api with GNU Affero General Public License v3.0 6 votes vote down vote up
private static final void writeDoc(Document doc, OutputStream out)
    throws IOException
{
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            tf.setAttribute("indent-number", new Integer(2));
        } catch (IllegalArgumentException iae) {

        }
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
        t.setOutputProperty(OutputKeys.INDENT, "yes");

        t.transform(new DOMSource(doc),
                    new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
    } catch(TransformerException e) {
        throw new AssertionError(e);
    }
}
 
Example #17
Source File: CatalogSupport4.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name = "data_ValidatorA")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    StreamSource source = new StreamSource(new File(xml_val_test));

    return new Object[][]{
        // use catalog
        {true, false, true, ds, null, null, xml_catalog, null},
        {false, true, true, ds, null, null, null, xml_catalog},
        {true, false, true, ss, null, null, xml_catalog, null},
        {false, true, true, ss, null, null, null, xml_catalog},
        {true, false, true, stax, null, null, xml_catalog, xml_catalog},
        {false, true, true, stax1, null, null, xml_catalog, xml_catalog},
        {true, false, true, source, null, null, xml_catalog, null},
        {false, true, true, source, null, null, null, xml_catalog},
    };
}
 
Example #18
Source File: WSDLConverter.java    From jolie with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void parseSchemaElement( Element element )
	throws IOException {
	try {
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty( "indent", "yes" );
		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult( sw );
		DOMSource source = new DOMSource( element );
		transformer.transform( source, result );
		InputSource schemaSource = new InputSource( new StringReader( sw.toString() ) );
		schemaSource.setSystemId( definition.getDocumentBaseURI() );
		schemaParser.parse( schemaSource );
	} catch( SAXException | TransformerException e ) {
		throw new IOException( e );
	}
}
 
Example #19
Source File: CrossrefBuilderTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testCreateCrossrefXml_SkippedVolume() throws Exception {
        File targetFolder = temp.getRoot();
        CrossrefBuilder builder = new CrossrefBuilder(targetFolder);
        builder.addPeriodicalTitle("1210-8510", "titleTest", "abbrevTest", "print");
        builder.addIssue("10", "2010", "uuid");
        Document article = builder.getDocumentBuilder().parse(
                CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
        builder.addArticle(article);
        Document articles = builder.mergeArticles();
        StringWriter dump = new StringWriter();
        TransformErrorListener errors = builder.createCrossrefXml(new DOMSource(articles), new StreamResult(dump));
//        System.out.println(dump);
        assertTrue(errors.getErrors().toString(), errors.getErrors().isEmpty());

        List<String> validateErrors = builder.validateCrossref(new StreamSource(new StringReader(dump.toString())));
        assertTrue(validateErrors.toString(), validateErrors.isEmpty());
    }
 
Example #20
Source File: AbstractUnmarshallerImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal( Source source ) throws JAXBException {
    if( source == null ) {
        throw new IllegalArgumentException(
            Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
    }

    if(source instanceof SAXSource)
        return unmarshal( (SAXSource)source );
    if(source instanceof StreamSource)
        return unmarshal( streamSourceToInputSource((StreamSource)source));
    if(source instanceof DOMSource)
        return unmarshal( ((DOMSource)source).getNode() );

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #21
Source File: LogicalMessageImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public Source getPayload() {
    assert (!(payloadSrc instanceof DOMSource));
    try {
        Transformer transformer = XmlUtil.newTransformer();
        DOMResult domResult = new DOMResult();
        transformer.transform(payloadSrc, domResult);
        DOMSource dom = new DOMSource(domResult.getNode());
        lm = new DOMLogicalMessageImpl((DOMSource) dom);
        payloadSrc = null;
        return dom;
    } catch (TransformerException te) {
        throw new WebServiceException(te);
    }
}
 
Example #22
Source File: EmailStyleHelper.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public EmailContent generateEmailContent(Templates style, Document document) {
DOMResult result = new DOMResult();
       if (LOG.isDebugEnabled()) {
           LOG.debug("Input document: " + XmlJotter.jotNode(document.getDocumentElement(), true));
       }
       try {
           style.newTransformer().transform(new DOMSource(document), result);
       } catch (TransformerException te) {
           String message = "Error transforming immediate reminder DOM";
           LOG.error(message, te);
           throw new WorkflowRuntimeException(message, te);
       }

       Node node = result.getNode();

       if (LOG.isDebugEnabled()) {
           LOG.debug("Email to be sent: " + XmlJotter.jotNode(node));
       }
       XPathFactory xpf = XPathFactory.newInstance();
       XPath xpath = xpf.newXPath();
       try {
           String subject = (String) xpath.evaluate("/email/subject", node, XPathConstants.STRING);
           String body = (String) xpath.evaluate("/email/body", node, XPathConstants.STRING);
           // simple heuristic to determine whether content is HTML
           return new EmailContent(subject, body, body.matches("(?msi).*<(\\w+:)?html.*"));
       } catch (XPathExpressionException xpee) {
           throw new WorkflowRuntimeException("Error evaluating generated email content", xpee);
       }
   }
 
Example #23
Source File: CaptureOperationsModule.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Validates the given document against the given schema.
 */
private void validateDocument(Document document, Schema schema) throws SAXException, IOException {
    if (schema != null) {
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
        LOG.info("Incoming capture request was successfully validated against the EPCISDocument schema");
    } else {
        LOG.warn("Schema validator unavailable. Unable to validate EPCIS capture event against schema!");
    }
}
 
Example #24
Source File: SOAPHeaderLoggerHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean handleMessage(SOAPMessageContext ctx) {
   try {
      SOAPHeader header = ctx.getMessage().getSOAPHeader();
      if (header != null) {
         Iterator it = ctx.getMessage().getSOAPHeader().examineAllHeaderElements();

         while(it.hasNext()) {
            Object obj = it.next();
            if (obj instanceof Element) {
               Element el = (Element)obj;
               String nameValue = "{" + el.getNamespaceURI() + "}" + el.getLocalName();
               if (this.propList.contains(nameValue)) {
                  LOG.info(ConnectorXmlUtils.toString((Source)(new DOMSource(el))));
               }
            } else {
               LOG.error("Unsupported Object with name: [" + obj.getClass().getName() + "]");
            }
         }
      }
   } catch (SOAPException var7) {
      LOG.error("SOAPException: " + var7.getMessage(), var7);
   } catch (TechnicalConnectorException var8) {
      LOG.error("TechnicalConnectorException: " + var8.getMessage(), var8);
   }

   return true;
}
 
Example #25
Source File: NdkExportTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/** Tests if the exception is thrown for invalid event mets  */
private void testEvent(MdSecType digiProv, String eventIdentifierValue, String eventType, String eventDetail, String linkingObjectIdentifierValue){
    XmlData premisData = digiProv.getMdWrap().getXmlData();
    DOMSource premisSource = new DOMSource((Node) premisData.getAny().get(0));
    EventComplexType premisType = PremisUtils.unmarshal(premisSource, EventComplexType.class);
    assertEquals(eventIdentifierValue, premisType.getEventIdentifier().getEventIdentifierValue());
    assertEquals(eventType, premisType.getEventType());
    assertEquals(eventDetail, premisType.getEventDetail());
    assertEquals("ProArc_AgentID", premisType.getLinkingAgentIdentifier().get(0).getLinkingAgentIdentifierType());
    assertEquals("ProArc", premisType.getLinkingAgentIdentifier().get(0).getLinkingAgentIdentifierValue());
    assertEquals(linkingObjectIdentifierValue, premisType.getLinkingObjectIdentifier().get(0).getLinkingObjectIdentifierValue());
}
 
Example #26
Source File: Converter.java    From xml-avro with Apache License 2.0 5 votes vote down vote up
private static void saveDocument(Document doc, File file) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(doc), new StreamResult(file));
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: XmlUtils.java    From funcj with MIT License 5 votes vote down vote up
public static OutputStream write(Node node, OutputStream os, boolean pretty) throws CodecException {
    try {
        final Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        if (pretty) {
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        }

        tf.transform(new DOMSource(node), new StreamResult(os));
        return os;
    } catch (TransformerException ex) {
        throw new CodecException(ex);
    }
}
 
Example #28
Source File: DOMStreamReader.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void displayDOM(Node node, java.io.OutputStream ostream) {
    try {
        System.out.println("\n====\n");
        XmlUtil.newTransformer().transform(
            new DOMSource(node), new StreamResult(ostream));
        System.out.println("\n====\n");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #29
Source File: AbstractXMLTst.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String getDocumentString(Document document) throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    //initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(document);
    transformer.transform(source, result);

    String xmlString = result.getWriter().toString();
    return xmlString;
}
 
Example #30
Source File: SmartTransformerFactoryImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * javax.xml.transform.sax.TransformerFactory implementation.
 * Look up the value of a feature (to see if it is supported).
 * This method must be updated as the various methods and features of this
 * class are implemented.
 *
 * @param name The feature name
 * @return 'true' if feature is supported, 'false' if not
 */
public boolean getFeature(String name) {
    // All supported features should be listed here
    String[] features = {
        DOMSource.FEATURE,
        DOMResult.FEATURE,
        SAXSource.FEATURE,
        SAXResult.FEATURE,
        StreamSource.FEATURE,
        StreamResult.FEATURE
    };

    // feature name cannot be null
    if (name == null) {
        ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_GET_FEATURE_NULL_NAME);
        throw new NullPointerException(err.toString());
    }

    // Inefficient, but it really does not matter in a function like this
    for (int i = 0; i < features.length; i++) {
        if (name.equals(features[i]))
            return true;
    }

    // secure processing?
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return featureSecureProcessing;
    }

    // unknown feature
    return false;
}