Example usage for javax.xml.transform OutputKeys ENCODING

List of usage examples for javax.xml.transform OutputKeys ENCODING

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys ENCODING.

Prototype

String ENCODING

To view the source code for javax.xml.transform OutputKeys ENCODING.

Click Source Link

Document

encoding = string.

Usage

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog220.java

protected void updateKnoxTopology() throws AmbariException {
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    for (final Cluster cluster : getCheckedClusterMap(ambariManagementController.getClusters()).values()) {
        Config topology = cluster.getDesiredConfigByType(TOPOLOGY_CONFIG);
        if (topology != null) {
            String content = topology.getProperties().get(CONTENT_PROPERTY);
            if (content != null) {
                Document topologyXml = convertStringToDocument(content);
                if (topologyXml != null) {
                    Element root = topologyXml.getDocumentElement();
                    if (root != null) {
                        NodeList providerNodes = root.getElementsByTagName("provider");
                        boolean authorizationProviderExists = false;
                        try {
                            for (int i = 0; i < providerNodes.getLength(); i++) {
                                Node providerNode = providerNodes.item(i);
                                NodeList childNodes = providerNode.getChildNodes();
                                for (int k = 0; k < childNodes.getLength(); k++) {
                                    Node child = childNodes.item(k);
                                    child.normalize();
                                    String childTextContent = child.getTextContent();
                                    if (childTextContent != null
                                            && childTextContent.toLowerCase().equals("authorization")) {
                                        authorizationProviderExists = true;
                                        break;
                                    }//from www . ja va 2  s.  c om
                                }
                                if (authorizationProviderExists) {
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LOG.error(
                                    "Error occurred during check 'authorization' provider already exists in topology."
                                            + e);
                            return;
                        }
                        if (!authorizationProviderExists) {
                            NodeList nodeList = root.getElementsByTagName("gateway");
                            if (nodeList != null && nodeList.getLength() > 0) {
                                boolean rangerPluginEnabled = isConfigEnabled(cluster,
                                        AbstractUpgradeCatalog.CONFIGURATION_TYPE_RANGER_KNOX_PLUGIN_PROPERTIES,
                                        AbstractUpgradeCatalog.PROPERTY_RANGER_KNOX_PLUGIN_ENABLED);

                                Node gatewayNode = nodeList.item(0);
                                Element newProvider = topologyXml.createElement("provider");

                                Element role = topologyXml.createElement("role");
                                role.appendChild(topologyXml.createTextNode("authorization"));
                                newProvider.appendChild(role);

                                Element name = topologyXml.createElement("name");
                                if (rangerPluginEnabled) {
                                    name.appendChild(topologyXml.createTextNode("XASecurePDPKnox"));
                                } else {
                                    name.appendChild(topologyXml.createTextNode("AclsAuthz"));
                                }
                                newProvider.appendChild(name);

                                Element enabled = topologyXml.createElement("enabled");
                                enabled.appendChild(topologyXml.createTextNode("true"));
                                newProvider.appendChild(enabled);

                                gatewayNode.appendChild(newProvider);

                                DOMSource topologyDomSource = new DOMSource(root);
                                StringWriter writer = new StringWriter();
                                try {
                                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                                            "5");
                                    transformer.transform(topologyDomSource, new StreamResult(writer));
                                } catch (TransformerConfigurationException e) {
                                    e.printStackTrace();
                                    LOG.error(
                                            "Unable to create transformer instance, to convert Document(XML) to String. "
                                                    + e);
                                    return;
                                } catch (TransformerException e) {
                                    e.printStackTrace();
                                    LOG.error("Unable to transform Document(XML) to StringWriter. " + e);
                                    return;
                                }

                                content = writer.toString();
                                Map<String, String> updates = Collections.singletonMap(CONTENT_PROPERTY,
                                        content);
                                updateConfigurationPropertiesForCluster(cluster, TOPOLOGY_CONFIG, updates, true,
                                        false);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java

/**
 * Uses the context to retrieve a default encoding for the serializers.
 *//*from   w ww  . ja  v a2  s .  c om*/
public void contextualize(Context context) throws ContextException {
    String defaultEncoding = (String) context.get(Constants.CONTEXT_DEFAULT_ENCODING);
    if (defaultEncoding != null) {
        this.format.setProperty(OutputKeys.ENCODING, defaultEncoding);
    }
}

From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java

/**
 * Set the configurations for this serializer.
 *///from  w ww . j  ava 2  s .  c o  m
public void configure(Configuration conf) throws ConfigurationException {
    // configure buffer size
    //   Configuration bsc = conf.getChild("buffer-size", false);
    //   if(null != bsc)
    //    outputBufferSize = bsc.getValueAsInteger(DEFAULT_BUFFER_SIZE);

    // configure xalan
    String cdataSectionElements = conf.getChild("cdata-section-elements").getValue(null);
    String dtPublic = conf.getChild("doctype-public").getValue(null);
    String dtSystem = conf.getChild("doctype-system").getValue(null);
    String encoding = conf.getChild("encoding").getValue(null);
    String indent = conf.getChild("indent").getValue(null);
    String mediaType = conf.getChild("media-type").getValue(null);
    String method = conf.getChild("method").getValue(null);
    String omitXMLDeclaration = conf.getChild("omit-xml-declaration").getValue(null);
    String standAlone = conf.getChild("standalone").getValue(null);
    String version = conf.getChild("version").getValue(null);

    final StringBuffer buffer = new StringBuffer();

    if (cdataSectionElements != null) {
        format.put(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSectionElements);
        buffer.append(";cdata-section-elements=").append(cdataSectionElements);
    }
    if (dtPublic != null) {
        format.put(OutputKeys.DOCTYPE_PUBLIC, dtPublic);
        buffer.append(";doctype-public=").append(dtPublic);
    }
    if (dtSystem != null) {
        format.put(OutputKeys.DOCTYPE_SYSTEM, dtSystem);
        buffer.append(";doctype-system=").append(dtSystem);
    }
    if (encoding != null) {
        format.put(OutputKeys.ENCODING, encoding);
        buffer.append(";encoding=").append(encoding);
    }
    if (indent != null) {
        format.put(OutputKeys.INDENT, indent);
        buffer.append(";indent=").append(indent);
    }
    if (mediaType != null) {
        format.put(OutputKeys.MEDIA_TYPE, mediaType);
        buffer.append(";media-type=").append(mediaType);
    }
    if (method != null) {
        format.put(OutputKeys.METHOD, method);
        buffer.append(";method=").append(method);
    }
    if (omitXMLDeclaration != null) {
        format.put(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration);
        buffer.append(";omit-xml-declaration=").append(omitXMLDeclaration);
    }
    if (standAlone != null) {
        format.put(OutputKeys.STANDALONE, standAlone);
        buffer.append(";standalone=").append(standAlone);
    }
    if (version != null) {
        format.put(OutputKeys.VERSION, version);
        buffer.append(";version=").append(version);
    }

    if (buffer.length() > 0) {
        this.cachingKey = buffer.toString();
    }

    String tFactoryClass = conf.getChild("transformer-factory").getValue(null);
    if (tFactoryClass != null) {
        try {
            this.tfactory = (SAXTransformerFactory) ClassUtils.newInstance(tFactoryClass);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Using transformer factory " + tFactoryClass);
            }
        } catch (Exception e) {
            throw new ConfigurationException("Cannot load transformer factory " + tFactoryClass, e);
        }
    } else {
        // Standard TrAX behaviour
        this.tfactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    }
    tfactory.setErrorListener(new TraxErrorHandler(getLogger()));

    // Check if we need namespace as attributes.
    try {
        if (needsNamespacesAsAttributes()) {
            // Setup a correction pipe
            this.namespacePipe = new NamespaceAsAttributes();
            this.namespacePipe.enableLogging(getLogger());
        }
    } catch (Exception e) {
        getLogger().warn("Cannot know if transformer needs namespaces attributes - assuming NO.", e);
    }
}

From source file:org.apache.cocoon.transformation.DASLTransformer.java

/**
 * Intercept the <dasl:query> end tag, convert buffered input to a String, build and execute the
 * DASL query.//  ww  w  .j  a va2  s .c  o  m
 *
 * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
 */
public void endElement(String uri, String name, String raw) throws SAXException {
    String query;
    if (name.equals(QUERY_TAG) && uri.equals(DASL_QUERY_NS)) {
        DocumentFragment frag = this.endRecording();
        try {
            Properties props = XMLUtils.createPropertiesForXML(false);
            props.put(OutputKeys.ENCODING, "ISO-8859-1");
            query = XMLUtils.serializeNode(frag, props);
            // Perform the DASL query
            this.performSearchMethod(query);
        } catch (ProcessingException e) {
            throw new SAXException("Unable to fetch the query data:", e);
        }
    } else if (name.equals(SUBSTITUTE_TAG) && uri.equals(DASL_QUERY_NS)) {
        //Do nothing!!!!
    } else {
        super.endElement(uri, name, raw);
    }
}

From source file:org.apache.cocoon.transformation.WebDAVTransformer.java

public void endElement(String uri, String name, String raw) throws SAXException {
    if (name.equals(REQUEST_TAG) && uri.equals(NS_URI)) {

        try {/*w w w .  j  av  a 2s .  c  om*/
            HttpURL url = new HttpURL(m_target);
            if (url.getUser() != null && !"".equals(url.getUser())) {
                m_state.setCredentials(null, new UsernamePasswordCredentials(url.getUser(), url.getPassword()));
            }
            m_target = url.getURI();

            if (m_validity != null) {
                m_validity.add(makeWebdavEventValidity(url));
            }

        } catch (Exception e) {
            //ignore
        }

        // create method
        WebDAVRequestMethod method = new WebDAVRequestMethod(m_target, m_method);

        try {
            // add request headers
            Iterator headers = m_headers.entrySet().iterator();
            while (headers.hasNext()) {
                Map.Entry header = (Map.Entry) headers.next();
                method.addRequestHeader((String) header.getKey(), (String) header.getValue());
            }

            Properties props = XMLUtils.createPropertiesForXML(false);
            props.put(OutputKeys.ENCODING, "ISO-8859-1");
            String body = XMLUtils.serializeNode(m_requestdocument, props);
            // set request body
            method.setRequestBody(body.getBytes("ISO-8859-1"));

            // execute the request
            executeRequest(method);
        } catch (ProcessingException e) {
            if (getLogger().isErrorEnabled()) {
                getLogger().debug("Couldn't read request from sax stream", e);
            }
            throw new SAXException("Couldn't read request from sax stream", e);
        } catch (UnsupportedEncodingException e) {
            if (getLogger().isErrorEnabled()) {
                getLogger().debug("ISO-8859-1 encoding not present", e);
            }
            throw new SAXException("ISO-8859-1 encoding not present", e);
        } finally {
            method.releaseConnection();
            m_headers = null;
        }
    } else if (name.equals(HEADER_TAG) && uri.equals(NS_URI)) {
        // dont do anything
    } else if (name.equals(BODY_TAG) && uri.equals(NS_URI)) {
        m_requestdocument = super.endRecording();
    } else {
        super.endElement(uri, name, raw);
    }
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlFilterReaderBaseTest.java

public void dump(Node node, Writer writer) throws TransformerException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(node), new StreamResult(writer));
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlFilterReaderBaseTest.java

public void dump(Node node, OutputStream stream) throws TransformerException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(node), new StreamResult(stream));
}

From source file:org.apache.jackrabbit.webdav.client.methods.XmlRequestEntity.java

public XmlRequestEntity(Document xmlDocument) throws IOException {
    super();//from ww  w  .  j ava2s.  c  o  m
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.transform(new DOMSource(xmlDocument), new StreamResult(out));
    } catch (TransformerException e) {
        log.error("XML serialization failed", e);
        IOException exception = new IOException("XML serialization failed");
        exception.initCause(e);
        throw exception;
    }

    delegatee = new StringRequestEntity(out.toString(), "text/xml", "UTF-8");
}

From source file:org.apache.sling.stanbol.ui.StanbolResourceViewer.java

private void setContent(Node jcrNode, String newContent) throws IOException, RepositoryException {

    try {/*from   ww w . j  a va 2s . com*/
        Document doc = Utils.getXMLDocument(jcrNode);
        Element docElem = doc.getDocumentElement();
        if (docElem.getNodeName().equalsIgnoreCase("html")) {
            Element newBody = parseBody(newContent);
            Element body = (Element) doc.getElementsByTagName("body").item(0);
            org.w3c.dom.Node importedNewBody = doc.importNode(newBody, true);
            body.getParentNode().replaceChild(importedNewBody, body);
        } else {
            InputSource inputSource = new InputSource(new StringReader(newContent));
            Document newContentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(inputSource);
            docElem = newContentDoc.getDocumentElement();
        }
        DOMSource domSource = new DOMSource(docElem);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        //StringWriter out = new StringWriter();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(baos);
        transformer.transform(domSource, streamResult);
        //jcrNode.setProperty("jcr:content/jcr:data", out.toString());
        jcrNode.getProperty("jcr:content/jcr:data").setValue(new String(baos.toByteArray(), "utf-8"));
        jcrNode.save();
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.load.balancer.conf.configurator.SynapseConfigurator.java

/**
 * Write xml document to file./*from  w  w  w  .  j av  a  2  s . c  o  m*/
 *
 * @param document
 * @param outputFilePath
 * @throws IOException
 */
private static void write(Document document, String outputFilePath) throws IOException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DocumentType documentType = document.getDoctype();
        if (documentType != null) {
            String publicId = documentType.getPublicId();
            if (publicId != null) {
                transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, publicId);
            }
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId());
        }
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        Source source = new DOMSource(document);
        FileOutputStream outputStream = new FileOutputStream(outputFilePath);
        Result result = new StreamResult(outputStream);
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(String.format("Could not write xml file: s%", outputFilePath), e);
    }
}