List of usage examples for javax.xml.transform OutputKeys ENCODING
String ENCODING
To view the source code for javax.xml.transform OutputKeys ENCODING.
Click Source Link
From source file:com.esri.geoportal.commons.csw.client.impl.Client.java
@Override public String readMetadata(String id) throws Exception { LOG.debug(String.format("Executing readMetadata(id=%s)", id)); loadCapabilities();/*from www. j a v a 2 s .c o m*/ String getRecordByIdUrl = createGetMetadataByIdUrl(capabilites.get_getRecordByIDGetURL(), URLEncoder.encode(id, "UTF-8")); HttpGet getMethod = new HttpGet(getRecordByIdUrl); getMethod.setConfig(DEFAULT_REQUEST_CONFIG); try (CloseableHttpResponse httpResponse = httpClient.execute(getMethod); InputStream responseStream = httpResponse.getEntity().getContent();) { if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); } String response = IOUtils.toString(responseStream, "UTF-8"); if (CONFIG_FOLDER_PATH.equals(profile.getMetadataxslt())) { return response; } // create transformer Templates template = TemplatesManager.getInstance().getTemplate(profile.getMetadataxslt()); Transformer transformer = template.newTransformer(); try (ByteArrayInputStream contentStream = new ByteArrayInputStream(response.getBytes("UTF-8"));) { // perform transformation StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(contentStream), new StreamResult(writer)); String intermediateResult = writer.toString(); // select url to get meta data DcList lstDctReferences = new DcList(intermediateResult); String xmlUrl = lstDctReferences.stream() .filter(v -> v.getValue().toLowerCase().endsWith(".xml") || v.getScheme().equals(SCHEME_METADATA_DOCUMENT)) .map(v -> v.getValue()).findFirst().orElse(""); // use URL to get meta data if (!xmlUrl.isEmpty()) { HttpGet getRequest = new HttpGet(xmlUrl); try (CloseableHttpResponse httpResp = httpClient.execute(getRequest); InputStream metadataStream = httpResp.getEntity().getContent();) { return IOUtils.toString(metadataStream, "UTF-8"); } } if (!intermediateResult.isEmpty()) { try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayInputStream intermediateStream = new ByteArrayInputStream( intermediateResult.getBytes("UTF-8")); StringWriter intermediateBuffer = new StringWriter(); tr.transform(new StreamSource(intermediateStream), new StreamResult(intermediateBuffer)); return intermediateBuffer.toString(); } catch (Exception ex) { return makeResourceFromCswResponse(response, id); } } return response; } } }
From source file:info.novatec.testit.livingdoc.report.XmlReport.java
@Override public void printTo(Writer out) throws IOException { try {//from w ww .jav a2s .c o m Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(dom), new StreamResult(out)); } catch (TransformerException ex) { LOG.error(LOG_ERROR, ex); throw new IOException(ex.getMessage()); } }
From source file:eidassaml.starterkit.EidasRequest.java
public byte[] generate(Map<EidasPersonAttributes, Boolean> _requestedAttributes) throws IOException, XMLParserException, UnmarshallingException, CertificateEncodingException, MarshallingException, SignatureException, TransformerFactoryConfigurationError, TransformerException { byte[] returnvalue = null; StringBuilder attributesBuilder = new StringBuilder(); for (Map.Entry<EidasPersonAttributes, Boolean> entry : _requestedAttributes.entrySet()) { attributesBuilder.append(attributeTemplate.replace("$NAME", entry.getKey().getName()).replace("$ISREQ", entry.getValue().toString())); }/*from www . java 2 s. c o m*/ String template = TemplateLoader.GetTemplateByName("auth"); template = template.replace("$ForceAuthn", Boolean.toString(this.forceAuthn)); template = template.replace("$IsPassive", Boolean.toString(this.isPassive)); template = template.replace("$Destination", destination); template = template.replace("$Id", id); template = template.replace("$IssuerInstand", issueInstant); template = template.replace("$ProviderName", providerName); template = template.replace("$Issuer", issuer); template = template.replace("$requestAttributes", attributesBuilder.toString()); template = template.replace("$NameIDPolicy", nameIdPolicy.NAME); template = template.replace("$AuthClassRef", authClassRef.NAME); if (null != selectorType) { template = template.replace("$SPType", "<eidas:SPType>" + selectorType.NAME + "</eidas:SPType>"); } else { template = template.replace("$SPType", ""); } BasicParserPool ppMgr = new BasicParserPool(); ppMgr.setNamespaceAware(true); List<Signature> sigs = new ArrayList<Signature>(); try (InputStream is = new ByteArrayInputStream(template.getBytes(Constants.UTF8_CHARSET))) { Document inCommonMDDoc = ppMgr.parse(is); Element metadataRoot = inCommonMDDoc.getDocumentElement(); UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot); request = (AuthnRequest) unmarshaller.unmarshall(metadataRoot); XMLSignatureHandler.addSignature(request, signer.getSigKey(), signer.getSigCert(), signer.getSigType(), signer.getSigDigestAlg()); sigs.add(request.getSignature()); AuthnRequestMarshaller arm = new AuthnRequestMarshaller(); Element all = arm.marshall(request); if (sigs.size() > 0) Signer.signObjects(sigs); Transformer trans = TransformerFactory.newInstance().newTransformer(); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) { trans.transform(new DOMSource(all), new StreamResult(bout)); returnvalue = bout.toByteArray(); } } return returnvalue; }
From source file:com.ibm.rpe.web.service.docgen.impl.GenerateBaseTemplate.java
public final void prettyPrint(Document xml) throws Exception { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(xml), new StreamResult(out)); System.out.println(out.toString()); }
From source file:com.moviejukebox.tools.DOMHelper.java
/** * Write the Document out to a file using nice formatting * * @param doc The document to save//w ww .j a v a 2s. c o m * @param localFile The file to write to * @return */ public static boolean writeDocumentToFile(Document doc, File localFile) { try { Transformer trans = TransformerFactory.newInstance().newTransformer(); // Define the output properties trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); trans.setOutputProperty(OutputKeys.INDENT, YES); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); doc.setXmlStandalone(true); trans.transform(new DOMSource(doc), new StreamResult(localFile)); return true; } catch (IllegalArgumentException | DOMException | TransformerException error) { LOG.error("Error writing the document to {}", localFile); LOG.error("Message: {}", error.getMessage()); return false; } }
From source file:com.alfaariss.oa.util.configuration.handler.jdbc.JDBCConfigurationHandler.java
/** * Saves the database configuration using the update query. * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document) *//*from w w w. j av a 2 s .c o m*/ public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException { Connection oConnection = null; OutputStream os = null; PreparedStatement ps = null; try { os = new ByteArrayOutputStream(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(os)); //Save to DB oConnection = _oDataSource.getConnection(); ps = oConnection.prepareStatement(_sUpdateQuery); ps.setString(1, os.toString()); ps.setString(2, _sConfigId); ps.executeUpdate(); } catch (SQLException e) { _logger.error("Database error while writing configuration, SQL eror", e); throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE); } catch (TransformerException e) { _logger.error("Error while transforming document", e); throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE); } catch (Exception e) { _logger.error("Internal error during during configuration save", e); throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE); } finally { try { if (os != null) os.close(); } catch (IOException e) { _logger.debug("Error closing configuration outputstream", e); } try { if (ps != null) ps.close(); } catch (SQLException e) { _logger.debug("Error closing statement", e); } try { if (oConnection != null) oConnection.close(); } catch (SQLException e) { _logger.debug("Error closing connection", e); } } }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
public static void prettyPrintDOMWithEncoding(Document doc, String defaultEncoding, Result result) { Node firstChild = doc.getFirstChild(); boolean omitXMLDeclaration = false; String encoding = defaultEncoding; // default Encoding char set if non // is found in the PI if ((firstChild.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE) && (firstChild.getNodeName().equals("xml"))) { omitXMLDeclaration = true;/* w ww . ja v a 2s . c om*/ String piValue = firstChild.getNodeValue(); // extract from PI the encoding Char Set int encodingOffset = piValue.indexOf("encoding=\""); if (encodingOffset != -1) { encoding = piValue.substring(encodingOffset + 10); // remove the last " encoding = encoding.substring(0, encoding.length() - 1); } } try { Transformer t = getNewTransformer(); t.setOutputProperty(OutputKeys.ENCODING, encoding); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, text t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no"); t.transform(new DOMSource(doc), result); } catch (Exception e) { Engine.logEngine.error("Unexpected exception while pretty print DOM", e); } }
From source file:org.alloy.metal.xml.merge.MergeContext.java
/** * Merge 2 xml document streams together into a final resulting stream. During * the merge, various merge business rules are followed based on configuration * defined for various merge points./*from w w w . ja v a2s.c om*/ * * @param stream1 * @param stream2 * @return the stream representing the merged document * @throws org.broadleafcommerce.common.extensibility.context.merge.exceptions.MergeException */ public ResourceInputStream merge(ResourceInputStream stream1, ResourceInputStream stream2) throws MergeException { try { Document doc1 = builder.parse(stream1); Document doc2 = builder.parse(stream2); List<Node> exhaustedNodes = new ArrayList<Node>(); // process any defined handlers for (MergeHandler handler : this.handlers) { if (LOG.isDebugEnabled()) { LOG.debug("Processing handler: " + handler.getXPath()); } MergePoint point = new MergePoint(handler, doc1, doc2); List<Node> list = point.merge(exhaustedNodes); exhaustedNodes.addAll(list); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer xmlTransformer = tFactory.newTransformer(); xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0"); xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString()); xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (doc1.getDoctype() != null && doc1.getDoctype().getSystemId() != null) { xmlTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc1.getDoctype().getSystemId()); } DOMSource source = new DOMSource(doc1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos)); StreamResult result = new StreamResult(writer); xmlTransformer.transform(source, result); byte[] itemArray = baos.toByteArray(); return new ResourceInputStream(new ByteArrayInputStream(itemArray), stream2.getName(), stream1.getNames()); } catch (Exception e) { throw new MergeException(e); } }
From source file:de.awtools.xml.XSLTransformer.java
/** * Liefert den Transformer./*from w w w. j a v a2s . c o m*/ * * @return Ein <code>Transformer</code> */ private final Transformer getTransformer() { if ((transe == null) || (styleModified)) { InputStream xslt = null; try { xslt = getStyle(); transe = TransformerUtils.getTransformer(xslt, getUriResolver()); transe.setOutputProperty(OutputKeys.ENCODING, getEncoding()); transe.setOutputProperty(OutputKeys.METHOD, getMethod()); transe.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, getOmitXmlDeclaration()); styleModified = false; } catch (IOException ex) { log.debug("IOException", ex); throw new RuntimeException(ex); } finally { IOUtils.closeQuietly(xslt); } } return transe; }