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.exist.xquery.functions.util.Serialize.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (args[0].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }//w ww  . ja  va  2s .  c  o  m

    Properties outputProperties = null;
    OutputStream os = null;

    if (args.length == 3) {
        // TODO: Remove this conditional in eXist 2.0 since the function has been deprecated.
        /** serialize to disk **/

        // check the file output path
        final String path = args[1].itemAt(0).getStringValue();
        final File file = new File(path);
        if (file.isDirectory()) {
            logger.debug("Output file is a directory: " + file.getAbsolutePath());
            return BooleanValue.FALSE;
        }
        if (file.exists() && !file.canWrite()) {
            logger.debug("Cannot write to file " + file.getAbsolutePath());
            return BooleanValue.FALSE;
        }

        //parse serialization options from third argument to function
        outputProperties = parseSerializationOptions(args[2]);

        //setup output stream for file
        try {
            os = new FileOutputStream(file);
        } catch (final IOException e) {
            throw new XPathException(this,
                    "A problem occurred while serializing the node set: " + e.getMessage(), e);
        }

        //do the serialization
        serialize(args[0].iterate(), outputProperties, os);

        return BooleanValue.TRUE;
    } else {
        /** serialize to string **/

        //parse serialization options from second argument to function           
        outputProperties = parseSerializationOptions(args[1]);

        //setup output stream for byte array
        os = new ByteArrayOutputStream();

        //do the serialization
        serialize(args[0].iterate(), outputProperties, os);

        try {
            final String encoding = outputProperties.getProperty(OutputKeys.ENCODING, "UTF-8");
            return new StringValue(new String(((ByteArrayOutputStream) os).toByteArray(), encoding));
        } catch (final UnsupportedEncodingException e) {
            throw new XPathException(this,
                    "A problem occurred while serializing the node set: " + e.getMessage(), e);
        }
    }

}

From source file:org.exist.xquery.functions.util.Serialize.java

private void serialize(SequenceIterator siNode, Properties outputProperties, OutputStream os)
        throws XPathException {
    // serialize the node set
    final SAXSerializer sax = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
    outputProperties.setProperty(Serializer.GENERATE_DOC_EVENTS, "false");
    try {/*from   ww  w. j a  v  a  2  s . co m*/
        final String encoding = outputProperties.getProperty(OutputKeys.ENCODING, "UTF-8");
        final Writer writer = new OutputStreamWriter(os, encoding);
        sax.setOutput(writer, outputProperties);
        final Serializer serializer = context.getBroker().getSerializer();
        serializer.reset();
        serializer.setProperties(outputProperties);
        serializer.setSAXHandlers(sax, sax);

        sax.startDocument();

        while (siNode.hasNext()) {
            final NodeValue next = (NodeValue) siNode.nextItem();
            serializer.toSAX(next);
        }

        sax.endDocument();
        writer.close();
    } catch (final SAXException e) {
        throw new XPathException(this, "A problem occurred while serializing the node set: " + e.getMessage(),
                e);
    } catch (final IOException e) {
        throw new XPathException(this, "A problem occurred while serializing the node set: " + e.getMessage(),
                e);
    } finally {
        SerializerPool.getInstance().returnObject(sax);
    }
}

