javax.xml.transform.TransformerFactoryConfigurationError Java Examples

The following examples show how to use javax.xml.transform.TransformerFactoryConfigurationError. 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: MCRIncludeHandler.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private void preloadFromURI(String uri, String sStatic)
    throws TransformerException, TransformerFactoryConfigurationError {
    if (uri.trim().isEmpty()) {
        return;
    }

    LOGGER.debug("preloading " + uri);

    Element xml;
    try {
        xml = resolve(uri.trim(), sStatic);
    } catch (Exception ex) {
        LOGGER.warn("Exception preloading " + uri, ex);
        return;
    }

    Map<String, Element> cache = chooseCacheLevel(uri, sStatic);
    handlePreloadedComponents(xml, cache);
}
 
Example #2
Source File: EvaluateXQuery.java    From nifi with Apache License 2.0 6 votes vote down vote up
void writeformattedItem(XdmItem item, ProcessContext context, OutputStream out)
        throws TransformerFactoryConfigurationError, TransformerException, IOException {

    if (item.isAtomicValue()) {
        out.write(item.getStringValue().getBytes(UTF8));
    } else { // item is an XdmNode
        XdmNode node = (XdmNode) item;
        switch (node.getNodeKind()) {
            case DOCUMENT:
            case ELEMENT:
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                final Properties props = getTransformerProperties(context);
                transformer.setOutputProperties(props);
                transformer.transform(node.asSource(), new StreamResult(out));
                break;
            default:
                out.write(node.getStringValue().getBytes(UTF8));
        }
    }
}
 
Example #3
Source File: DocumentConverter.java    From container with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a given node to a String
 *
 * @return String - String representation of the given Node
 */
private static String getString(final Node node) {
    String result = null;
    if (node != null) {
        try {
            // prepare
            final Source source = new DOMSource(node);
            final StringWriter stringWriter = new StringWriter();
            final Result streamResult = new StreamResult(stringWriter);
            final TransformerFactory factory = TransformerFactory.newInstance();
            final Transformer transformer = factory.newTransformer();
            // serialize
            transformer.transform(source, streamResult);
            result = stringWriter.getBuffer().toString();
        } catch (final TransformerFactoryConfigurationError | TransformerException e) {
            e.printStackTrace();
        }
    }
    return result;
}
 
Example #4
Source File: SvgRenderer.java    From OkapiBarcode with Apache License 2.0 6 votes vote down vote up
/**
 * Cleans / sanitizes the specified string for inclusion in XML. A bit convoluted, but we're
 * trying to do it without adding an external dependency just for this...
 *
 * @param s the string to be cleaned / sanitized
 * @return the cleaned / sanitized string
 */
protected String clean(String s) {

    // remove control characters
    s = s.replaceAll("[\u0000-\u001f]", "");

    // escape XML characters
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Text text = document.createTextNode(s);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(text);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(source, result);
        return writer.toString();
    } catch (ParserConfigurationException | TransformerException | TransformerFactoryConfigurationError e) {
        return s;
    }
}
 
Example #5
Source File: XMLBase.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
protected void storeXmlDocument ( final Document doc, final File file ) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException
{
    // create output directory

    file.getParentFile ().mkdirs ();

    // write out xml

    final TransformerFactory transformerFactory = TransformerFactory.newInstance ();

    final Transformer transformer = transformerFactory.newTransformer ();
    transformer.setOutputProperty ( OutputKeys.INDENT, "yes" ); //$NON-NLS-1$

    final DOMSource source = new DOMSource ( doc );
    final StreamResult result = new StreamResult ( file );
    transformer.transform ( source, result );
}
 
