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:org.deegree.framework.util.HttpUtils.java
/** * /* w w w . j a v a 2s . c o m*/ * @param url * @param content * @param timeout * timeout in milliseconds * @param user * (can <code>null</code>) * @param password * (can <code>null</code>) * @param header * @return result of http post request * @throws HttpException * @throws IOException */ public static HttpMethod performHttpPost(String url, XMLFragment content, int timeout, String user, String password, Map<String, String> header) throws HttpException, IOException { HttpClient client = new HttpClient(); URL tmp = new URL(url); WebUtils.enableProxyUsage(client, tmp); url = tmp.toExternalForm(); client.getHttpConnectionManager().getParams().setSoTimeout(timeout); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); PostMethod pm = new PostMethod(url); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000000); Properties props = new Properties(); props.put(OutputKeys.ENCODING, "UTF-8"); content.write(bos, props); pm.setRequestEntity(new ByteArrayRequestEntity(bos.toByteArray(), "text/xml")); if (header != null) { Iterator<String> iter = header.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); if (!"content-length".equalsIgnoreCase(key)) { pm.addRequestHeader(new Header(key, header.get(key))); } } } pm.addRequestHeader(new Header("content-length", Integer.toString(bos.toByteArray().length))); bos.close(); setHTTPCredentials(pm, user, password); client.executeMethod(pm); if (LOG.getLevel() == ILogger.LOG_DEBUG) { LOG.logDebug(pm.getResponseBodyAsString()); } if (pm.getStatusCode() != 200) { throw new HttpException("status code: " + pm.getStatusCode()); } return pm; }
From source file:org.deegree.framework.xml.XMLFragment.java
/** * Writes the <code>XMLFragment</code> instance to the given <code>Writer</code> using the default system encoding * and adding CDATA-sections in for text-nodes where needed. * //w ww . j a v a 2 s .c o m * TODO: Add code for CDATA safety. * * @param writer */ public void write(Writer writer) { Properties properties = new Properties(); properties.setProperty(OutputKeys.ENCODING, CharsetUtils.getSystemCharset()); write(writer, properties); }
From source file:org.deegree.framework.xml.XMLFragment.java
/** * Writes the <code>XMLFragment</code> instance to the given <code>OutputStream</code> using the default system * encoding and adding CDATA-sections in for text-nodes where needed. * /* w w w . j av a 2 s .c o m*/ * TODO: Add code for CDATA safety. * * @param os */ public void write(OutputStream os) { Properties properties = new Properties(); properties.setProperty(OutputKeys.ENCODING, CharsetUtils.getSystemCharset()); write(os, properties); }
From source file:org.devgateway.eudevfin.reports.core.utils.ReportTemplate.java
public final String 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)); return out.toString(); }
From source file:org.eclipse.buckminster.jnlp.componentinfo.cloudsmith.ComponentInfoProvider.java
public String prepareHTML(Map<String, String> properties, IOPML opml, String destination) throws Exception { if (opml == null) return null; if (properties == null) throw new IllegalArgumentException("Properties are not set"); if (destination == null) throw new IllegalArgumentException("Target destination is not set"); m_properties = properties;// ww w .j a v a 2s .com m_opml = opml; String htmlURL = null; InputStream is = getResource(IPath.SEPARATOR + SRC_HTML_FOLDER + IPath.SEPARATOR + HTML_TEMPLATE); ByteArrayOutputStream bos = new ByteArrayOutputStream(); FileUtils.copyFile(is, bos, m_nullMonitor); String string = bos.toString(HTML_ENCODING); String basePath = m_properties.get(PROP_BASE_PATH_URL); if (basePath == null) throw new Exception("Missing required property '" + PROP_BASE_PATH_URL + '\''); string = string.replaceAll(Pattern.quote(HTML_BASEPATH_PLACEHOLDER), basePath); m_xml = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(string.getBytes(HTML_ENCODING))); fillTemplate(); File htmlDestDir = new File(destination); if (!(htmlDestDir.exists() && htmlDestDir.isDirectory())) FileUtils.createDirectory(htmlDestDir, m_nullMonitor); File imgDestDir = new File(htmlDestDir, "img"); if (!(imgDestDir.exists() && imgDestDir.isDirectory())) FileUtils.createDirectory(imgDestDir, m_nullMonitor); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(stream); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, HTML_ENCODING); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, HTML_DOCTYPE_PUBLIC); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, HTML_DOCTYPE_SYSTEM); transformer.transform(new DOMSource(m_xml), result); String htmlFileName = "distro." + m_properties.get(PROP_CSPEC_NAME) + "." + m_properties.get(PROP_CSPEC_VERSION_STRING) + ".html"; htmlFileName = htmlFileName.replaceAll("(?:/|\\\\|:|\\*|\\?|\"|<|>|\\|)", "_"); htmlURL = destination + File.separator + htmlFileName; FileUtils.copyFile(new ByteArrayInputStream(stream.toByteArray()), htmlDestDir, htmlFileName, m_nullMonitor); if (!new File(imgDestDir, IMG_FOOTER).exists()) FileUtils.copyFile(getResource(IPath.SEPARATOR + SRC_HTML_IMG_FOLDER + IPath.SEPARATOR + IMG_FOOTER), imgDestDir, IMG_FOOTER, m_nullMonitor); if (!new File(imgDestDir, IMG_FAVICON).exists()) FileUtils.copyFile(getResource(IPath.SEPARATOR + SRC_HTML_IMG_FOLDER + IPath.SEPARATOR + IMG_FAVICON), imgDestDir, IMG_FAVICON, m_nullMonitor); if (!new File(imgDestDir, IMG_RSS).exists()) FileUtils.copyFile(getResource(IPath.SEPARATOR + SRC_HTML_IMG_FOLDER + IPath.SEPARATOR + IMG_RSS), imgDestDir, IMG_RSS, m_nullMonitor); if (!new File(imgDestDir, IMG_LOGO).exists()) FileUtils.copyFile(new URL(m_properties.get(PROP_PROVIDER_LOGO_URL)).openStream(), imgDestDir, IMG_LOGO, m_nullMonitor); return htmlURL; }
From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java
/** * Resolves all <include> in a given schema and writes the * result to the given output stream. Includes that can't be resolved * are removed from the schema./*from w ww .j a v a 2 s. c o m*/ * @param in the input stream providing the schema to resolve. * @param out the output stream to write the result to. * @throws IOException if an i/o error occured. * @throws SAXException if parsing of the schema failed. * @throws ParserConfigurationException indicates a serious parser configuration error. * @throws TransformerException if transforming the schema DOM to a character stream failed. * @throws TransformerConfigurationException indicates a serious transformer configuration error. */ private void resolveIncludes(InputStream in, OutputStream out) throws IOException, SAXException, ParserConfigurationException, TransformerConfigurationException, TransformerException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document schemaDOM = dbf.newDocumentBuilder().parse(new InputSource(in)); Element schemaRoot = schemaDOM.getDocumentElement(); // iterate all <include> tags and resolve them if possible NodeList includes = schemaDOM.getElementsByTagName("xsd:include"); while (includes.getLength() > 0) { for (int i = 0; i < includes.getLength(); ++i) { Node includeNode = includes.item(i); Node includeParent = includeNode.getParentNode(); Node schemaLocation = includeNode.getAttributes().getNamedItem("schemaLocation"); if (schemaLocation != null) { // extract the pure file name from the schemaLocation and // try to find an XSD resource in all model extensions matching // the given schemaLocation attribute -> if found, replace the include tag // with the DOM of the include (without the root tag, of course!) URL includeFile = RestUtils.findSchemaResource(schemaLocation.getTextContent()); if (includeFile != null) { Document includeDOM = dbf.newDocumentBuilder() .parse(new InputSource(includeFile.openStream())); NodeList includeNodes = includeDOM.getDocumentElement().getChildNodes(); for (int j = 0; j < includeNodes.getLength(); ++j) { // import and insert the tag before <include> schemaRoot.insertBefore(schemaDOM.importNode(includeNodes.item(j), true), includeNode); } } // in any case: remove the <include> tag includeParent.removeChild(includeNode); } } // resolve includes of includes (if any) includes = schemaDOM.getElementsByTagName("xsd:include"); } // serialize the schema DOM to the given output stream Transformer xform = TransformerFactory.newInstance().newTransformer(); xform.setOutputProperty(OutputKeys.INDENT, "yes"); xform.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); xform.transform(new DOMSource(schemaDOM), new StreamResult(out)); }
From source file:org.eevolution.LMX.engine.vendor.LMXFoliosDigitalesService.java
public String parse(final Source response) throws TransformerFactoryConfigurationError, TransformerException, IOException, SOAPException { assert response != null; final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); final StringWriter writer = new StringWriter(); final StreamResult result = new StreamResult(writer); transformer.transform(response, result); //String respxml = StringEscapeUtils.unescapeXml(writer.toString()); String respxml = ""; respxml = getXMLSealed(writer.toString()); return respxml; }
From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException { if (rewriteConfig == null) { configure();/*from w w w . ja v a2s . c om*/ rewriteConfig = new RewriteConfig(this); } final long start = System.currentTimeMillis(); final HttpServletRequest request = servletRequest; final HttpServletResponse response = servletResponse; if (LOG.isTraceEnabled()) { LOG.trace(request.getRequestURI()); } final Descriptor descriptor = Descriptor.getDescriptorSingleton(); if (descriptor != null && descriptor.requestsFiltered()) { final String attr = (String) request.getAttribute("XQueryURLRewrite.forwarded"); if (attr == null) { // request = new HttpServletRequestWrapper(request, /*formEncoding*/ "utf-8" ); //logs the request if specified in the descriptor descriptor.doLogRequestInReplayLog(request); request.setAttribute("XQueryURLRewrite.forwarded", "true"); } } Subject user = defaultUser; Subject requestUser = HttpAccount.getUserFromServletRequest(request); if (requestUser != null) { user = requestUser; } else { // Secondly try basic authentication final String auth = request.getHeader("Authorization"); if (auth != null) { requestUser = authenticator.authenticate(request, response); if (requestUser != null) { user = requestUser; } } } try { configure(); //checkCache(user); final RequestWrapper modifiedRequest = new RequestWrapper(request); final URLRewrite staticRewrite = rewriteConfig.lookup(modifiedRequest); if (staticRewrite != null && !staticRewrite.isControllerForward()) { modifiedRequest.setPaths(staticRewrite.resolve(modifiedRequest), staticRewrite.getPrefix()); if (LOG.isTraceEnabled()) { LOG.trace("Forwarding to target: " + staticRewrite.getTarget()); } staticRewrite.doRewrite(modifiedRequest, response); } else { if (LOG.isTraceEnabled()) { LOG.trace("Processing request URI: " + request.getRequestURI()); } if (staticRewrite != null) { // fix the request URI staticRewrite.updateRequest(modifiedRequest); } // check if the request URI is already in the url cache ModelAndView modelView = getFromCache(request.getHeader("Host") + request.getRequestURI(), user); if (LOG.isDebugEnabled()) { LOG.debug("Checked cache for URI: " + modifiedRequest.getRequestURI() + " original: " + request.getRequestURI()); } // no: create a new model and view configuration if (modelView == null) { modelView = new ModelAndView(); // Execute the query Sequence result = Sequence.EMPTY_SEQUENCE; DBBroker broker = null; try { broker = pool.get(user); modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI()); final Properties outputProperties = new Properties(); outputProperties.setProperty(OutputKeys.INDENT, "yes"); outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8"); outputProperties.setProperty(OutputKeys.MEDIA_TYPE, MimeType.XML_TYPE.getName()); result = runQuery(broker, modifiedRequest, response, modelView, staticRewrite, outputProperties); logResult(broker, result); if (response.isCommitted()) { return; } // process the query result if (result.getItemCount() == 1) { final Item resource = result.itemAt(0); if (!Type.subTypeOf(resource.getType(), Type.NODE)) { throw new ServletException( "XQueryURLRewrite: urlrewrite query should return an element!"); } Node node = ((NodeValue) resource).getNode(); if (node.getNodeType() == Node.DOCUMENT_NODE) { node = ((Document) node).getDocumentElement(); } if (node.getNodeType() != Node.ELEMENT_NODE) { //throw new ServletException("Redirect XQuery should return an XML element!"); response(broker, response, outputProperties, result); return; } Element elem = (Element) node; if (!(Namespaces.EXIST_NS.equals(elem.getNamespaceURI()))) { response(broker, response, outputProperties, result); return; // throw new ServletException("Redirect XQuery should return an element in namespace " + Namespaces.EXIST_NS); } if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI()) && "dispatch".equals(elem.getLocalName())) { node = elem.getFirstChild(); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) { final Element action = (Element) node; if ("view".equals(action.getLocalName())) { parseViews(modifiedRequest, action, modelView); } else if ("error-handler".equals(action.getLocalName())) { parseErrorHandlers(modifiedRequest, action, modelView); } else if ("cache-control".equals(action.getLocalName())) { final String option = action.getAttribute("cache"); modelView.setUseCache("yes".equals(option)); } else { final URLRewrite urw = parseAction(modifiedRequest, action); if (urw != null) { modelView.setModel(urw); } } } node = node.getNextSibling(); } if (modelView.getModel() == null) { modelView.setModel(new PassThrough(config, elem, modifiedRequest)); } } else if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI()) && "ignore".equals(elem.getLocalName())) { modelView.setModel(new PassThrough(config, elem, modifiedRequest)); final NodeList nl = elem.getElementsByTagNameNS(Namespaces.EXIST_NS, "cache-control"); if (nl.getLength() > 0) { elem = (Element) nl.item(0); final String option = elem.getAttribute("cache"); modelView.setUseCache("yes".equals(option)); } } else { response(broker, response, outputProperties, result); return; } } else if (result.getItemCount() > 1) { response(broker, response, outputProperties, result); return; } if (modelView.useCache()) { LOG.debug("Caching request to " + request.getRequestURI()); urlCache.put(modifiedRequest.getHeader("Host") + request.getRequestURI(), modelView); } } finally { pool.release(broker); } // store the original request URI to org.exist.forward.request-uri modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI()); modifiedRequest.setAttribute(RQ_ATTR_SERVLET_PATH, request.getServletPath()); } if (LOG.isTraceEnabled()) { LOG.trace("URLRewrite took " + (System.currentTimeMillis() - start) + "ms."); } final HttpServletResponse wrappedResponse = new CachingResponseWrapper(response, modelView.hasViews() || modelView.hasErrorHandlers()); if (modelView.getModel() == null) { modelView.setModel(new PassThrough(config, modifiedRequest)); } if (staticRewrite != null) { if (modelView.getModel().doResolve()) { staticRewrite.rewriteRequest(modifiedRequest); } else { modelView.getModel().setAbsolutePath(modifiedRequest); } } modifiedRequest.allowCaching(!modelView.hasViews()); doRewrite(modelView.getModel(), modifiedRequest, wrappedResponse); int status = ((CachingResponseWrapper) wrappedResponse).getStatus(); if (status == HttpServletResponse.SC_NOT_MODIFIED) { response.flushBuffer(); } else if (status < 400) { if (modelView.hasViews()) { applyViews(modelView, modelView.views, response, modifiedRequest, wrappedResponse); } else { ((CachingResponseWrapper) wrappedResponse).flush(); } } else { // HTTP response code indicates an error if (modelView.hasErrorHandlers()) { final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData(); if (data != null) { modifiedRequest.setAttribute(RQ_ATTR_ERROR, new String(data, UTF_8)); } applyViews(modelView, modelView.errorHandlers, response, modifiedRequest, wrappedResponse); } else { flushError(response, wrappedResponse); } } } // Sequence result; // if ((result = (Sequence) request.getAttribute(RQ_ATTR_RESULT)) != null) { // writeResults(response, broker, result); // } } catch (final Throwable e) { LOG.error("Error while processing " + servletRequest.getRequestURI() + ": " + e.getMessage(), e); throw new ServletException("An error occurred while processing request to " + servletRequest.getRequestURI() + ": " + e.getMessage(), e); } }
From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java
private void response(DBBroker broker, HttpServletResponse response, Properties outputProperties, Sequence resultSequence) throws IOException { final String encoding = outputProperties.getProperty(OutputKeys.ENCODING); final ServletOutputStream sout = response.getOutputStream(); final PrintWriter output = new PrintWriter(new OutputStreamWriter(sout, encoding)); if (!response.containsHeader("Content-Type")) { String mimeType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE); if (mimeType != null) { final int semicolon = mimeType.indexOf(';'); if (semicolon != Constants.STRING_NOT_FOUND) { mimeType = mimeType.substring(0, semicolon); }//from w ww.j a v a2 s.co m response.setContentType(mimeType + "; charset=" + encoding); } } // response.addHeader( "pragma", "no-cache" ); // response.addHeader( "Cache-Control", "no-cache" ); final Serializer serializer = broker.getSerializer(); serializer.reset(); final SerializerPool serializerPool = SerializerPool.getInstance(); final SAXSerializer sax = (SAXSerializer) serializerPool.borrowObject(SAXSerializer.class); try { sax.setOutput(output, outputProperties); serializer.setProperties(outputProperties); serializer.setSAXHandlers(sax, sax); serializer.toSAX(resultSequence, 1, resultSequence.getItemCount(), false, false); } catch (final SAXException e) { throw new IOException(e); } finally { serializerPool.returnObject(sax); } output.flush(); output.close(); }
From source file:org.exist.xmldb.RemoteResourceSet.java
@Override public Resource getMembersAsResource() throws XMLDBException { final List<Object> params = new ArrayList<>(); params.add(Integer.valueOf(handle)); params.add(outputProperties);/*from w w w.j a va2 s . c om*/ try { final Path tmpfile = TemporaryFileManager.getInstance().getTemporaryFile(); try (final OutputStream os = Files.newOutputStream(tmpfile)) { Map<?, ?> table = (Map<?, ?>) xmlRpcClient.execute("retrieveAllFirstChunk", params); long offset = ((Integer) table.get("offset")).intValue(); byte[] data = (byte[]) table.get("data"); final boolean isCompressed = "yes" .equals(outputProperties.getProperty(EXistOutputKeys.COMPRESS_OUTPUT, "no")); // One for the local cached file Inflater dec = null; byte[] decResult = null; int decLength = 0; if (isCompressed) { dec = new Inflater(); decResult = new byte[65536]; dec.setInput(data); do { decLength = dec.inflate(decResult); os.write(decResult, 0, decLength); } while (decLength == decResult.length || !dec.needsInput()); } else { os.write(data); } while (offset > 0) { params.clear(); params.add(table.get("handle")); params.add(Long.toString(offset)); table = (Map<?, ?>) xmlRpcClient.execute("getNextExtendedChunk", params); offset = Long.parseLong((String) table.get("offset")); data = (byte[]) table.get("data"); // One for the local cached file if (isCompressed) { dec.setInput(data); do { decLength = dec.inflate(decResult); os.write(decResult, 0, decLength); } while (decLength == decResult.length || !dec.needsInput()); } else { os.write(data); } } if (dec != null) { dec.end(); } final RemoteXMLResource res = new RemoteXMLResource(leasableXmlRpcClient.lease(), collection, handle, 0, XmldbURI.EMPTY_URI, Optional.empty()); res.setContent(tmpfile); res.setProperties(outputProperties); return res; } catch (final XmlRpcException xre) { final byte[] data = (byte[]) xmlRpcClient.execute("retrieveAll", params); String content; try { content = new String(data, outputProperties.getProperty(OutputKeys.ENCODING, "UTF-8")); } catch (final UnsupportedEncodingException ue) { LOG.warn(ue); content = new String(data); } final RemoteXMLResource res = new RemoteXMLResource(leasableXmlRpcClient.lease(), collection, handle, 0, XmldbURI.EMPTY_URI, Optional.empty()); res.setContent(content); res.setProperties(outputProperties); return res; } catch (final IOException | DataFormatException ioe) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe); } } catch (final IOException ioe) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe); } catch (final XmlRpcException xre) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, xre.getMessage(), xre); } }