From source file:org.exist.xquery.modules.httpclient.PUTFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence response = null;/*from   ww  w.  j a  v a2s  .  com*/

    // must be a URL
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //get the url
    String url = args[0].itemAt(0).getStringValue();

    //get the payload
    Item payload = args[1].itemAt(0);

    //get the persist state
    boolean persistState = args[2].effectiveBooleanValue();

    String indentLevel = (args.length >= 5 && !args[4].isEmpty()) ? args[4].itemAt(0).toString() : null;

    RequestEntity entity = null;

    if (Type.subTypeOf(payload.getType(), Type.NODE)) {
        //serialize the node to SAX
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStreamWriter osw = new OutputStreamWriter(baos, UTF_8);

        IndentingXMLWriter xmlWriter = new IndentingXMLWriter(osw);
        Properties outputProperties = new Properties();
        outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
        if (indentLevel != null) {
            outputProperties.setProperty(OutputKeys.INDENT, "yes");
            outputProperties.setProperty(EXistOutputKeys.INDENT_SPACES, indentLevel);
        } else {
            outputProperties.setProperty(OutputKeys.INDENT, "no");
        }
        xmlWriter.setOutputProperties(outputProperties);

        SAXSerializer sax = new SAXSerializer();

        sax.setReceiver(xmlWriter);

        try {
            payload.toSAX(context.getBroker(), sax, new Properties());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            throw new XPathException(this, e);
        }
        entity = new ByteArrayRequestEntity(baos.toByteArray(), "application/xml; charset=utf-8");

    } else if (Type.subTypeOf(payload.getType(), Type.BASE64_BINARY)) {

        entity = new ByteArrayRequestEntity(payload.toJavaObject(byte[].class));

    } else {

        try {
            entity = new StringRequestEntity(payload.getStringValue(), "text/text; charset=utf-8", "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        }
    }

    //setup PUT request
    PutMethod put = new PutMethod(url);

    put.setRequestEntity(entity);

    //setup PUT Request Headers
    if (!args[3].isEmpty()) {
        setHeaders(put, ((NodeValue) args[3].itemAt(0)).getNode());
    }

    try {

        //execute the request
        response = doRequest(context, put, persistState, null, null);

    } catch (IOException ioe) {
        throw (new XPathException(this, ioe.getMessage(), ioe));
    } finally {
        put.releaseConnection();
    }

    return (response);
}

From source file:org.exjello.mail.Exchange2003Connection.java

private static RequestEntity createFindInboxEntity() throws Exception {
    synchronized (Exchange2003Connection.class) {
        if (findInboxEntity == null) {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            Document doc = dbf.newDocumentBuilder().newDocument();
            Element propfind = doc.createElementNS(DAV_NAMESPACE, "propfind");
            doc.appendChild(propfind);/*from  www  .  j a  v  a  2  s  .  c  om*/
            Element prop = doc.createElementNS(DAV_NAMESPACE, "prop");
            propfind.appendChild(prop);
            Element inbox = doc.createElementNS(HTTPMAIL_NAMESPACE, "inbox");
            prop.appendChild(inbox);
            Element drafts = doc.createElementNS(HTTPMAIL_NAMESPACE, "drafts");
            prop.appendChild(drafts);
            Element sendmsg = doc.createElementNS(HTTPMAIL_NAMESPACE, "sendmsg");
            prop.appendChild(sendmsg);
            Element outbox = doc.createElementNS(HTTPMAIL_NAMESPACE, "outbox");
            prop.appendChild(outbox);
            Element sentitems = doc.createElementNS(HTTPMAIL_NAMESPACE, "sentitems");
            prop.appendChild(sentitems);

            // http://msdn.microsoft.com/en-us/library/ms992623(EXCHG.65).aspx

            ByteArrayOutputStream collector = new ByteArrayOutputStream();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            transformer.transform(new DOMSource(doc), new StreamResult(collector));
            findInboxEntity = collector.toByteArray();
        }
        return new ByteArrayRequestEntity(findInboxEntity, XML_CONTENT_TYPE);
    }
}

From source file:org.exjello.mail.Exchange2003Connection.java

private static byte[] createSearchEntity(String sqlString) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from  w  w w.java 2s  .  c  o  m*/
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element searchRequest = doc.createElementNS(DAV_NAMESPACE, "searchrequest");
    doc.appendChild(searchRequest);
    Element sql = doc.createElementNS(DAV_NAMESPACE, "sql");
    searchRequest.appendChild(sql);
    sql.appendChild(doc.createTextNode(sqlString));
    ByteArrayOutputStream collector = new ByteArrayOutputStream();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    transformer.transform(new DOMSource(doc), new StreamResult(collector));
    return collector.toByteArray();
}

From source file:org.exjello.mail.Exchange2003Connection.java

private static RequestEntity createDeleteEntity(List<ExchangeMessage> messages) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/* www . java  2s .  co  m*/
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element delete = doc.createElementNS(DAV_NAMESPACE, "delete");
    doc.appendChild(delete);
    Element target = doc.createElementNS(DAV_NAMESPACE, "target");
    delete.appendChild(target);
    for (ExchangeMessage message : messages) {
        String url = message.getUrl();
        Element href = doc.createElementNS(DAV_NAMESPACE, "href");
        target.appendChild(href);
        String file = url.substring(url.lastIndexOf("/") + 1);
        href.appendChild(doc.createTextNode(file));
    }
    ByteArrayOutputStream collector = new ByteArrayOutputStream();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    transformer.transform(new DOMSource(doc), new StreamResult(collector));
    return new ByteArrayRequestEntity(collector.toByteArray(), XML_CONTENT_TYPE);
}

From source file:org.exjello.mail.Exchange2003Connection.java

