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.freecine.filmscan.TestScanStrip.java

@Test
public void testXmlExportImport() throws IOException, TransformerConfigurationException, SAXException {
    ScanStrip sc = new ScanStrip();
    sc.setOrientation(90);/* ww w  . ja v  a2  s  . co m*/
    for (int n = 100; n < 37000; n += 800) {
        sc.addPerforation(100, n);
    }
    File f = File.createTempFile("scanstrip_test", "xml");

    // Write the strip info to a file
    StreamResult streamResult = new StreamResult(f);
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd = tf.newTransformerHandler();
    Transformer serializer = hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    hd.setResult(streamResult);
    hd.startDocument();
    sc.writeXml(hd);
    hd.endDocument();

    Digester d = new Digester();
    d.addRuleSet(new ScanStripRuleSet(""));
    ScanStrip parsedSc = (ScanStrip) d.parse(f);
    assert parsedSc.equals(sc);
}

From source file:org.freecine.filmscan.TestScene.java

/**
 Test import & export to XML/*from   ww  w  .j a v a2  s. c  o m*/
 @throws java.io.IOException
 @throws javax.xml.transform.TransformerConfigurationException
 @throws org.xml.sax.SAXException
 */
@Test
public void testXml() throws IOException, TransformerConfigurationException, SAXException {
    Project prj = new Project(new File("."));
    ScanStrip sc1 = prj.getScanStrip("strip1");
    ScanStrip sc2 = prj.getScanStrip("strip2");
    for (int n = 0; n < 30; n++) {
        sc1.addPerforation(100, n * 800);
        sc2.addPerforation(100, n * 800);
    }

    Scene scene = new Scene();
    scene.addFrames(sc1, 3, 27);
    scene.addFrames(sc2, 0, 25);
    scene.setBlack(127);
    scene.setWhite(23000);

    File f = File.createTempFile("scene_test", "xml");

    // Write the strip info to a file
    StreamResult streamResult = new StreamResult(f);
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd = tf.newTransformerHandler();
    Transformer serializer = hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    hd.setResult(streamResult);
    hd.startDocument();
    scene.writeXml(hd);
    hd.endDocument();

    Digester d = new Digester();
    d.addRuleSet(new SceneRuleSet(prj, ""));
    Scene parsedScene = (Scene) d.parse(f);

    assertEquals(scene.getFrameCount(), parsedScene.getFrameCount());
    assertEquals(scene.getWhite(), parsedScene.getWhite());
    assertEquals(scene.getBlack(), parsedScene.getBlack());

    for (int n = 0; n < scene.getFrameCount(); n++) {
        System.out.println(n);
        assertTrue(scene.getFrameStrip(n) == parsedScene.getFrameStrip(n));
        assertEquals(scene.getStripFrameNum(n), parsedScene.getStripFrameNum(n));
    }

}

From source file:org.geoserver.security.xml.XMLRoleStore.java