Example #6
Source File: EvaluateXQuery.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
void writeformattedItem(XdmItem item, ProcessContext context, OutputStream out)
        throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException {

    if (item.isAtomicValue()) {
        out.write(item.getStringValue().getBytes(UTF8));
    } else { // item is an XdmNode
        XdmNode node = (XdmNode) item;
        switch (node.getNodeKind()) {
            case DOCUMENT:
            case ELEMENT:
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                final Properties props = getTransformerProperties(context);
                transformer.setOutputProperties(props);
                transformer.transform(node.asSource(), new StreamResult(out));
                break;
            default:
                out.write(node.getStringValue().getBytes(UTF8));
        }
    }
}
 
Example #7
Source File: AS3ScriptExporter.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
private static String prettyFormatXML(String input) {
    int indent = 5;
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
        logger.log(Level.SEVERE, "Pretty print error", e);
        return input;
    }
}
 
Example #8
Source File: StreamSourceEntityProvider.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void writeTo(StreamSource streamSource,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException {
    StreamResult streamResult = new StreamResult(entityStream);
    try {
        TransformerFactory factory = createFeaturedTransformerFactory();
        factory.newTransformer().transform(streamSource, streamResult);
    } catch (TransformerException | TransformerFactoryConfigurationError e) {
        throw new IOException(String.format("Can't write to output stream, %s", e));
    }
}
 
Example #9
Source File: DPPParameterValueWrapper.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
public void saveToFile(final @Nonnull File file) {
  try {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    final Element element = document.createElement(MAINFILE_ELEMENT);
    document.appendChild(element);

    this.saveValueToXML(element);

    // Create transformer.
    final Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    // Write to file and transform.
    transformer.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));

  } catch (ParserConfigurationException | TransformerFactoryConfigurationError
      | FileNotFoundException | TransformerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}
 
Example #10
Source File: JaxpTransformer.java    From tutorials with MIT License 6 votes vote down vote up
public String modifyAttribute(String attribute, String oldValue, String newValue) throws XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
    // 2- Locate the node(s) with xpath
    XPath xpath = XPathFactory.newInstance()
        .newXPath();
    NodeList nodes = (NodeList) xpath.evaluate(String.format("//*[contains(@%s, '%s')]", attribute, oldValue), this.input, XPathConstants.NODESET);
    // 3- Make the change on the selected nodes
    for (int i = 0; i < nodes.getLength(); i++) {
        Element value = (Element) nodes.item(i);
        value.setAttribute(attribute, newValue);
    }
    // Stream api syntax
    // IntStream
    // .range(0, nodes.getLength())
    // .mapToObj(i -> (Element) nodes.item(i))
    // .forEach(value -> value.setAttribute(attribute, newValue));
    // 4- Save the result to a new XML doc
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer xformer = factory.newTransformer();
    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    Writer output = new StringWriter();
    xformer.transform(new DOMSource(this.input), new StreamResult(output));
    return output.toString();
}
 
