Example usage for org.w3c.dom.ls LSSerializer getDomConfig

List of usage examples for org.w3c.dom.ls LSSerializer getDomConfig

Introduction

In this page you can find the example usage for org.w3c.dom.ls LSSerializer getDomConfig.

Prototype

public DOMConfiguration getDomConfig();

Source Link

Document

The DOMConfiguration object used by the LSSerializer when serializing a DOM node.

Usage

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private String prettyPrint(final Signature signature)
        throws TransformerException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(signature.getBytes()));
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    DOMResult outputTarget = new DOMResult();
    transformer.transform(xmlSource, outputTarget);

    final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    final LSSerializer writer = impl.createLSSerializer();

    writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
    writer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);

    return writer.writeToString(outputTarget.getNode());
}

From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java

private CombinedQueryDefinitionImpl parseCombinedQuery(RawCombinedQueryDefinition qdef) {
    DOMHandle handle = new DOMHandle();
    HandleAccessor.receiveContent(handle, HandleAccessor.contentAsString(qdef.getHandle()));
    Document combinedQueryXml = handle.get();
    DOMImplementationLS domImplementation = (DOMImplementationLS) combinedQueryXml.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("xml-declaration", false);

    NodeList nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "options");
    Node n = nl.item(0);/*  ww  w.j a  v a2s .co  m*/
    String options = null;
    StringHandle optionsHandle = null;
    if (n != null) {
        options = lsSerializer.writeToString(n);
        optionsHandle = new StringHandle(options).withFormat(Format.XML);
    }

    //TODO this could be more than one string...
    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "qtext");
    n = nl.item(0);
    String qtext = null;
    if (n != null) {
        qtext = lsSerializer.writeToString(n);
    }

    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "sparql");
    n = nl.item(0);
    String sparql = null;
    if (n != null) {
        sparql = lsSerializer.writeToString(n);
    }

    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "query");
    n = nl.item(0);
    String query = null;
    if (n != null) {
        query = lsSerializer.writeToString(nl.item(0));
    }
    StringHandle structuredQueryHandle = new StringHandle().with(query).withFormat(Format.XML);
    RawStructuredQueryDefinition structuredQueryDefinition = new RawQueryDefinitionImpl.Structured(
            structuredQueryHandle);
    return new CombinedQueryDefinitionImpl(structuredQueryDefinition, optionsHandle, qtext, sparql);
}

From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java

/**
 * method to convert Document to String//from   ww  w. j  a  v  a 2  s  . co  m
 *
 * @param doc
 * @return
 */
protected String getStringFromDocument(final Document doc) {
    try {
        final StringWriter writer = new StringWriter();
        final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
        final LSSerializer lsSerializer = domImplementation.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);

        final LSOutput lsOutput = domImplementation.createLSOutput();
        lsOutput.setCharacterStream(writer);
        lsSerializer.write(doc, lsOutput);

        return writer.toString();
    } catch (final LSException ex) {
        getLog().error(ex);
        return null;
    }
}

From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java

protected void writeXmlFile(final Document doc, final File workDirectory, final String fileName)
        throws MojoFailureException {
    final File destinationFile = new File(workDirectory, fileName);
    try {/*from   w  w  w  .  j a  v a2s  .  c  om*/
        final FileOutputStream ostream = new FileOutputStream(destinationFile);
        final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
        final LSSerializer lsSerializer = domImplementation.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);

        final LSOutput lsOutput = domImplementation.createLSOutput();
        lsOutput.setByteStream(ostream);
        lsSerializer.write(doc, lsOutput);

        ostream.close();
        refreshEclipse(destinationFile);
    } catch (final Exception e) {
        throw new MojoFailureException("Cannot write output file", e);
    }
}

From source file:org.dasein.cloud.cloudstack.CSMethod.java