@Override
protected void serialize() throws IOException {

    DocumentBuilder builder = null;
    try {/*  w  w  w  .j a v a  2s.c  om*/
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e1) {
        throw new IOException(e1);
    }
    Document doc = builder.newDocument();

    Element rolereg = doc.createElement(E_ROLEREGISTRY_RR);
    doc.appendChild(rolereg);
    rolereg.setAttribute(javax.xml.XMLConstants.XMLNS_ATTRIBUTE, NS_RR);
    rolereg.setAttribute(A_VERSION_RR, VERSION_RR_1_0);

    Element rolelist = doc.createElement(E_ROLELIST_RR);
    rolereg.appendChild(rolelist);

    for (GeoServerRole roleObject : helper.roleMap.values()) {
        Element role = doc.createElement(E_ROLE_RR);
        rolelist.appendChild(role);
        role.setAttribute(A_ROLEID_RR, roleObject.getAuthority());
        GeoServerRole parentObject = helper.role_parentMap.get(roleObject);
        if (parentObject != null) {
            role.setAttribute(A_PARENTID_RR, parentObject.getAuthority());
        }
        for (Object key : roleObject.getProperties().keySet()) {
            Element property = doc.createElement(E_PROPERTY_RR);
            role.appendChild(property);
            property.setAttribute(A_PROPERTY_NAME_RR, key.toString());
            property.setTextContent(roleObject.getProperties().getProperty(key.toString()));
        }
    }

    Element userList = doc.createElement(E_USERLIST_RR);
    rolereg.appendChild(userList);
    for (String userName : helper.user_roleMap.keySet()) {
        Element userroles = doc.createElement(E_USERROLES_RR);
        userList.appendChild(userroles);
        userroles.setAttribute(A_USERNAME_RR, userName);
        SortedSet<GeoServerRole> roleObjects = helper.user_roleMap.get(userName);
        for (GeoServerRole roleObject : roleObjects) {
            Element ref = doc.createElement(E_ROLEREF_RR);
            userroles.appendChild(ref);
            ref.setAttribute(A_ROLEREFID_RR, roleObject.getAuthority());
        }
    }

    Element groupList = doc.createElement(E_GROUPLIST_RR);
    rolereg.appendChild(groupList);

    for (String groupName : helper.group_roleMap.keySet()) {
        Element grouproles = doc.createElement(E_GROUPROLES_RR);
        groupList.appendChild(grouproles);
        grouproles.setAttribute(A_GROUPNAME_RR, groupName);
        SortedSet<GeoServerRole> roleObjects = helper.group_roleMap.get(groupName);
        for (GeoServerRole roleObject : roleObjects) {
            Element ref = doc.createElement(E_ROLEREF_RR);
            grouproles.appendChild(ref);
            ref.setAttribute(A_ROLEREFID_RR, roleObject.getAuthority());
        }
    }

    // serialize the dom
    try {
        //            TODO, wait for JAVA 6
        //            if (isValidatingXMLSchema()) {
        //                XMLValidator.Singleton.validateRoleRegistry(doc);
        //            }

        Transformer tx = TransformerFactory.newInstance().newTransformer();
        tx.setOutputProperty(OutputKeys.METHOD, "XML");
        tx.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tx.setOutputProperty(OutputKeys.INDENT, "yes");

        OutputStream out = new BufferedOutputStream(new FileOutputStream(roleFile));
        try {
            tx.transform(new DOMSource(doc), new StreamResult(out));
            out.flush();
        } finally {
            IOUtils.closeQuietly(out);
        }

        /* standard java, but there is no possibility to set 
         * the number of chars to indent, each line is starting at 
         * column 0
        Source source = new DOMSource(doc);
        // Prepare the output file            
        Result result = new StreamResult(
            new OutputStreamWriter(new FileOutputStream(roleFile),"UTF-8"));
                
        TransformerFactory fac = TransformerFactory.newInstance();
        Transformer xformer = fac.newTransformer();                        
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");            
        xformer.transform(source, result);
        */

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.geoserver.security.xml.XMLUserGroupStore.java

@Override
protected void serialize() throws IOException {

    DocumentBuilder builder = null;
    try {//from  w  w w  . j av a2  s  .com
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        builder = fac.newDocumentBuilder();
    } catch (ParserConfigurationException e1) {
        throw new IOException(e1);
    }
    Document doc = builder.newDocument();

    Element userreg = doc.createElement(E_USERREGISTRY_UR);
    doc.appendChild(userreg);
    userreg.setAttribute(javax.xml.XMLConstants.XMLNS_ATTRIBUTE, NS_UR);
    userreg.setAttribute(A_VERSION_UR, VERSION_UR_1_0);

    Element users = doc.createElement(E_USERS_UR);
    userreg.appendChild(users);
    for (GeoServerUser userObject : helper.userMap.values()) {
        Element user = doc.createElement(E_USER_UR);
        users.appendChild(user);
        user.setAttribute(A_USER_NAME_UR, userObject.getUsername());
        if (userObject.getPassword() != null) {
            user.setAttribute(A_USER_PASSWORD_UR, userObject.getPassword());
        }
        user.setAttribute(A_USER_ENABLED_UR, String.valueOf(userObject.isEnabled()));

        for (Object key : userObject.getProperties().keySet()) {
            Element property = doc.createElement(E_PROPERTY_UR);
            user.appendChild(property);
            property.setAttribute(A_PROPERTY_NAME_UR, key.toString());
            property.setTextContent(userObject.getProperties().getProperty(key.toString()));
        }
    }

    Element groups = doc.createElement(E_GROUPS_UR);
    userreg.appendChild(groups);
    for (GeoServerUserGroup groupObject : helper.groupMap.values()) {
        Element group = doc.createElement(E_GROUP_UR);
        groups.appendChild(group);
        group.setAttribute(A_GROUP_NAME_UR, groupObject.getGroupname());
        group.setAttribute(A_GROUP_ENABLED_UR, groupObject.isEnabled() ? "true" : "false");
        SortedSet<GeoServerUser> userObjects = helper.group_userMap.get(groupObject);
        if (userObjects != null) {
            for (GeoServerUser userObject : userObjects) {
                Element member = doc.createElement(E_MEMBER_UR);
                group.appendChild(member);
                member.setAttribute(A_MEMBER_NAME_UR, userObject.getUsername());
            }
        }
    }

    // serialize the dom
    try {
        //            TODO, wait for JAVA 6
        //            if (isValidatingXMLSchema()) {
        //                XMLValidator.Singleton.validateUserGroupRegistry(doc);
        //            }            

        Transformer tx = TransformerFactory.newInstance().newTransformer();
        tx.setOutputProperty(OutputKeys.METHOD, "XML");
        tx.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tx.setOutputProperty(OutputKeys.INDENT, "yes");

        OutputStream out = new BufferedOutputStream(new FileOutputStream(userFile));
        try {
            tx.transform(new DOMSource(doc), new StreamResult(out));
            out.flush();
        } finally {
            IOUtils.closeQuietly(out);
        }
        /* standard java, but there is no possiTbility to set 
         * the number of chars to indent, each line is starting at 
         * column 0            
        Source source = new DOMSource(doc);
        Result result = new StreamResult(
            new OutputStreamWriter(new FileOutputStream(userFile),"UTF-8"));
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.transform(source, result);
        */

    } catch (Exception e) {
        throw new IOException(e);
    }

}

From source file:org.geotools.data.wfs.internal.v1_x.MapServerWFSStrategy.java

@Override
public InputStream getPostContents(WFSRequest request) throws IOException {
    InputStream in = super.getPostContents(request);

    if (request.getOperation().compareTo(WFSOperationType.GET_FEATURE) == 0
            && getVersion().compareTo("1.0.0") == 0 && mapServerVersion != null) {
        try {/*from w w  w  .  ja v  a2 s .  c  o  m*/
            // Pre-5.6.7 versions of MapServer do not support the following gml:Box coordinate format:
            // <gml:coord><gml:X>-59.0</gml:X><gml:Y>-35.0</gml:Y></gml:coord><gml:coord>< gml:X>-58.0</gml:X><gml:Y>-34.0</gml:Y></gml:coord>
            // Rewrite the coordinates in the following format:
            // <gml:coordinates cs="," decimal="." ts=" ">-59,-35 -58,-34</gml:coordinates>
            String[] tokens = mapServerVersion.split("\\.");
            if (tokens.length == 3 && versionCompare(mapServerVersion, "5.6.7") < 0) {
                StringWriter writer = new StringWriter();
                IOUtils.copy(in, writer, "UTF-8");
                String pc = writer.toString();

                boolean reformatted = false;
                if (pc.contains("gml:Box") && pc.contains("gml:coord") && pc.contains("gml:X")
                        && pc.contains("gml:Y")) {

                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setNamespaceAware(true);
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(new ByteArrayInputStream(pc.getBytes()));

                    NodeList boxes = doc.getElementsByTagName("gml:Box");
                    for (int b = 0; b < boxes.getLength(); b++) {
                        Element box = (Element) boxes.item(b);
                        NodeList coords = box.getElementsByTagName("gml:coord");
                        if (coords != null && coords.getLength() == 2) {
                            Element coord1 = (Element) coords.item(0);
                            Element coord2 = (Element) coords.item(1);
                            if (coord1 != null && coord2 != null) {
                                Element coordX1 = (Element) (coord1.getElementsByTagName("gml:X").item(0));
                                Element coordY1 = (Element) (coord1.getElementsByTagName("gml:Y").item(0));
                                Element coordX2 = (Element) (coord2.getElementsByTagName("gml:X").item(0));
                                Element coordY2 = (Element) (coord2.getElementsByTagName("gml:Y").item(0));
                                if (coordX1 != null && coordY1 != null && coordX2 != null && coordY2 != null) {
                                    reformatted = true;
                                    String x1 = coordX1.getTextContent();
                                    String y1 = coordY1.getTextContent();
                                    String x2 = coordX2.getTextContent();
                                    String y2 = coordY2.getTextContent();

                                    box.removeChild(coord1);
                                    box.removeChild(coord2);

                                    Element coordinates = doc.createElement("gml:coordinates");
                                    coordinates.setAttribute("cs", ",");
                                    coordinates.setAttribute("decimal", ".");
                                    coordinates.setAttribute("ts", " ");
                                    coordinates.appendChild(
                                            doc.createTextNode(x1 + "," + y1 + " " + x2 + "," + y2));
                                    box.appendChild(coordinates);
                                }
                            }
                        }
                    }

                    if (reformatted) {
                        DOMSource domSource = new DOMSource(doc);
                        StringWriter domsw = new StringWriter();
                        StreamResult result = new StreamResult(domsw);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer transformer = tf.newTransformer();
                        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                        transformer.transform(domSource, result);
                        domsw.flush();
                        pc = domsw.toString();
                    }
                }
                in = new ByteArrayInputStream(pc.getBytes());
            }
        } catch (SAXException | ParserConfigurationException | TransformerException | IOException ex) {
            LOGGER.log(Level.FINE,
                    "Unexpected exception while rewriting 1.0.0 GETFEATURE request with BBOX filter",
                    ex.getMessage());
        }
    }

    return in;
}

From source file:org.gephi.desktop.preview.PresetUtils.java

public void savePreset(PreviewPreset preset) {
    int exist = -1;
    for (int i = 0; i < presets.size(); i++) {
        PreviewPreset p = presets.get(i);
        if (p.getName().equals(preset.getName())) {
            exist = i;//w  w  w  .j a  va2s.  c o m
            break;
        }
    }
    if (exist == -1) {
        addPreset(preset);
    } else {
        presets.set(exist, preset);
    }

    try {
        //Create file if dont exist
        FileObject folder = FileUtil.getConfigFile("previewpresets");
        if (folder == null) {
            folder = FileUtil.getConfigRoot().createFolder("previewpresets");
        }

        String filename = DigestUtils.sha1Hex(preset.getName());//Safe filename

        FileObject presetFile = folder.getFileObject(filename, "xml");
        if (presetFile == null) {
            presetFile = folder.createData(filename, "xml");
        }

        //Create doc
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        final Document document = documentBuilder.newDocument();
        document.setXmlVersion("1.0");
        document.setXmlStandalone(true);

        //Write doc
        writeXML(document, preset);

        //Write XML file
        try (OutputStream outputStream = presetFile.getOutputStream()) {
            Source source = new DOMSource(document);
            Result result = new StreamResult(outputStream);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.transform(source, result);
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:org.gluu.saml.Response.java

public void printDocument(OutputStream out) throws IOException, TransformerException {
    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.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(new DOMSource(xmlDoc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperation.java

private void writeSvgDocument(final File file, final Document svgDocument) {
    try {/*from  w w w .j  a  v a2  s . c om*/
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, svgDocument.getInputEncoding());
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
        Result output = new StreamResult(file);
        Source input = new DOMSource(svgDocument);
        transformer.transform(input, output);
    } catch (TransformerConfigurationException e) {
        log.info("Writing SVG file " + file.getName() + " failed, using original instead", e);
    } catch (TransformerException e) {
        log.info("Writing SVG file " + file.getName() + " failed, using original instead", e);
    }
}

From source file:org.hippoecm.repository.impl.SessionDecorator.java

private ContentHandler getExportContentHandler(OutputStream stream) throws RepositoryException {
    try {//ww  w.  j a v a 2s.  com
        SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler = stf.newTransformerHandler();

        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
        handler.setResult(new StreamResult(stream));
        return handler;
    } catch (TransformerFactoryConfigurationError e) {
        throw new RepositoryException("SAX transformer implementation not available", e);
    } catch (TransformerException e) {
        throw new RepositoryException("Error creating an XML export content handler", e);
    }
}

From source file:org.jahia.services.content.JCRSessionWrapper.java

/**
 * Creates a {@link ContentHandler} instance that serializes the
 * received SAX events to the given output stream.
 *
 * @param stream output stream to which the SAX events are serialized
 * @return SAX content handler/*ww  w.  ja v a2  s .c om*/
 * @throws RepositoryException if an error occurs
 */
private ContentHandler getExportContentHandler(OutputStream stream) throws RepositoryException {
    try {
        SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler = stf.newTransformerHandler();

        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");

        handler.setResult(new StreamResult(stream));
        return handler;
    } catch (TransformerFactoryConfigurationError e) {
        throw new RepositoryException("SAX transformer implementation not available", e);
    } catch (TransformerException e) {
        throw new RepositoryException("Error creating an XML export content handler", e);
    }
}