private RequestEntity createAddBccEntity(Address[] addresses) throws Exception {
    StringBuilder recipientList = new StringBuilder();
    for (Address address : addresses) {
        if (recipientList.length() != 0)
            recipientList.append(';');
        recipientList.append(((InternetAddress) address).getAddress());
    }//ww  w  .j  a va2  s  .  co m
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element propertyUpdate = doc.createElementNS(DAV_NAMESPACE, "propertyupdate");
    doc.appendChild(propertyUpdate);
    Element set = doc.createElementNS(DAV_NAMESPACE, "set");
    propertyUpdate.appendChild(set);
    Element prop = doc.createElementNS(DAV_NAMESPACE, "prop");
    set.appendChild(prop);
    Element bcc = doc.createElementNS(MAILHEADER_NAMESPACE, "bcc");
    prop.appendChild(bcc);
    bcc.appendChild(doc.createTextNode(recipientList.toString()));
    ByteArrayOutputStream collector = new ByteArrayOutputStream();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    if (session.getDebug()) {
        transformer.transform(new DOMSource(doc), new StreamResult(session.getDebugOut()));
        session.getDebugOut().println();
    }
    transformer.transform(new DOMSource(doc), new StreamResult(collector));
    return new ByteArrayRequestEntity(collector.toByteArray(), XML_CONTENT_TYPE);
}

From source file:org.exjello.mail.Exchange2003Connection.java

private static RequestEntity createMarkReadEntity(List<ExchangeMessage> messages) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from   w  ww.  ja v a  2  s  .c o  m*/
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element propertyUpdate = doc.createElementNS(DAV_NAMESPACE, "propertyupdate");
    doc.appendChild(propertyUpdate);
    Element target = doc.createElementNS(DAV_NAMESPACE, "target");
    propertyUpdate.appendChild(target);
    for (ExchangeMessage message : messages) {
        String url = message.getUrl();
        Element href = doc.createElementNS(DAV_NAMESPACE, "href");
        target.appendChild(href);
        String file = url.substring(url.lastIndexOf("/") + 1);
        href.appendChild(doc.createTextNode(file));
    }
    Element set = doc.createElementNS(DAV_NAMESPACE, "set");
    propertyUpdate.appendChild(set);
    Element prop = doc.createElementNS(DAV_NAMESPACE, "prop");
    set.appendChild(prop);
    Element read = doc.createElementNS(HTTPMAIL_NAMESPACE, "read");
    prop.appendChild(read);
    read.appendChild(doc.createTextNode("1"));
    ByteArrayOutputStream collector = new ByteArrayOutputStream();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    transformer.transform(new DOMSource(doc), new StreamResult(collector));
    return new ByteArrayRequestEntity(collector.toByteArray(), XML_CONTENT_TYPE);
}

From source file:org.exjello.mail.ExchangeConnection.java

private static RequestEntity createFindInboxEntity() throws Exception {
    synchronized (ExchangeConnection.class) {
        if (findInboxEntity == null) {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            Document doc = dbf.newDocumentBuilder().newDocument();
            Element propfind = doc.createElementNS(DAV_NAMESPACE, "propfind");
            doc.appendChild(propfind);/*from  w  w  w . jav a 2s .  c  om*/
            Element prop = doc.createElementNS(DAV_NAMESPACE, "prop");
            propfind.appendChild(prop);
            Element inbox = doc.createElementNS(HTTPMAIL_NAMESPACE, "inbox");
            prop.appendChild(inbox);
            Element drafts = doc.createElementNS(HTTPMAIL_NAMESPACE, "drafts");
            prop.appendChild(drafts);
            Element sendmsg = doc.createElementNS(HTTPMAIL_NAMESPACE, "sendmsg");
            prop.appendChild(sendmsg);
            Element outbox = doc.createElementNS(HTTPMAIL_NAMESPACE, "outbox");
            prop.appendChild(outbox);
            Element sentitems = doc.createElementNS(HTTPMAIL_NAMESPACE, "sentitems");
            prop.appendChild(sentitems);

            // http://msdn.microsoft.com/en-us/library/ms992623(EXCHG.65).aspx

            ByteArrayOutputStream collector = new ByteArrayOutputStream();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            transformer.transform(new DOMSource(doc), new StreamResult(collector));
            findInboxEntity = collector.toByteArray();
        }
        return new ByteArrayRequestEntity(findInboxEntity, XML_CONTENT_TYPE);
    }
}

From source file:org.expath.tools.model.exist.EXistSequence.java

@Override
public void serialize(final OutputStream out, final SerialParameters params) throws ToolsException {
    final Properties props = params == null ? null : makeOutputProperties(params);
    props.setProperty(Serializer.GENERATE_DOC_EVENTS, "false");

    final String encoding = props.getProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
    try (final Writer writer = new OutputStreamWriter(new CloseShieldOutputStream(out), encoding)) {
        final XQuerySerializer xqSerializer = new XQuerySerializer(context.getBroker(), props, writer);
        xqSerializer.serialize(sequence);
    } catch (final SAXException | IOException | XPathException e) {
        throw new ToolsException("A problem occurred while serializing the node set: " + e.getMessage(), e);
    }//from w w w  .j  ava  2 s  .c  o  m
}