private String prettifyXml(Document doc) {
    try {//from   w w w. jav a 2s .  c  om
        DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance()
                .getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        return writer.writeToString(doc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Transform into formatted XML.//from   ww w .j a v a 2 s .  c om
 */
private String getFormattedXml(Node node) {
    Document document = node.getOwnerDocument().getImplementation().createDocument("", "fake", null);
    Element copy = (Element) document.importNode(node, true);
    document.importNode(node, false);
    document.removeChild(document.getDocumentElement());
    document.appendChild(copy);
    DOMImplementation domImpl = document.getImplementation();
    DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
    LSSerializer serializer = domImplLs.createLSSerializer();
    serializer.getDomConfig().setParameter("format-pretty-print", true);
    return serializer.writeToString(document);
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Utility method for serializing DOM to a String
 * @param doc Document to serialize/* ww  w.  j ava2  s .c o m*/
 * @return XML document as a String
 */
private String writeDomToString(Document doc) {
    LSSerializer writer = domLoadSaveImpl.createLSSerializer();
    DOMConfiguration domConfig = writer.getDomConfig();
    domConfig.setParameter("xml-declaration", false);
    String xmlString = writer.writeToString(doc);
    return xmlString;
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    initialize(request);//from w  w  w . j  a  va2 s  .  c o m

    int userId = 0;
    int groupId = 0;
    String user = "";
    String context = request.getContextPath();
    String url = request.getPathInfo();

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    try {
        //On initialise le dataProvider
        Connection c = null;
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // =====================================================================================
    boolean trace = false;
    StringBuffer outTrace = new StringBuffer();
    StringBuffer outPrint = new StringBuffer();
    String logFName = null;

    response.setCharacterEncoding("UTF-8");

    System.out.println("FileServlet::doGet");
    try {
        // ====== URI : /resources/file[/{lang}]/{context-id}
        // ====== PathInfo: /resources/file[/{uuid}?lang={fr|en}&size={S|L}] pathInfo
        //         String uri = request.getRequestURI();
        String[] token = url.split("/");
        String uuid = token[1];
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile:"+request.getRemoteAddr()+":"+uri);

        /// FIXME: Passe la scurit si la source provient de localhost, il faudrait un change afin de s'assurer que n'importe quel servlet ne puisse y accder
        String sourceip = request.getRemoteAddr();
        System.out.println("IP: " + sourceip);

        /// Vrification des droits d'accs
        // TODO: Might be something special with proxy and export/PDF, to investigate
        if (!ourIPs.contains(sourceip)) {
            if (userId == 0)
                throw new RestWebApplicationException(Status.FORBIDDEN, "");

            if (!credential.hasNodeRight(userId, groupId, uuid, Credential.READ)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit READ sur le noeud "+nodeUuid);
            }
        } else // Si la requte est locale et qu'il n'y a pas de session, on ignore la vrification
        {
            System.out.println("IP OK: bypass");
        }

        /// On rcupre le noeud de la ressource pour retrouver le lien
        String data = dataProvider.getResNode(uuid, userId, groupId);

        //         javax.servlet.http.HttpSession session = request.getSession(true);
        //====================================================
        //String ppath = session.getServletContext().getRealPath("/");
        //logFName = ppath +"logs/logNode.txt";
        //====================================================
        String size = request.getParameter("size");
        if (size == null)
            size = "S";

        String lang = request.getParameter("lang");
        if (lang == null) {
            lang = "fr";
        }

        /*
        String nodeUuid = uri.substring(uri.lastIndexOf("/")+1);
        if  (uri.lastIndexOf("/")>uri.indexOf("file/")+6) { // -- file/ = 5 carac. --
           lang = uri.substring(uri.indexOf("file/")+5,uri.lastIndexOf("/"));
        }
        //*/

        String ref = request.getHeader("referer");

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Trouve le bon noeud
        XPath xPath = XPathFactory.newInstance().newXPath();

        /// Either we have a fileid per language
        String filterRes = "//fileid[@lang='" + lang + "']";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);
        String resolve = "";
        if (nodelist.getLength() != 0) {
            Element fileNode = (Element) nodelist.item(0);
            resolve = fileNode.getTextContent();
        }

        /// Or just a single one shared
        if ("".equals(resolve)) {
            response.setStatus(404);
            return;
        }

        String filterName = "//filename[@lang='" + lang + "']";
        NodeList textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filename = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            filename = fileNode.getTextContent();
        }

        String filterType = "//type[@lang='" + lang + "']";
        textList = (NodeList) xPath.compile(filterType).evaluate(doc, XPathConstants.NODESET);
        String type = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            type = fileNode.getTextContent();
        }

        /*
        String filterSize = "//size[@lang='"+lang+"']";
        textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filesize = "";
        if( textList.getLength() != 0 )
        {
           Element fileNode = (Element) textList.item(0);
           filesize = fileNode.getTextContent();
        }
        //*/

        System.out.println("!!! RESOLVE: " + resolve);

        /// Envoie de la requte au servlet de fichiers
        // http://localhost:8080/MiniRestFileServer/user/claudecoulombe/file/a8e0f07f-671c-4f6a-be6c-9dba12c519cf/ptype/sql
        /// TODO: Ne plus avoir besoin du switch
        String urlTarget = "http://" + server + "/" + resolve;
        //         String urlTarget = "http://"+ server + "/user/" + resolve +"/"+ lang + "/ptype/fs";

        HttpURLConnection connection = CreateConnection(urlTarget, request);
        connection.connect();
        InputStream input = connection.getInputStream();
        String sizeComplete = connection.getHeaderField("Content-Length");
        int completeSize = Integer.parseInt(sizeComplete);

        response.setContentLength(completeSize);
        response.setContentType(type);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        ServletOutputStream output = response.getOutputStream();

        byte[] buffer = new byte[completeSize];
        int totalRead = 0;
        int bytesRead = -1;

        while ((bytesRead = input.read(buffer, 0, completeSize)) != -1 || totalRead < completeSize) {
            output.write(buffer, 0, bytesRead);
            totalRead += bytesRead;
        }

        //         IOUtils.copy(input, output);
        //         IOUtils.closeQuietly(output);

        output.flush();
        output.close();
        input.close();
        connection.disconnect();
    } catch (RestWebApplicationException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.toString() + " -> " + e.getLocalizedMessage());
        e.printStackTrace();
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile: error"+e);
    } finally {
        try {
            dataProvider.disconnect();
        } catch (Exception e) {
            ServletOutputStream out = response.getOutputStream();
            out.println("Erreur dans doGet: " + e);
            out.close();
        }
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // =====================================================================================
    initialize(request);/*from  ww w  .ja v  a 2  s . co m*/

    int userId = 0;
    int groupId = 0;
    String user = "";

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    Connection c = null;
    try {
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /// uuid: celui de la ressource

    /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]

    String origin = request.getRequestURL().toString();

    /// Rcupration des paramtres
    String url = request.getPathInfo();
    String[] token = url.split("/");
    String uuid = token[1];

    String size = request.getParameter("size");
    if (size == null)
        size = "S";

    String lang = request.getParameter("lang");
    if (lang == null) {
        lang = "fr";
    }

    /// Vrification des droits d'accs
    if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid);
    }

    String data;
    String fileid = "";
    try {
        data = dataProvider.getResNode(uuid, userId, groupId);

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Cherche si on a dj envoy quelque chose
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//filename[@lang=\"" + lang + "\"]";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        String filename = "";
        if (nodelist.getLength() > 0)
            filename = nodelist.item(0).getTextContent();

        if (!"".equals(filename)) {
            /// Already have one, per language
            String filterId = "//fileid[@lang='" + lang + "']";
            NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET);
            if (idlist.getLength() != 0) {
                Element fileNode = (Element) idlist.item(0);
                fileid = fileNode.getTextContent();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }

    int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch
    if (last < 0)
        last = 0;
    fileid = fileid.substring(last);
    /// request.getHeader("REFERRER");

    /// criture des donnes
    String urlTarget = "http://" + server + "/" + fileid;
    //      String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

    // Unpack form, fetch binary data and send
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    /*
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    //*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    String json = "";
    HttpURLConnection connection = null;
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if ("uploadfile".equals(item.getFieldName())) {
                // Send raw data
                InputStream inputData = item.getInputStream();

                /*
                URL urlConn = new URL(urlTarget);
                connection = (HttpURLConnection) urlConn.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);                 /// We don't want to cache data
                connection.setInstanceFollowRedirects(false);   /// Let client follow any redirection
                String method = request.getMethod();
                connection.setRequestMethod(method);
                        
                String context = request.getContextPath();
                connection.setRequestProperty("app", context);
                //*/

                String fileName = item.getName();
                long filesize = item.getSize();
                String contentType = item.getContentType();

                //               /*
                connection = CreateConnection(urlTarget, request);
                connection.setRequestProperty("filename", uuid);
                connection.setRequestProperty("content-type", "application/octet-stream");
                connection.setRequestProperty("content-length", Long.toString(filesize));
                //*/
                connection.connect();

                OutputStream outputData = connection.getOutputStream();
                IOUtils.copy(inputData, outputData);

                /// Those 2 lines are needed, otherwise, no request sent
                int code = connection.getResponseCode();
                String msg = connection.getResponseMessage();

                InputStream objReturn = connection.getInputStream();
                StringWriter idResponse = new StringWriter();
                IOUtils.copy(objReturn, idResponse);
                fileid = idResponse.toString();

                connection.disconnect();

                /// Construct Json
                StringWriter StringOutput = new StringWriter();
                JsonWriter writer = new JsonWriter(StringOutput);
                writer.beginObject();
                writer.name("files");
                writer.beginArray();
                writer.beginObject();

                writer.name("name").value(fileName);
                writer.name("size").value(filesize);
                writer.name("type").value(contentType);
                writer.name("url").value(origin);
                writer.name("fileid").value(fileid);
                //                               writer.name("deleteUrl").value(ref);
                //                                       writer.name("deleteType").value("DELETE");
                writer.endObject();

                writer.endArray();
                writer.endObject();

                writer.close();

                json = StringOutput.toString();

                /*
                DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream());
                byte[] buffer = new byte[1024];
                int dataSize;
                while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
                {
                   datawriter.write(buffer, 0, dataSize);
                }
                datawriter.flush();
                datawriter.close();
                //*/
                //               outputData.close();
                //               inputData.close();

                break;
            }
        }
    } catch (FileUploadException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
    HttpURLConnection connection = CreateConnection( urlTarget, request );
            
    connection.setRequestProperty("referer", origin);
            
    /// Send post data
    ServletInputStream inputData = request.getInputStream();
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            
    byte[] buffer = new byte[1024];
    int dataSize;
    while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
    {
       writer.write(buffer, 0, dataSize);
    }
    inputData.close();
    writer.close();
            
    /// So we can forward some Set-Cookie
    String ref = request.getHeader("referer");
            
    /// Prend le JSON du fileserver
    InputStream in = connection.getInputStream();
            
    InitAnswer(connection, response, ref);
            
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    StringBuilder builder = new StringBuilder();
    for( String line = null; (line = reader.readLine()) != null; )
       builder.append(line).append("\n");
    //*/

    /// Envoie la mise  jour au backend
    /*
    try
    {
       PostForm.updateResource(session.getId(), backend, uuid, lang, json);
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
    //*/

    connection.disconnect();
    /// Renvoie le JSON au client
    response.setContentType("application/json");
    PrintWriter respWriter = response.getWriter();
    respWriter.write(json);

    //      RetrieveAnswer(connection, response, ref);
    dataProvider.disconnect();
}

From source file:net.svcret.core.util.XMLUtils.java

public static void serialize(Document document, boolean prettyPrint, Writer theWriter) {
    DOMImplementationLS impl = getDOMImpl();
    LSSerializer serializer = impl.createLSSerializer();
    // document.normalizeDocument();
    DOMConfiguration config = serializer.getDomConfig();
    if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
        config.setParameter("format-pretty-print", true);
    }//from   w w w  .j a va 2  s  .  c o m
    config.setParameter("xml-declaration", true);
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setCharacterStream(theWriter);
    serializer.write(document, output);
}