Example #11
Source File: XsltView.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Instantiate a new TransformerFactory for this view.
 * <p>The default implementation simply calls
 * {@link javax.xml.transform.TransformerFactory#newInstance()}.
 * If a {@link #setTransformerFactoryClass "transformerFactoryClass"}
 * has been specified explicitly, the default constructor of the
 * specified class will be called instead.
 * <p>Can be overridden in subclasses.
 * @param transformerFactoryClass the specified factory class (if any)
 * @return the new TransactionFactory instance
 * @see #setTransformerFactoryClass
 * @see #getTransformerFactory()
 */
protected TransformerFactory newTransformerFactory(
		@Nullable Class<? extends TransformerFactory> transformerFactoryClass) {

	if (transformerFactoryClass != null) {
		try {
			return ReflectionUtils.accessibleConstructor(transformerFactoryClass).newInstance();
		}
		catch (Exception ex) {
			throw new TransformerFactoryConfigurationError(ex, "Could not instantiate TransformerFactory");
		}
	}
	else {
		return TransformerFactory.newInstance();
	}
}
 
Example #12
Source File: XFLConverter.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
private static String prettyFormatXML(String input) {
    int indent = 5;
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
        logger.log(Level.SEVERE, "Pretty print error", e);
        return input;
    }
}
 
Example #13
Source File: Dom4jProcessorUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, TransformerException, URISyntaxException, DocumentException, SAXException {
    String path = getClass().getResource("/xml/attribute.xml")
        .toString();
    Dom4jTransformer transformer = new Dom4jTransformer(path);
    String attribute = "customer";
    String oldValue = "true";
    String newValue = "false";
    String expectedXml = new String(Files.readAllBytes((Paths.get(getClass().getResource("/xml/attribute_expected.xml")
        .toURI()))));

    String result = transformer
      .modifyAttribute(attribute, oldValue, newValue)
      .replaceAll("(?m)^[ \t]*\r?\n", "");//Delete extra spaces added by Java 11

    assertThat(result).and(expectedXml)
        .areSimilar();
}
 
Example #14
Source File: PolygonSimplificationUtil.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
public static void simplifyPointsOfTextLines(String pageXmlIn, String pageXmlOut, boolean doIndent) throws XPathFactoryConfigurationException, ParserConfigurationException, MalformedURLException, IllegalArgumentException, SAXException, IOException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
		PageXmlFileProcessor fp = new PageXmlFileProcessor(pageXmlIn);
		Document doc = fp.getDocument();
		NodeList nl = fp.getTextLineCoordsPoints(doc);
		
		logger.debug("got "+nl.getLength()+" lines");
		for (int i=0; i<nl.getLength(); ++i) {
			Node n = nl.item(i);
//			Node pts = n.getAttributes().getNamedItem("points");
//			String oldPoints = pts.getNodeValue();
			String oldPoints = n.getNodeValue();
			logger.trace("old points = "+oldPoints);
			String simplified = simplifyPointsStr(oldPoints, RamerDouglasPeuckerFilter.DEFAULT_PERC_OF_POLYGON_LENGTH);
			logger.trace("simplified = "+simplified);
			n.setNodeValue(simplified);
		}
		
		if (!StringUtils.isEmpty(pageXmlOut)) {
			logger.debug("writing PAGE-XML to: "+pageXmlOut+", doIndent: "+doIndent);
			fp.writeToFile(doc, new File(pageXmlOut), doIndent);	
		}
	}
 
Example #15
Source File: TeiidServer.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
private static String prettyFormat(String xml) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        StreamResult result = new StreamResult(new StringWriter());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        DOMSource source = new DOMSource(db.parse(is));
        transformer.transform(source, result);
        return result.getWriter().toString();
    } catch (IllegalArgumentException | TransformerFactoryConfigurationError | ParserConfigurationException
            | SAXException | IOException | TransformerException e) {
        return xml;
    }
}
 
Example #16
Source File: SecurityUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Instantiate a new TransformerFactory.
 * 
 * @return
 * @throws Exception
 */
public static TransformerFactory newTransformerFactory( ) throws Exception
{
	return AccessController.doPrivileged( new PrivilegedExceptionAction<TransformerFactory>( ) {

		public TransformerFactory run( ) throws Exception
		{
			try
			{
				return TransformerFactory.newInstance( );
			}
			catch ( TransformerFactoryConfigurationError error )
			{
				throw error.getException( );
			}
		}
	} );
}
 
Example #17
Source File: JsXMLHttpRequest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private byte[] domToUtf8(JsSimpleDomNode xml) {
    Node node = xml.getWrappedNode();
    // entire document.
    // if that's an issue, we could code something more complex.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(baos);
    DOMSource source = new DOMSource(node);
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        transformerFactory.newTransformer().transform(source, result);
    } catch (TransformerException | TransformerFactoryConfigurationError e) {
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}
 
