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.springsource.ide.eclipse.commons.browser.javafx.JavaFxBrowserManager.java

/**
 * For debugging..// w ww . java2 s  .c o  m
 */
private void printPageHtml() {
    StringWriter sw = new StringWriter();
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "html");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        transformer.transform(new DOMSource(getView().getEngine().getDocument()), new StreamResult(sw));
        System.out.println(sw.toString());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.talend.designer.maven.utils.PomUtil.java

/**
 * /*from www .j  a  v  a2s  .  co m*/
 * Create pom without refresh eclipse resources
 * 
 * @param artifact
 * @return
 */
public static String generatePom2(MavenArtifact artifact) {
    try {
        Project project = ProjectManager.getInstance().getCurrentProject();
        IProject fsProject = ResourceUtils.getProject(project);
        SecureRandom random = new SecureRandom();
        IPath tempPath = fsProject.getLocation().append("temp").append("pom" + Math.abs(random.nextLong()));
        File tmpFolder = new File(tempPath.toPortableString());
        tmpFolder.mkdirs();
        String pomFile = tempPath.append(TalendMavenConstants.POM_FILE_NAME).toPortableString();
        Model pomModel = new Model();
        pomModel.setModelVersion(TalendMavenConstants.POM_VERSION);
        pomModel.setModelEncoding(TalendMavenConstants.DEFAULT_ENCODING);
        pomModel.setGroupId(artifact.getGroupId());
        pomModel.setArtifactId(artifact.getArtifactId());
        pomModel.setVersion(artifact.getVersion());
        String artifactType = artifact.getType();
        if (artifactType == null || "".equals(artifactType)) {
            artifactType = TalendMavenConstants.PACKAGING_JAR;
        }
        pomModel.setPackaging(artifactType);

        ByteArrayOutputStream buf = new ByteArrayOutputStream();

        MavenPlugin.getMaven().writeModel(pomModel, buf);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(false);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        TransformerFactory tfactory = TransformerFactory.newInstance();

        Document document = documentBuilder.parse(new ByteArrayInputStream(buf.toByteArray()));
        Element documentElement = document.getDocumentElement();

        NamedNodeMap attributes = documentElement.getAttributes();

        if (attributes == null || attributes.getNamedItem("xmlns") == null) { //$NON-NLS-1$
            Attr attr = document.createAttribute("xmlns"); //$NON-NLS-1$
            attr.setTextContent("http://maven.apache.org/POM/4.0.0"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }

        if (attributes == null || attributes.getNamedItem("xmlns:xsi") == null) { //$NON-NLS-1$
            Attr attr = document.createAttribute("xmlns:xsi"); //$NON-NLS-1$
            attr.setTextContent("http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }

        if (attributes == null || attributes.getNamedItem("xsi:schemaLocation") == null) { //$NON-NLS-1$
            Attr attr = document.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", //$NON-NLS-1$
                    "xsi:schemaLocation"); //$NON-NLS-1$
            attr.setTextContent(
                    "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }
        Transformer transformer = tfactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File(pomFile));
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(source, result);

        return pomFile;
    } catch (PersistenceException e) {
        ExceptionHandler.process(e);
    } catch (CoreException e) {
        ExceptionHandler.process(e);
    } catch (ParserConfigurationException e) {
        ExceptionHandler.process(e);
    } catch (SAXException e) {
        ExceptionHandler.process(e);
    } catch (IOException e) {
        ExceptionHandler.process(e);
    } catch (TransformerConfigurationException e) {
        ExceptionHandler.process(e);
    } catch (TransformerException e) {
        ExceptionHandler.process(e);
    }
    return null;
}

From source file:org.tizzit.util.xml.SAXHelper.java

/**
 * @param node the string to stream.//from w  w  w  .  j  a  v  a2 s  .c  o  m
 * @param handler the content handler.
 * @since tizzit-common 15.10.2009
 */
public static void string2sax(String node, ContentHandler handler, String encoding) {
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.STANDALONE, "no");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        if (!"".equals(encoding) && encoding != null) {
            t.setOutputProperty(OutputKeys.ENCODING, encoding);
        }
        StreamSource source = new StreamSource(new StringReader(node));
        SAXResult result = new SAXResult(new OmitXmlDeclarationContentHandler(handler));
        t.transform(source, result);
    } catch (Exception exe) {
        log.error("unknown error occured", exe);
    }
}

From source file:org.wandora.application.gui.topicpanels.webview.WebViewPanel.java

private void initFX(final JFXPanel fxPanel) {
    Group group = new Group();
    Scene scene = new Scene(group);
    fxPanel.setScene(scene);/*from w w  w  .ja  v a  2 s.co  m*/

    webView = new WebView();

    if (javaFXVersionInt >= 8) {
        webView.setScaleX(1.0);
        webView.setScaleY(1.0);
        //webView.setFitToHeight(false);
        //webView.setFitToWidth(false);
        //webView.setZoom(javafx.stage.Screen.getPrimary().getDpi() / 96);
    }

    group.getChildren().add(webView);

    int w = this.getWidth();
    int h = this.getHeight() - 34;

    webView.setMinSize(w, h);
    webView.setMaxSize(w, h);
    webView.setPrefSize(w, h);

    // Obtain the webEngine to navigate
    webEngine = webView.getEngine();

    webEngine.locationProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue,
                final String newValue) {
            if (newValue.endsWith(".pdf")) {
                try {
                    int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(),
                            "Open PDF document in external application?",
                            "Open PDF document in external application?", WandoraOptionPane.YES_NO_OPTION);
                    if (a == WandoraOptionPane.YES_OPTION) {
                        Desktop dt = Desktop.getDesktop();
                        dt.browse(new URI(newValue));
                    }
                } catch (Exception e) {
                }
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        urlTextField.setText(newValue);
                    }
                });
            }
        }
    });
    webEngine.titleProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue,
                final String newValue) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    title = newValue;
                }
            });
        }
    });
    webEngine.setOnAlert(new EventHandler<WebEvent<java.lang.String>>() {
        @Override
        public void handle(WebEvent<String> t) {
            if (t != null) {
                String str = t.getData();
                if (str != null && str.length() > 0) {
                    WandoraOptionPane.showMessageDialog(Wandora.getWandora(), str, "Javascript Alert",
                            WandoraOptionPane.PLAIN_MESSAGE);
                }
            }
        }
    });
    webEngine.setConfirmHandler(new Callback<String, Boolean>() {
        @Override
        public Boolean call(String msg) {
            int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), msg, "Javascript Alert",
                    WandoraOptionPane.YES_NO_OPTION);
            return (a == WandoraOptionPane.YES_OPTION);
        }
    });
    webEngine.setPromptHandler(new Callback<PromptData, String>() {
        @Override
        public String call(PromptData data) {
            String a = WandoraOptionPane.showInputDialog(Wandora.getWandora(), data.getMessage(),
                    data.getDefaultValue(), "Javascript Alert", WandoraOptionPane.QUESTION_MESSAGE);
            return a;
        }
    });

    webEngine.setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {
        @Override
        public WebEngine call(PopupFeatures features) {
            if (informPopupBlocking) {
                WandoraOptionPane.showMessageDialog(Wandora.getWandora(),
                        "A javascript popup has been blocked. Wandora doesn't allow javascript popups in Webview topic panel.",
                        "Javascript popup blocked", WandoraOptionPane.PLAIN_MESSAGE);
            }
            informPopupBlocking = false;
            return null;
        }
    });
    webEngine.setOnVisibilityChanged(new EventHandler<WebEvent<Boolean>>() {
        @Override
        public void handle(WebEvent<Boolean> t) {
            if (t != null) {
                Boolean b = t.getData();
                if (informVisibilityChanges) {
                    WandoraOptionPane.showMessageDialog(Wandora.getWandora(),
                            "A browser window visibility change has been blocked. Wandora doesn't allow visibility changes of windows in Webview topic panel.",
                            "Javascript visibility chnage blocked", WandoraOptionPane.PLAIN_MESSAGE);
                    informVisibilityChanges = false;
                }
            }
        }
    });
    webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
        @Override
        public void changed(ObservableValue ov, State oldState, State newState) {
            if (newState == Worker.State.SCHEDULED) {
                //System.out.println("Scheduled!");
                startLoadingAnimation();
            }
            if (newState == Worker.State.SUCCEEDED) {
                Document doc = webEngine.getDocument();
                try {
                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                    //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                    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");

                    // transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(System.out, "UTF-8")));

                    StringWriter stringWriter = new StringWriter();
                    transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
                    webSource = stringWriter.toString();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                stopLoadingAnimation();
            } else if (newState == Worker.State.CANCELLED) {
                //System.out.println("Cancelled!");
                stopLoadingAnimation();
            } else if (newState == Worker.State.FAILED) {
                webEngine.loadContent(failedToOpenMessage);
                stopLoadingAnimation();
            }
        }
    });

}

