Example usage for org.w3c.dom Node insertBefore

List of usage examples for org.w3c.dom Node insertBefore

Introduction

In this page you can find the example usage for org.w3c.dom Node insertBefore.

Prototype

public Node insertBefore(Node newChild, Node refChild) throws DOMException;

Source Link

Document

Inserts the node newChild before the existing child node refChild.

Usage

From source file:DomUtils.java

/**
 * Replace one node with a list of nodes.
 * @param newNodes New nodes - added in same location as oldNode.
 * @param oldNode Old node - removed./* ww  w . j a va2s .co m*/
 * @param clone Clone Nodelist Nodes.
 */
public static void replaceNode(NodeList newNodes, Node oldNode, boolean clone) {

    Node parentNode = oldNode.getParentNode();

    if (parentNode == null) {
        System.out
                .println("Cannot replace [" + oldNode + "] with a NodeList. [" + oldNode + "] has no parent.");
        return;
    }

    int nodeCount = newNodes.getLength();
    List nodeList = DomUtils.copyNodeList(newNodes);

    if (nodeCount == 0) {
        if (!(parentNode instanceof Document)) {
            parentNode.removeChild(oldNode);
        }
        return;
    }

    if (parentNode instanceof Document) {
        List elements = DomUtils.getElements(newNodes, "*", null);

        if (!elements.isEmpty()) {
            System.out.println(
                    "Request to replace the Document root node with a 1+ in length NodeList.  Replacing root node with the first element node from the NodeList.");
            parentNode.removeChild(oldNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            System.out.println(
                    "Cannot replace document root element with a NodeList that doesn't contain an element node.");
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            if (clone) {
                parentNode.insertBefore(((Node) nodeList.get(i)).cloneNode(true), oldNode);
            } else {
                parentNode.insertBefore((Node) nodeList.get(i), oldNode);
            }
        }
        parentNode.removeChild(oldNode);
    }
}

From source file:DomUtils.java

/**
 * Insert the supplied nodes before the supplied reference node (refNode).
 * @param newNodes Nodes to be inserted.
 * @param refNode Reference node before which the supplied nodes should
 * be inserted./*from   ww  w .  j av  a2 s  . c  o m*/
 */
public static void insertBefore(NodeList newNodes, Node refNode) {

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        System.out
                .println("Cannot insert a NodeList before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

    int nodeCount = newNodes.getLength();
    List nodeList = DomUtils.copyNodeList(newNodes);

    if (nodeCount == 0) {
        return;
    }

    if (parentNode instanceof Document) {
        List elements = DomUtils.getElements(newNodes, "*", null);

        if (!elements.isEmpty()) {
            System.out.println(
                    "Request to insert a NodeList before the Document root node.  Will replace the root element with the 1st element node from the NodeList.");
            parentNode.removeChild(refNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            System.out.println(
                    "Cannot insert beforen the document root element from a NodeList that doesn't contain an element node.");
        }

        for (int i = 0; i < nodeCount; i++) {
            Node node = (Node) nodeList.get(i);
            if (node.getNodeType() != Node.ELEMENT_NODE) {
                System.out.println("****" + node);
                parentNode.insertBefore(node, refNode);
            }
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            parentNode.insertBefore((Node) nodeList.get(i), refNode);
        }
    }
}

From source file:eionet.gdem.qa.QAResultPostProcessor.java

/**
 * Parses div nodes and adds warning node to result
 * @param divElements Div elements//  w w w  .  j  a  v  a2  s .  co  m
 * @param warnMessage Warning message
 * @return true if feedbacktext class is found
 * @throws XmlException If an error occurs.
 */
private boolean parseDivNodes(NodeList divElements, String warnMessage) throws XmlException {
    boolean feedBackDivFound = false;
    try {
        for (int i = 0; divElements != null && i < divElements.getLength(); i++) {
            Node divNode = divElements.item(i);
            Node classNode = divNode.getAttributes().getNamedItem("class");

            if (classNode != null && classNode.getNodeValue().equalsIgnoreCase("feedbacktext")) {
                // found feedback div
                feedBackDivFound = true;

                Node firstChild = divNode.getFirstChild();
                Document doc = divNode.getOwnerDocument();

                Node warningNode = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(new InputSource(
                                new StringReader("<div class=\"error-msg\">" + warnMessage + "</div>")))
                        .getFirstChild();
                warningNode = doc.importNode(warningNode, true);
                if (firstChild == null) {
                    divNode.appendChild(warningNode);
                } else {
                    warningNode = divNode.insertBefore(warningNode, firstChild);
                }
                //
                break;
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error processing divNodes " + e);
    }
    return feedBackDivFound;
}

From source file:com.wfreitas.camelsoap.SoapClient.java

/**
 * Clone a collection node./*  w w w  .  j a  v  a  2  s. c om*/
 * <p/>
 * Note we have to frig with the OGNL expressions for collections/arrays because the
 * collection entry is represented by [0], [1] etc in the OGNL expression, not the actual
 * element name on the DOM e.g. collection node "order/items/item" (where "item" is the
 * actual collection entry) maps to the OGNL expression "order.items[0]" etc.
 *
 * @param element    The collection/array "entry" sub-branch.
 * @param cloneCount The number of times it needs to be cloned.
 * @param ognl       The OGNL expression for the collection/array. Not including the
 *                   indexing part.
 */
private void cloneCollectionTemplateElement(Element element, int cloneCount, String ognl) {
    if (element == null) {
        return;
    }

    Node insertPoint = element.getNextSibling();
    Node parent = element.getParentNode();

    element.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
            OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB, ognl + "[0]");
    for (int i = 0; i < cloneCount; i++) {
        Element clone = (Element) element.cloneNode(true);

        clone.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS, OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + IS_CLONE_ATTRIB,
                "true");
        clone.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
                OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB,
                ognl + "[" + Integer.toString(i + 1) + "]");
        if (insertPoint == null) {
            parent.appendChild(clone);
        } else {
            parent.insertBefore(clone, insertPoint);
        }
    }
}

From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java

private void addDefaultIntellectualRights(Document doc) throws TransformerException {
    NodeList contacts = getContacts(doc);
    Element intellectualRightsElement = doc.createElement("intellectualRights");
    Element paraElement = doc.createElement("para");
    paraElement.appendChild(doc.createTextNode(INTELLECTUAL_RIGHTS_TEXT));
    intellectualRightsElement.appendChild(paraElement);
    Node datasetNode = getDatasetNode(doc);

    /* /*from  w  ww  .  jav a  2  s  .  co m*/
     * Determine where to insert the intellectualRights element. This
     * depends on the presence of nearby optional elements.
     */
    String insertBefore = null;
    if (hasElement(doc, DISTRIBUTION_PATH)) {
        insertBefore = DISTRIBUTION_PATH;
    } else if (hasElement(doc, COVERAGE_PATH)) {
        insertBefore = COVERAGE_PATH;
    } else if (hasElement(doc, PURPOSE_PATH)) {
        insertBefore = PURPOSE_PATH;
    } else if (hasElement(doc, MAINTENANCE_PATH)) {
        insertBefore = MAINTENANCE_PATH;
    } else {
        insertBefore = CONTACT_PATH;
    }

    NodeList insertNodeList = getElementNodeList(doc, insertBefore);
    Node insertNode = insertNodeList.item(0);
    datasetNode.insertBefore(intellectualRightsElement, insertNode);
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * Inserts the specified node./*  w  ww. ja va 2  s  . c o  m*/
 *
 * @param parentNode the path pointing to the origin node.
 * @param beforeNode the path pointing to the node before which a clone of the
 *               origin node will be inserted.
 * @return 
 */
public Node insertNode(Node parentNode, Node originNode, Node beforeNode) throws XFormsException {
    // insert a deep clone of 'origin' node before 'before' node. if
    // 'before' node is null, the clone will be appended to 'parent' node.
    ModelItem miOrigin = getModelItem(originNode);
    Node insertedNode;
    if (originNode.getNodeType() == Node.ATTRIBUTE_NODE) {
        insertedNode = this.instanceDocument.importNode(originNode, true);
        ((Element) parentNode).setAttributeNode((Attr) insertedNode);
    } else {
        insertedNode = parentNode.insertBefore(this.instanceDocument.importNode(originNode, true), beforeNode);
    }
    String canonPath = DOMUtil.getCanonicalPath(insertedNode);

    ModelItem insertedModelItem = getModelItem(insertedNode);
    insertedModelItem.getDeclarationView().setDatatype(miOrigin.getDeclarationView().getDatatype());
    insertedModelItem.getDeclarationView().setConstraints(miOrigin.getDeclarationView().getConstraints());

    // get canonical path for inserted node
    String canonicalPath;
    if (beforeNode != null || originNode.getNodeType() == Node.ATTRIBUTE_NODE) {
        canonicalPath = BindingResolver.getCanonicalPath(insertedNode);
    } else {
        Node lastChild = ((DocumentTraversal) instanceDocument)
                .createTreeWalker(parentNode, NodeFilter.SHOW_ALL, null, false).lastChild();
        canonicalPath = BindingResolver.getCanonicalPath(lastChild);
    }

    String[] canonicalParts = XPathUtil.getNodesetAndPredicates(canonicalPath);

    if (originNode.hasChildNodes()) {
        setDatatypeOnChilds(originNode, insertedNode);
    }

    // dispatch internal betterform event (for instant repeat updating)
    HashMap map = new HashMap();
    map.put("nodeset", canonicalParts[0]);
    map.put("position", canonicalParts.length > 1 ? canonicalParts[1] : "1");
    map.put("canonPath", canonPath);
    this.container.dispatch(this.target, BetterFormEventNames.NODE_INSERTED, map);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug(
                this + " insert node: instance data after manipulation" + toString(this.instanceDocument));
    }

    return insertedNode;
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * Receive scoEntrynode to modify it/*from   w  w w  .  ja  va  2  s.c o  m*/
 * 
 * @param node
 * @param document
 */
public static void changeScoEntry(Node node, org.w3c.dom.Document document) {
    if (node.getNodeName().equals("scoEntry")) {
        /**
         * for each scoEntry must create scoEntryAddress node
         * 
         */
        // adding the title...scoEntry/scoEntryTitle
        if (node.getChildNodes().item(1) != null
                && node.getChildNodes().item(1).getNodeName().equals("scoEntryTitle")) {
            Node scoEntryAddress = document.createElement("scoEntryAddress");

            // create the scoEntryAddress node
            Node scoEntryCode = document.createElement("scoEntryCode");

            ((Element) scoEntryCode).setAttribute("modelIdentCode", modelic);
            ((Element) scoEntryCode).setAttribute("scormContentPackageNumber", PackageNumber);
            ((Element) scoEntryCode).setAttribute("scormContentPackageIssuer", PackageIssuer);
            ((Element) scoEntryCode).setAttribute("scormContentPackageVolume", PackageVolume);
            scoEntryAddress.appendChild(scoEntryCode);

            // create the scoEntryStatus node
            Node scoEntryStatus = document.createElement("scoEntryStatus");
            // status
            Node status = document.createElement("security");
            ((Element) status).setAttribute("securityClassification", securityClassification);
            // qualityAssurance

            Node qualityAssuranceNode = qualityAssurance.cloneNode(true);
            scoEntryStatus.appendChild(qualityAssuranceNode);

            // adding address and status
            node.insertBefore(scoEntryStatus, node.getChildNodes().item(1));
            node.insertBefore(scoEntryAddress, node.getChildNodes().item(1));

            // move the title under the scoEntryAddress section
            scoEntryAddress.appendChild(node.getChildNodes().item(3));
        }
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }/*w  w w.j  a v a2 s  . c  o m*/
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Add a named and namespaced XML element to the document as a sibling element
 * that precedes the position of this builder node, and return the builder node
 * representing the new child./*from   www .  jav  a  2s  .c om*/
 *
 * @param name
 * the name of the XML element.
 * @param namespaceURI
 * a namespace URI
 *
 * @return
 * a builder node representing the new child.
 *
 * @throws IllegalStateException
 * if you attempt to add a sibling element to a node where there are already
 * one or more siblings that are text nodes.
 */
public XMLBuilder elementBefore(String name, String namespaceURI) {
    Node parentNode = this.xmlNode.getParentNode();
    assertElementContainsNoOrWhitespaceOnlyTextNodes(parentNode);

    Element newElement = (namespaceURI == null ? getDocument().createElement(name)
            : getDocument().createElementNS(namespaceURI, name));

    // Insert new element before the current element
    parentNode.insertBefore(newElement, this.xmlNode);
    // Return a new builder node pointing at the new element
    return new XMLBuilder(newElement, null);
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/*  w  w  w  .ja v a  2s  .c o  m*/
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //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();
    }

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

    /// Variable stuff
    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");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            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();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}