Example #18
Source File: SAXSourceEntityProvider.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void writeTo(SAXSource saxSource,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException {
    StreamResult streamResult = new StreamResult(entityStream);
    try {
        TransformerFactory factory = createFeaturedTransformerFactory();
        factory.newTransformer().transform(saxSource, streamResult);
    } catch (TransformerException | TransformerFactoryConfigurationError e) {
        throw new IOException(String.format("Can't write to output stream, %s", e));
    }
}
 
Example #19
Source File: KpiResource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@POST
@Path("/getKpiTemplate")
public String loadTemplate(@Context HttpServletRequest req)
		throws EMFUserError, EMFInternalError, JSONException, TransformerFactoryConfigurationError, TransformerException {
	ObjTemplate template;
	try {
		JSONObject request = RestUtilities.readBodyAsJSONObject(req);

		template = DAOFactory.getObjTemplateDAO().getBIObjectActiveTemplate(request.getInt("id"));
		if (template == null) {
			return new JSONObject().toString();
		}

	} catch (Exception e) {
		logger.error("Error converting JSON Template to XML...", e);
		throw new SpagoBIServiceException(this.request.getPathInfo(), "An unexpected error occured while executing service", e);

	}
	return new JSONObject(Xml.xml2json(new String(template.getContent()))).toString();

}
 
Example #20
Source File: MCRDerivateCommands.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param style
 * @return
 * @throws TransformerFactoryConfigurationError
 */
private static Transformer getTransformer(String style) throws TransformerFactoryConfigurationError {
    String xslfile = DEFAULT_TRANSFORMER;
    if (style != null && style.trim().length() != 0) {
        xslfile = style + "-derivate.xsl";
    }
    Transformer trans = null;

    try {
        URL xslURL = MCRDerivateCommands.class.getResource("/" + xslfile);

        if (xslURL != null) {
            StreamSource source = new StreamSource(xslURL.toURI().toASCIIString());
            TransformerFactory transfakt = TransformerFactory.newInstance();
            transfakt.setURIResolver(MCRURIResolver.instance());
            trans = transfakt.newTransformer(source);
        }
    } catch (Exception e) {
        LOGGER.debug("Cannot build Transformer.", e);
    }
    return trans;
}
 
Example #21
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests saving a configuration if an invalid transformer factory is
 * specified. In this case an error is thrown by the transformer factory.
 * XMLConfiguration should not catch this error.
 */
@Test
public void testSaveWithInvalidTransformerFactory() throws ConfigurationException {
    System.setProperty(PROP_FACTORY, "an.invalid.Class");
    try
    {
        saveTestConfig();
        fail("Could save with invalid TransformerFactory!");
    }
    catch (final TransformerFactoryConfigurationError cex)
    {
        // ok
    }
    finally
    {
        System.getProperties().remove(PROP_FACTORY);
    }
}
 
Example #22
Source File: StoreQALDXML.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
public void close() throws IOException, TransformerFactoryConfigurationError, TransformerException {
	Element root = doc.createElement("dataset");
	root.setAttribute("id", dataset);
	doc.appendChild(root);
	for (Element question : questions) {
		root.appendChild(question);
	}

	Transformer transformer = TransformerFactory.newInstance().newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	DOMSource source = new DOMSource(doc);
	StreamResult file = new StreamResult(new File("answer_" + dataset + ".xml"));
	transformer.transform(source, file);

	System.out.println("\nXML DOM Created Successfully..");
}
 
Example #23
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 #24
Source File: XMLUtilities.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates an instance of the currently specified JAXP {@link TransformerFactory}, ensuring
 * that the result supports the {@link DOMSource#FEATURE} and {@link DOMResult#FEATURE}
 * features.
 */
public static TransformerFactory createJAXPTransformerFactory() {
    TransformerFactory transformerFactory = null;
    try {
        transformerFactory = TransformerFactory.newInstance();
    }
    catch (TransformerFactoryConfigurationError e) {
        throw new SnuggleRuntimeException(e);
    }
    /* Make sure we have DOM-based features */
    requireFeature(transformerFactory, DOMSource.FEATURE);
    requireFeature(transformerFactory, DOMResult.FEATURE);
    
    /* Must have been OK! */
    return transformerFactory;
}
 
Example #25
Source File: XMLTransformerFactory.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static TransformerFactory createTransformerFactory (@Nullable final ErrorListener aErrorListener,
                                                           @Nullable final URIResolver aURIResolver)
{
  try
  {
    final TransformerFactory aFactory = TransformerFactory.newInstance ();
    if (aErrorListener != null)
      aFactory.setErrorListener (aErrorListener);
    if (aURIResolver != null)
      aFactory.setURIResolver (aURIResolver);
    return aFactory;
  }
  catch (final TransformerFactoryConfigurationError ex)
  {
    throw new InitializationException ("Failed to create XML TransformerFactory", ex);
  }
}
 
Example #26
Source File: ViolationParserUtils.java    From violations-lib with Apache License 2.0 5 votes vote down vote up
private static Transformer createTranformer()
    throws TransformerFactoryConfigurationError, TransformerConfigurationException {
  final TransformerFactory factory = TransformerFactory.newInstance();
  factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
  factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
  final Transformer transformer = factory.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  return transformer;
}
 
Example #27
Source File: YT1108Test.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static String toString(final Node xml) {
    try {
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        final StreamResult result = new StreamResult(new StringWriter());
        final DOMSource source = new DOMSource(xml);
        transformer.transform(source, result);

        return result.getWriter().toString();
    } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
        throw new RuntimeException("Unable to serialize xml element " + xml, e);
    }
}
 
Example #28
Source File: ParsingServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
/**
 * Prints the document to the specified HTTP servlet response.
 * @param response response to print the document to
 */
public void printDocument( final HttpServletResponse response ) throws TransformerFactoryConfigurationError, TransformerException, IOException {
	response.setContentType( "text/xml" );
	response.setCharacterEncoding( "UTF-8" );
	setNoCache( response );
	
	final Transformer transformer = TransformerFactory.newInstance().newTransformer();
	transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
	transformer.transform( new DOMSource( document ), new StreamResult( response.getOutputStream() ) );
}
 
Example #29
Source File: DataPointProcessingQueue.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
public void saveToFile(final @Nonnull File file) {
  try {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    final Element element = document.createElement("DataPointProcessing");
    document.appendChild(element);

    // Serialize batch queue.
    this.saveToXML(element);

    // Create transformer.
    final Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    // Write to file and transform.
    transformer.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));

    logger.finest("Saved " + this.size() + " processing step(s) to " + file.getName());

  } catch (ParserConfigurationException | TransformerFactoryConfigurationError
      | FileNotFoundException | TransformerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return;
  }

}
 
Example #30
Source File: AbstractXMLTst.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void validateDocument(Document document, String xsdURL) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {
//        Element element = (Element) document.getElementsByTagName("ConfigurationChangeEvent").item(0);
//        element.setAttribute("xmlns", "http://timweb.cern.ch/schemas/tim-daq/Configuration");
        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.XML_NS_URI);
//        factory.
        URL location = new URL(xsdURL);
        // load a WXS schema, represented by a Schema instance
        Schema schema = factory.newSchema(location);
        // create a Validator instance, which can be used to validate an instance document
        Validator validator = schema.newValidator();
//        validator.setErrorHandler(new ErrorHandler() {
//
//            @Override
//            public void warning(final SAXParseException exception) throws SAXException {
//                exception.printStackTrace();
//            }
//
//            @Override
//            public void fatalError(final SAXParseException exception) throws SAXException {
//                exception.printStackTrace();
//            }
//
//            @Override
//            public void error(final SAXParseException exception) throws SAXException {
//                exception.printStackTrace();
//            }
//        });
        // validate the xml
        String xmlString = getDocumentString(document);
        validator.validate(new StreamSource(new StringReader(xmlString)));
    }