From source file:org.wisdom.content.jackson.JacksonSingleton.java

/**
 * Retrieves the string form of the given XML document.
 *
 * @param document the XML document, must not be {@literal null}
 * @return the String form of the object
 *///from www .j a va2  s .co  m
@Override
public String stringify(Document document) {
    try {
        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        transformer.transform(new DOMSource(document), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.apimgt.migration.client._200Specific.ResourceModifier200.java

public static void transformXMLDocument(Document document, File file) {
    document.getDocumentElement().normalize();
    try {//from   w ww .j av  a 2 s  . co m
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, Charset.defaultCharset().toString());
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(new DOMSource(document), new StreamResult(file));
    } catch (TransformerConfigurationException e) {
        log.error("Transformer configuration error encountered while transforming file " + file.getName(), e);
    } catch (TransformerException e) {
        log.error("Transformer error encountered while transforming file " + file.getName(), e);
    }
}

From source file:org.wso2.carbon.appmgt.migration.client.MigrationClientImpl.java

private String modifySignUpConfiguration(String configXml) throws APPMMigrationException {

    Writer stringWriter = new StringWriter();
    try {//from   w  w  w  .  jav a 2 s .co m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource configInputSource = new InputSource();
        configInputSource.setCharacterStream(new StringReader(configXml.trim()));
        Document doc = builder.parse(configInputSource);
        NodeList nodes = doc.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROOT);
        if (nodes.getLength() > 0) {
            // iterate through sign-up role list
            Element roleListParent = (Element) ((Element) nodes.item(0))
                    .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLES_ELEM).item(0);

            NodeList rolesEl = roleListParent.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_ELEM);
            for (int i = 0; i < rolesEl.getLength(); i++) {
                Element tmpEl = (Element) rolesEl.item(i);
                Element permissionElement = (Element) tmpEl
                        .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_PERMISSIONS).item(0);
                if (permissionElement == null) {
                    Element externalRole = (Element) tmpEl
                            .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(0);
                    Element newElement = doc.createElement(AppMConstants.SELF_SIGN_UP_REG_ROLE_PERMISSIONS);
                    //Set default permissions into config
                    newElement.setTextContent(
                            "/permission/admin/login,/permission/admin/manage/webapp/subscribe");
                    tmpEl.insertBefore(newElement, externalRole);
                }
            }
        }
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));

    } catch (SAXException e) {
        handleException("Error occurred while parsing signup configuration.", e);
    } catch (IOException e) {
        handleException("Error occurred while reading the sign up configuration document. "
                + "Please check the existence of signup configuration file in registry.", e);
    } catch (ParserConfigurationException e) {
        handleException("Error occurred while trying to build the signup configuration xml document", e);
    } catch (TransformerException e) {
        handleException("Error occurred while saving modified signup configuration xml document", e);
    }

    return stringWriter.toString();
}

From source file:org.wso2.carbon.appmgt.migration.util.ResourceUtil.java

public static void transformXMLDocument(Document document, File file) {
    document.getDocumentElement().normalize();
    try {//from  www  .  j  a  v  a 2  s  .  c  om
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, Charset.defaultCharset().toString());
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(document), new StreamResult(file));
    } catch (TransformerConfigurationException e) {
        log.error("Transformer configuration error encountered while transforming file " + file.getName(), e);
    } catch (TransformerException e) {
        log.error("Transformer error encountered while transforming file " + file.getName(), e);
    }
}

From source file:org.wso2.carbon.governance.comparator.utils.ComparatorUtils.java

/**
 * This method is used to format XML Strings
 * @param input                 input xml String
 * @return                      formatted xml String
 *//*  w ww.j a va 2 s  .co m*/
private String prettyFormatXML(String input) {
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(input.getBytes(ComparatorConstants.UTF_8))));

        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, ComparatorConstants.UTF_8);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ComparatorConstants.YES);
        transformer.setOutputProperty(OutputKeys.INDENT, ComparatorConstants.YES);
        transformer.setOutputProperty(ComparatorConstants.XML_INDENT_AMOUNT, ComparatorConstants.TWO);

        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);

        transformer.transform(new DOMSource(document), streamResult);
        return stringWriter.toString();
    } catch (TransformerException | SAXException | ParserConfigurationException | XPathExpressionException
            | IOException e) {
        log.warn("Error occurred while formatting the xml content.", e);
        return input;
    }
}

From source file:org.wso2.carbon.identity.user.store.configuration.UserStoreConfigAdminService.java

/**
 * Update a domain to be disabled/enabled
 *
 * @param domain:   Name of the domain to be updated
 * @param isDisable : Whether to disable/enable domain(true/false)
 *//*from w w w .  j  a  va2s.c  o m*/
public void changeUserStoreState(String domain, Boolean isDisable) throws IdentityUserStoreMgtException {

    File userStoreConfigFile = createConfigurationFile(domain);
    StreamResult result = new StreamResult(userStoreConfigFile);
    if (!userStoreConfigFile.exists()) {
        String errorMessage = "Cannot edit user store." + domain + " does not exist.";
        throw new IdentityUserStoreMgtException(errorMessage);
    }

    DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(userStoreConfigFile);

        NodeList elements = doc.getElementsByTagName("Property");
        for (int i = 0; i < elements.getLength(); i++) {
            //Assumes a property element only have attribute 'name'
            if ("Disabled".compareToIgnoreCase(elements.item(i).getAttributes().item(0).getNodeValue()) == 0) {
                elements.item(i).setTextContent(String.valueOf(isDisable));
                break;
            }
        }

        DOMSource source = new DOMSource(doc);

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

        if (log.isDebugEnabled()) {
            log.debug("New state :" + isDisable + " of the user store \'" + domain
                    + "\' successfully written to the file system");
        }
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage(), e);
        throw new IdentityUserStoreMgtException("Error while updating user store state", e);
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
        throw new IdentityUserStoreMgtException("Error while updating user store state", e);
    } catch (TransformerConfigurationException e) {
        log.error(e.getMessage(), e);
        throw new IdentityUserStoreMgtException("Error while updating user store state", e);
    } catch (TransformerException e) {
        log.error(e.getMessage(), e);
        throw new IdentityUserStoreMgtException("Error while updating user store state", e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new IdentityUserStoreMgtException("Error while updating user store state", e);
    }
}