Example usage for org.w3c.dom Node getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public byte[] generateDispensationDocumentFromPrescription(byte[] bytes, List<ViewResult> lines,
        List<ViewResult> dispensedLines, SpiritUserClientDto doctor, User user) {
    byte[] bytesED = null;
    try {//w ww .  java 2s.c  om
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(new ByteArrayInputStream(bytes));

        XPath xpath = XPathFactory.newInstance().newXPath();

        // TODO change effective time
        // TODO change language code to fit dispenser
        // TODO change OID, have to use country b OID
        // TODO author must be the dispenser not the prescriber
        // TODO custodian and legal authenticator should be not copied from ep doc
        // TODO

        // fixes 
        // First I have to check if exists in order not to create it
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "state", "N/A");

        // add telecom to patient role
        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "state",
                "N/A");

        // add street Address Line
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "streetAddressLine", "N/A");

        // add City
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "city", "N/A");
        // add postalcode
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "postalCode", "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr",
                "streetAddressLine", "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "city",
                "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr",
                "postalCode", "N/A");

        changeNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization", "name",
                "N/A");

        fixNode(dom, xpath,
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/author/assignedAuthor/representedOrganization/addr",
                "postalCode", "N/A");

        String ful_ext = "";
        String ful_root = "";
        XPathExpression ful1 = xpath.compile("/ClinicalDocument/component/structuredBody/component/section/id");
        NodeList fulRONodes = (NodeList) ful1.evaluate(dom, XPathConstants.NODESET);

        if (fulRONodes.getLength() > 0) {
            for (int t = 0; t < fulRONodes.getLength(); t++) {
                Node AddrNode = fulRONodes.item(t);
                try {
                    ful_ext = AddrNode.getAttributes().getNamedItem("extension").getNodeValue() + "";
                    ful_root = AddrNode.getAttributes().getNamedItem("root").getNodeValue() + "";
                } catch (Exception e) {
                }
            }
        }

        // fix infullfillment
        XPathExpression rootNodeExpr = xpath.compile("/ClinicalDocument");
        Node rootNode = (Node) rootNodeExpr.evaluate(dom, XPathConstants.NODE);

        try {
            Node infulfilment = null;
            XPathExpression salRO = xpath.compile("/ClinicalDocument/inFulfillmentOf");
            NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET);
            if (salRONodes.getLength() == 0) {
                XPathExpression salAddr = xpath.compile("/ClinicalDocument/relatedDocument");
                NodeList salAddrNodes = (NodeList) salAddr.evaluate(dom, XPathConstants.NODESET);
                if (salAddrNodes.getLength() > 0) {
                    for (int t = 0; t < salAddrNodes.getLength(); t++) {
                        Node AddrNode = salAddrNodes.item(t);
                        Node order = dom.createElement("inFulfillmentOf");
                        //legalNode.appendChild(order);
                        /*
                         * <relatedDocument typeCode="XFRM">
                        *      <parentDocument>
                        *      <id extension="2601010002.pdf.ep.52105899467.52105899468:39" root="2.16.840.1.113883.2.24.2.30"/>
                        *                     </parentDocument>
                        *                  </relatedDocument>
                         * 
                         * 
                         */
                        //Node order1 = dom.createElement("order");
                        Node order1 = dom.createElement("relatedDocument");
                        Node parentDoc = dom.createElement("parentDocument");
                        addAttribute(dom, parentDoc, "typeCode", "XFRM");
                        order1.appendChild(parentDoc);

                        Node orderNode = dom.createElement("id");
                        addAttribute(dom, orderNode, "extension", ful_ext);
                        addAttribute(dom, orderNode, "root", ful_root);
                        parentDoc.appendChild(orderNode);
                        rootNode.insertBefore(order, AddrNode);
                        infulfilment = rootNode.cloneNode(true);

                    }
                }
            }
        } catch (Exception e) {
            _log.error("Error fixing node inFulfillmentOf ...");
        }

        XPathExpression Telecom = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization");
        NodeList TelecomNodes = (NodeList) Telecom.evaluate(dom, XPathConstants.NODESET);
        if (TelecomNodes.getLength() == 0) {
            for (int t = 0; t < TelecomNodes.getLength(); t++) {
                Node TelecomNode = TelecomNodes.item(t);
                Node telecom = dom.createElement("telecom");
                addAttribute(dom, telecom, "use", "WP");
                addAttribute(dom, telecom, "value", "mailto:demo@epsos.eu");
                TelecomNode.insertBefore(telecom, TelecomNodes.item(0));
            }
        }

        // header xpaths
        XPathExpression clinicalDocExpr = xpath.compile("/ClinicalDocument");
        Node clinicalDocNode = (Node) clinicalDocExpr.evaluate(dom, XPathConstants.NODE);
        if (clinicalDocNode != null) {
            addAttribute(dom, clinicalDocNode, "xmlns", "urn:hl7-org:v3");
            addAttribute(dom, clinicalDocNode, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            addAttribute(dom, clinicalDocNode, "xsi:schemaLocation",
                    "urn:hl7-org:v3 CDASchema/CDA_extended.xsd");
            addAttribute(dom, clinicalDocNode, "classCode", "DOCCLIN");
            addAttribute(dom, clinicalDocNode, "moodCode", "EVN");
        }

        XPathExpression docTemplateIdExpr = xpath.compile("/ClinicalDocument/templateId");
        XPathExpression docCodeExpr = xpath.compile("/ClinicalDocument/code[@codeSystemName='"
                + XML_LOINC_SYSTEM + "' and @codeSystem='" + XML_LOINC_CODESYSTEM + "']");
        XPathExpression docTitleExpr = xpath.compile("/ClinicalDocument/title");

        // change templateId / LOINC code / title to dispensation root code
        NodeList templateIdNodes = (NodeList) docTemplateIdExpr.evaluate(dom, XPathConstants.NODESET);
        if (templateIdNodes != null) {
            for (int t = 0; t < templateIdNodes.getLength(); t++) {
                Node templateIdNode = templateIdNodes.item(t);
                templateIdNode.getAttributes().getNamedItem("root").setNodeValue(XML_DISPENSATION_TEMPLATEID);

                if (t > 0)
                    templateIdNode.getParentNode().removeChild(templateIdNode); // remove extra templateId nodes
            }
        }
        Node codeNode = (Node) docCodeExpr.evaluate(dom, XPathConstants.NODE);
        if (codeNode != null) {
            if (codeNode.getAttributes().getNamedItem("code") != null)
                codeNode.getAttributes().getNamedItem("code").setNodeValue(XML_DISPENSATION_LOINC_CODE);
            if (codeNode.getAttributes().getNamedItem("displayName") != null)
                codeNode.getAttributes().getNamedItem("displayName").setNodeValue("eDispensation");
            if (codeNode.getAttributes().getNamedItem("codeSystemName") != null)
                codeNode.getAttributes().getNamedItem("codeSystemName")
                        .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEMNAME);
            if (codeNode.getAttributes().getNamedItem("codeSystem") != null)
                codeNode.getAttributes().getNamedItem("codeSystem")
                        .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEM);
        }
        Node titleNode = (Node) docTitleExpr.evaluate(dom, XPathConstants.NODE);
        if (titleNode != null) {
            titleNode.setTextContent(XML_DISPENSATION_TITLE);
        }

        XPathExpression sectionExpr = xpath
                .compile("/ClinicalDocument/component/structuredBody/component/section[templateId/@root='"
                        + XML_PRESCRIPTION_ENTRY_TEMPLATEID + "']");
        XPathExpression substanceExpr = xpath.compile("entry/substanceAdministration");
        XPathExpression idExpr = xpath.compile("id");
        NodeList prescriptionNodes = (NodeList) sectionExpr.evaluate(dom, XPathConstants.NODESET);

        //   substanceAdministration.appendChild(newAuthorNode);

        if (prescriptionNodes != null && prescriptionNodes.getLength() > 0) {

            // calculate list of prescription ids to keep
            // calculate list of prescription lines to keep
            Set<String> prescriptionIdsToKeep = new HashSet<String>();
            Set<String> materialIdsToKeep = new HashSet<String>();
            HashMap<String, Node> materialReferences = new HashMap<String, Node>();
            if (dispensedLines != null && dispensedLines.size() > 0) {
                for (int i = 0; i < dispensedLines.size(); i++) {
                    ViewResult d_line = dispensedLines.get(i);
                    materialIdsToKeep.add((String) d_line.getField10());
                    prescriptionIdsToKeep.add((String) d_line.getField9());
                }
            }

            Node structuredBodyNode = null;
            for (int p = 0; p < prescriptionNodes.getLength(); p++) {
                // for each one of the prescription nodes (<component> tags) check if their id belongs to the list of prescription Ids to keep in dispensation document
                Node sectionNode = prescriptionNodes.item(p);
                Node idNode = (Node) idExpr.evaluate(sectionNode, XPathConstants.NODE);
                String prescrId = idNode.getAttributes().getNamedItem("extension").getNodeValue();
                if (prescriptionIdsToKeep.contains(prescrId)) {
                    NodeList substanceAdministrationNodes = (NodeList) substanceExpr.evaluate(sectionNode,
                            XPathConstants.NODESET);
                    if (substanceAdministrationNodes != null && substanceAdministrationNodes.getLength() > 0) {
                        for (int s = 0; s < substanceAdministrationNodes.getLength(); s++) {
                            // for each of the entries (substanceAdministration tags) within this prescription node
                            // check if the materialid in question is one of the dispensed ones, else do nothing
                            Node substanceAdministration = (Node) substanceAdministrationNodes.item(s);
                            Node substanceIdNode = (Node) idExpr.evaluate(substanceAdministration,
                                    XPathConstants.NODE);
                            String materialid = "";
                            try {
                                materialid = substanceIdNode.getAttributes().getNamedItem("extension")
                                        .getNodeValue();
                            } catch (Exception e) {
                                _log.error("error setting materialid");
                            }

                            if (materialIdsToKeep.contains(materialid)) {
                                // if the materialid is one of the dispensed ones, keep the substanceAdminstration node intact,
                                // as it will be used as an entryRelationship in the dispensation entry we will create
                                Node entryRelationshipNode = dom.createElement("entryRelationship");
                                addAttribute(dom, entryRelationshipNode, "typeCode", "REFR");
                                addTemplateId(dom, entryRelationshipNode, XML_DISPENSTATION_ENTRY_REFERENCEID);

                                entryRelationshipNode.appendChild(substanceAdministration);
                                materialReferences.put(materialid, entryRelationshipNode);

                            }
                        }
                    }
                }

                //    Then delete this node, dispensed lines will be written afterwards
                Node componentNode = sectionNode.getParentNode(); // component
                structuredBodyNode = componentNode.getParentNode(); // structuredBody
                structuredBodyNode.removeChild(componentNode);

            }

            // at the end of this for loop, prescription lines are removed from the document, and materialReferences hashmap contains
            // a mapping from materialId to ready nodes containing the entry relationship references to the corresponding prescription lines
            Node dispComponent = dom.createElement("component");
            Node dispSection = dom.createElement("section");

            addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_PARENT_TEMPLATEID);
            addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_TEMPLATEID);

            Node dispIdNode = dom.createElement("id");
            //addAttribute(dom, dispIdNode, "root", prescriptionIdsToKeep.iterator().next());
            addAttribute(dom, dispIdNode, "root", ful_root);
            addAttribute(dom, dispIdNode, "extension", ful_ext);
            dispSection.appendChild(dispIdNode);

            Node sectionCodeNode = dom.createElement("code");
            addAttribute(dom, sectionCodeNode, "code", "60590-7");
            addAttribute(dom, sectionCodeNode, "displayName", XML_DISPENSATION_TITLE);
            addAttribute(dom, sectionCodeNode, "codeSystem", XML_DISPENSATION_LOINC_CODESYSTEM);
            addAttribute(dom, sectionCodeNode, "codeSystemName", XML_DISPENSATION_LOINC_CODESYSTEMNAME);
            dispSection.appendChild(sectionCodeNode);

            Node title = dom.createElement("title");
            title.setTextContent(XML_DISPENSATION_TITLE);
            dispSection.appendChild(title);

            Node text = dom.createElement("text");
            Node textContent = this.generateDispensedLinesHtml(dispensedLines, db);
            textContent = textContent.cloneNode(true);
            dom.adoptNode(textContent);
            text.appendChild(textContent);
            dispSection.appendChild(text);
            dispComponent.appendChild(dispSection);

            structuredBodyNode.appendChild(dispComponent);

            for (int i = 0; i < dispensedLines.size(); i++) {
                ViewResult d_line = dispensedLines.get(i);
                String materialid = (String) d_line.getField10();
                // for each dispensed line create a dispensation entry in the document, and use the entryRelationship calculated above
                Node entry = dom.createElement("entry");
                Node supply = dom.createElement("supply");
                addAttribute(dom, supply, "classCode", "SPLY");
                addAttribute(dom, supply, "moodCode", "EVN");

                // add templateId tags
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE1);
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE2);
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE3);

                // add id tag
                Node supplyId = dom.createElement("id");
                addAttribute(dom, supplyId, "root", XML_DISPENSATION_ENTRY_SUPPLY_ID_ROOT);
                addAttribute(dom, supplyId, "extension", (String) d_line.getField1());
                supply.appendChild(supplyId);

                // add quantity tag
                Node quantity = dom.createElement("quantity");
                String nrOfPacks = (String) d_line.getField8();
                nrOfPacks = nrOfPacks.trim();
                String value = nrOfPacks;
                String unit = "1";
                if (nrOfPacks.indexOf(" ") != -1) {
                    value = nrOfPacks.substring(0, nrOfPacks.indexOf(" "));
                    unit = nrOfPacks.substring(nrOfPacks.indexOf(" ") + 1);
                }
                addAttribute(dom, quantity, "value", (String) d_line.getField7());
                addAttribute(dom, quantity, "unit", (String) d_line.getField12());
                supply.appendChild(quantity);

                // add product tag
                addProductTag(dom, supply, d_line, materialReferences.get(materialid));

                // add performer tag
                addPerformerTag(dom, supply, doctor);

                // add entryRelationship tag
                supply.appendChild(materialReferences.get(materialid));

                // add substitution relationship tag
                if (d_line.getField3() != null && ((Boolean) d_line.getField3()).booleanValue()) {
                    Node substitutionNode = dom.createElement("entryRelationship");
                    addAttribute(dom, substitutionNode, "typeCode", "COMP");
                    Node substanceAdminNode = dom.createElement("substanceAdministration");
                    addAttribute(dom, substanceAdminNode, "classCode", "SBADM");
                    addAttribute(dom, substanceAdminNode, "moodCode", "INT");

                    Node seqNode = dom.createElement("doseQuantity");
                    addAttribute(dom, seqNode, "value", "1");
                    addAttribute(dom, seqNode, "unit", "1");
                    substanceAdminNode.appendChild(seqNode);
                    substitutionNode.appendChild(substanceAdminNode);
                    // changed quantity
                    if (lines.get(0).getField21().equals(d_line.getField7())) {

                    }
                    // changed name
                    if (lines.get(0).getField11().equals(d_line.getField2())) {

                    }
                    supply.appendChild(substitutionNode);
                }
                entry.appendChild(supply);
                dispSection.appendChild(entry);
            }

        }

        // copy author tag from eprescription
        XPathExpression authorExpr = xpath.compile("/ClinicalDocument/author");
        Node oldAuthorNode = (Node) authorExpr.evaluate(dom, XPathConstants.NODE);
        Node newAuthorNode = oldAuthorNode.cloneNode(true);

        XPathExpression substExpr = xpath.compile(
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration");
        NodeList substNodes = (NodeList) substExpr.evaluate(dom, XPathConstants.NODESET);

        XPathExpression entryRelExpr = xpath.compile(
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/entryRelationship");
        NodeList entryRelNodes = (NodeList) entryRelExpr.evaluate(dom, XPathConstants.NODESET);
        Node entryRelNode = (Node) entryRelExpr.evaluate(dom, XPathConstants.NODE);

        if (substNodes != null) {
            //            for (int t=0; t<substNodes.getLength(); t++)
            //            {         
            int t = 0;
            Node substNode = substNodes.item(t);
            substNode.insertBefore(newAuthorNode, entryRelNode);
            //            }
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(dom);
        transformer.transform(source, result);

        String xmlString = result.getWriter().toString();
        bytesED = xmlString.getBytes();
        System.out.println(xmlString);

    } catch (Exception e) {
        _log.error(e.getMessage());
    }

    return bytesED;
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

/**
 * Builds a menu tree, typically used to present the menu in the menu ;)
 *
 * @param user           The current user
 * @param getterSettings If given - build tree from these settings
 * @return A DOM document containing the menu tree
 *///from ww w  .  jav  a  2s .c o  m
public Document getMenusForAdmin(User user, MenuGetterSettings getterSettings) {

    List<Integer> paramValues = new ArrayList<Integer>(2);
    StringBuffer sqlMenus = new StringBuffer(MENU_SELECT);

    if (getterSettings.hasMenuKeys()) {
        int[] menuKeys = getterSettings.getMenuKeys();
        sqlMenus.append(" WHERE ");
        sqlMenus.append("men_lKey IN (");
        for (int i = 0; i < menuKeys.length; i++) {
            if (i > 0) {
                sqlMenus.append(',');
            }
            sqlMenus.append(menuKeys[i]);
        }
        sqlMenus.append(')');
    }

    // Selekterer bare menyer som brukeren har create eller administrate p
    if (user != null) {
        MenuCriteria criteria = getterSettings.getMenuCriteria();
        getSecurityHandler().appendMenuSQL(user, sqlMenus, criteria);
    }

    Hashtable<String, Element> hashtable_menus = new Hashtable<String, Element>();

    Connection con = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    Document doc = XMLTool.createDocument("menus");
    try {
        con = getConnection();

        statement = con.prepareStatement(sqlMenus.toString());
        JDBCUtil.addValuesToPreparedStatement(statement, paramValues);

        try {

            // Frst selekterer vi ut menus...
            resultSet = statement.executeQuery();

            while (resultSet.next()) {

                int curMenuKey = resultSet.getInt("men_lKey");

                Element element_Menu = getMenuData(doc.getDocumentElement(), curMenuKey);
                Element accessRights = XMLTool.createElement(doc, element_Menu, "accessrights");
                getSecurityHandler().appendAccessRightsOnDefaultMenuItem(user, curMenuKey, accessRights, true);

                XMLTool.createElement(doc, element_Menu, "menuitems");
                // Lagrer referansen til kategori-elementet for raskt oppslag til senere bruk
                hashtable_menus.put(String.valueOf(curMenuKey), element_Menu);
            }
        } finally {
            close(resultSet);
            resultSet = null;
            close(statement);
            statement = null;
        }

        MenuItemCriteria menuItemCriteria = getterSettings.getMenuItemCriteria();
        if (!menuItemCriteria.getDisableMenuItemLoadingForUnspecified() || menuItemCriteria.getMenuKey() >= 0) {
            // Legger s til menuitems til menyene
            Hashtable<String, Element> hashtable_MenuItems = appendMenuItemsBySettings(user, doc,
                    hashtable_menus, getterSettings);

            // Hvis brukeren bare vil ha et fullt tree fra gitte menuItemKey,
            // s m vi fjerne alle ssken-noder til foreldre-nodene
            if (getterSettings.hasOnlyChildrenFromThisMenuItemKey()) {
                Element curMenuItem = hashtable_MenuItems
                        .get(getterSettings.getMenuItemKeyAsInteger().toString());

                while (curMenuItem != null) {

                    XMLTool.removeAllSiblings(curMenuItem);

                    // Move to first parent node (menuitems)
                    curMenuItem = (Element) curMenuItem.getParentNode();
                    // Exit loop if we have reached the top
                    if ("menus".equals(curMenuItem.getNodeName())) {
                        break;
                    }

                    // Move to next parent node (menuitem/menu)
                    if (curMenuItem != null) {
                        curMenuItem = (Element) curMenuItem.getParentNode();
                    }
                }
            }

            if (getterSettings.hasTagParentsOfThisMenuItem()) {

                Element menuItem = hashtable_MenuItems
                        .get(getterSettings.getTagParentsOfThisMenuItemKeyAsInteger().toString());
                Node parent = menuItem.getParentNode();
                String tagName = getterSettings.getTagParentsOfThisMenuItemTagName();
                String tagValue = getterSettings.getTagParentsOfThisMenuItemTagValue();
                while (parent != null) {
                    if (parent instanceof Element) {
                        ((Element) parent).setAttribute(tagName, tagValue);
                    }
                    parent = parent.getParentNode();
                }
            }
        }

        if (!getterSettings.hasMenuKeys()) {
            String sqlMenuItems;
            sqlMenuItems = "SELECT DISTINCT mei_men_lKey FROM tMenuItem JOIN tMenu on tMenuItem.mei_men_lKey = tMenu.men_lKey ";
            sqlMenuItems = getSecurityHandler().appendMenuItemSQL(user, sqlMenuItems, menuItemCriteria);

            statement = con.prepareStatement(sqlMenuItems);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                String menuKey = resultSet.getString("mei_men_lKey");
                if (!hashtable_menus.containsKey(menuKey)) {
                    Element menuElement = getMenuData(doc.getDocumentElement(), Integer.parseInt(menuKey));

                    hashtable_menus.put(menuKey, menuElement);
                }
            }
        }
    } catch (SQLException sqle) {
        String message = "Failed to get the menus: %t";
        VerticalEngineLogger.error(this.getClass(), 0, message, sqle);
        doc = XMLTool.createDocument("categories");
    } finally {
        close(resultSet);
        close(statement);
        close(con);
    }

    return doc;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/portfolio/{portfolio-id}")
@GET//  w  w  w  .  j  av a2  s  . c o m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip",
        MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId,
        @QueryParam("group") Integer group, @QueryParam("resources") String resource,
        @QueryParam("files") String files, @QueryParam("export") String export,
        @QueryParam("lang") String lang) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    Response response = null;
    try {
        String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0,
                this.label, resource, "", ui.subId).toString();

        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }

        if (response == null) {
            Date time = new Date();
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();

            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition",
                        "attachment; filename = \"" + code + "-" + time + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP

                /// Temp file in temp directory
                File tempDir = new File(System.getProperty("java.io.tmpdir", null));
                File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir);

                FileOutputStream fos = new FileOutputStream(tempZip);
                ZipOutputStream zos = new ZipOutputStream(fos);
                //               BufferedOutputStream bos = new BufferedOutputStream(zos);

                /// zos.setComment("Some comment");

                /// Write xml file to zip
                ZipEntry ze = new ZipEntry(portfolioUuid + ".xml");
                zos.putNextEntry(ze);

                byte[] bytes = portfolio.getBytes("UTF-8");
                zos.write(bytes);

                zos.closeEntry();

                /// Find all fileid/filename
                XPath xPath = XPathFactory.newInstance().newXPath();
                String filterRes = "//asmResource/fileid";
                NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

                /// Direct link to data
                // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

                /*
                String langatt = "";
                if( lang != null )
                   langatt = "?lang="+lang;
                else
                   langatt = "?lang=fr";
                //*/

                /// Fetch all files
                for (int i = 0; i < nodelist.getLength(); ++i) {
                    Node res = nodelist.item(i);
                    Node p = res.getParentNode(); // resource -> container
                    Node gp = p.getParentNode(); // container -> context
                    Node uuidNode = gp.getAttributes().getNamedItem("id");
                    String uuid = uuidNode.getTextContent();

                    String filterName = "./filename[@lang and text()]";
                    NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p,
                            XPathConstants.NODESET);
                    String filename = "";
                    if (textList.getLength() != 0) {
                        Element fileNode = (Element) textList.item(0);
                        filename = fileNode.getTextContent();
                        lang = fileNode.getAttribute("lang");
                        if ("".equals(lang))
                            lang = "fr";
                    }

                    String servlet = httpServletRequest.getRequestURI();
                    servlet = servlet.substring(0, servlet.indexOf("/", 7));
                    String server = httpServletRequest.getServerName();
                    int port = httpServletRequest.getServerPort();
                    //                  "http://"+ server + /resources/resource/file/ uuid ? lang= size=
                    // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";
                    String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid
                            + "?lang=" + lang;
                    HttpGet get = new HttpGet(url);

                    // Transfer sessionid so that local request still get security checked
                    HttpSession session = httpServletRequest.getSession(true);
                    get.addHeader("Cookie", "JSESSIONID=" + session.getId());

                    // Send request
                    CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse ret = client.execute(get);
                    HttpEntity entity = ret.getEntity();

                    // Put specific name for later recovery
                    if ("".equals(filename))
                        continue;
                    int lastDot = filename.lastIndexOf(".");
                    if (lastDot < 0)
                        lastDot = 0;
                    String filenameext = filename.substring(0); /// find extension
                    int extindex = filenameext.lastIndexOf(".");
                    filenameext = uuid + "_" + lang + filenameext.substring(extindex);

                    // Save it to zip file
                    //                  int length = (int) entity.getContentLength();
                    InputStream content = entity.getContent();

                    //                  BufferedInputStream bis = new BufferedInputStream(entity.getContent());

                    ze = new ZipEntry(filenameext);
                    try {
                        int totalread = 0;
                        zos.putNextEntry(ze);
                        int inByte;
                        byte[] buf = new byte[4096];
                        //                     zos.write(bytes,0,inByte);
                        while ((inByte = content.read(buf)) != -1) {
                            totalread += inByte;
                            zos.write(buf, 0, inByte);
                        }
                        System.out.println("FILE: " + filenameext + " -> " + totalread);
                        content.close();
                        //                     bis.close();
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EntityUtils.consume(entity);
                    ret.close();
                    client.close();
                }

                zos.close();
                fos.close();

                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();

                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
                        .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip")
                        .build();

                // Temp file cleanup
                tempZip.delete();
            } else {
                //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
                //              String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString();
                if (portfolio.equals("faux")) {

                    throw new RestWebApplicationException(Status.FORBIDDEN,
                            "Vous n'avez pas les droits necessaires");
                }

                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();

                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found",
                Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        if (dataProvider != null)
            dataProvider.disconnect();
    }

    return response;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

private String writeNode(Node node, String portfolioUuid, String portfolioModelId, int userId, int ordrer,
        String forcedUuid, String forcedUuidParent, int sharedResParent, int sharedNodeResParent, boolean isPut)
        throws Exception {
    String uuid = "";
    String originUuid = null;//  ww  w.j a v a 2s  . c om
    String parentUuid = null;
    String nodeChildrenUuid = null;
    String modelNodeUuid = null;
    int sharedRes = 0;
    int sharedNode = 0;
    int sharedNodeRes = 0;

    String sharedResUuid = null;
    String sharedNodeUuid = null;
    String sharedNodeResUuid = null;

    String metadata = "";
    String metadataWad = "";
    String metadataEpm = "";
    String asmType = null;
    String xsiType = null;
    String semtag = null;
    String format = null;
    String label = null;
    String code = null;
    String descr = null;
    String semanticTag = null;

    String nodeRole = null;

    String access = null;

    int returnValue = 0;

    if (node == null)
        return null;

    if (node.getNodeName().equals("portfolio")) {
        // On n'attribue pas d'uuid sur la balise portfolio
    } else {
        try {
            if (node.getAttributes().getNamedItem("id") != null) {
                originUuid = node.getAttributes().getNamedItem("id").getNodeValue();
                if (originUuid.length() > 0) {
                    uuid = node.getAttributes().getNamedItem("id").getNodeValue();
                } else
                    uuid = UUID.randomUUID().toString();
            } else
                uuid = UUID.randomUUID().toString();
        } catch (Exception ex) {
            uuid = UUID.randomUUID().toString();
        }
    }

    // Si uuid forc, alors on ne tient pas compte de l'uuid indiqu dans le xml
    if (forcedUuid != null) {
        uuid = forcedUuid;
        parentUuid = forcedUuidParent;
    } else if (forcedUuidParent != null) {
        // Dans le cas d'un uuid parent forc => POST => on gnre un UUID
        if (uuid == null)
            uuid = UUID.randomUUID().toString();
        parentUuid = forcedUuidParent;
    } else {
        try {

            if (node.getParentNode().getAttributes().getNamedItem("id") != null)
                if (node.getParentNode().getAttributes().getNamedItem("id").getNodeValue().length() > 0)
                    parentUuid = node.getParentNode().getAttributes().getNamedItem("id").getNodeValue();
        } catch (Exception ex) {
            //parentUuid = UUID.randomUUID().toString();
        }
    }

    try {
        if (node.getNodeName() != null)
            asmType = node.getNodeName();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("xsi_type") != null)
            xsiType = node.getAttributes().getNamedItem("xsi_type").getNodeValue().trim();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("semtag") != null)
            semtag = node.getAttributes().getNamedItem("semtag").getNodeValue().trim();
    } catch (Exception ex) {

    }
    try {
        if (node.getAttributes().getNamedItem("format") != null)
            format = node.getAttributes().getNamedItem("format").getNodeValue().trim();
    } catch (Exception ex) {
    }

    // Si id dfini, alors on crit en base
    //TODO Transactionnel noeud+enfant
    NodeList children = null;
    try {
        children = node.getChildNodes();
        // On parcourt une premire fois les enfants pour rcuperer la liste  crire en base
        int j = 0;
        for (int i = 0; i < children.getLength(); i++) {
            //if(!children.item(i).getNodeName().equals("#text"))
            //   nodeChildren.add(children.item(i).getAttributes().getNamedItem("id").getNodeValue());
            if (!children.item(i).getNodeName().equals("#text")) {
                if (children.item(i).getNodeName().equals("metadata-wad")) {

                    metadataWad = DomUtils.getNodeAttributesString(children.item(i));// " attr1=\"wad1\" attr2=\"wad2\" ";
                    metadataWad = processMeta(userId, metadataWad);

                    // Gestion de la securit intgre
                    //
                    Node metadataWadNode = children.item(i);
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("access") != null) {
                            //if(access.equalsIgnoreCase("public") || access.contains("public"))
                            //   credential.postGroupRight("all",uuid,Credential.READ,portfolioUuid,userId);
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("seenoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("seenoderoles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("delnoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("delnoderoles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("editnoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(metadataWadNode.getAttributes()
                                    .getNamedItem("editnoderoles").getNodeValue(), " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("submitnoderoles") != null) {
                            StringTokenizer tokens = new StringTokenizer(metadataWadNode.getAttributes()
                                    .getNamedItem("submitnoderoles").getNodeValue(), " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }
                    //
                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("seeresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("seeresroles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("delresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("delresroles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("editresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(
                                    metadataWadNode.getAttributes().getNamedItem("editresroles").getNodeValue(),
                                    " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        if (metadataWadNode.getAttributes().getNamedItem("submitresroles") != null) {
                            StringTokenizer tokens = new StringTokenizer(metadataWadNode.getAttributes()
                                    .getNamedItem("submitresroles").getNodeValue(), " ");
                            while (tokens.hasMoreElements()) {

                                nodeRole = tokens.nextElement().toString();
                                credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid,
                                        userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                    try {
                        Node actionroles = metadataWadNode.getAttributes().getNamedItem("actionroles");
                        if (actionroles != null) {
                            /// Format pour l'instant: actionroles="sender:1,2;responsable:4"
                            StringTokenizer tokens = new StringTokenizer(actionroles.getNodeValue(), ";");
                            while (tokens.hasMoreElements()) {
                                nodeRole = tokens.nextElement().toString();
                                StringTokenizer data = new StringTokenizer(nodeRole, ":");
                                String role = data.nextElement().toString();
                                String actions = data.nextElement().toString();
                                credential.postGroupRight(role, uuid, actions, portfolioUuid, userId);
                            }
                        }
                    } catch (Exception ex) {
                    }

                } else if (children.item(i).getNodeName().equals("metadata-epm")) {
                    metadataEpm = DomUtils.getNodeAttributesString(children.item(i));
                } else if (children.item(i).getNodeName().equals("metadata")) {
                    String tmpSharedRes = "";
                    try {
                        tmpSharedRes = children.item(i).getAttributes().getNamedItem("sharedResource")
                                .getNodeValue();
                    } catch (Exception ex) {
                    }

                    String tmpSharedNode = "";
                    try {
                        tmpSharedNode = children.item(i).getAttributes().getNamedItem("sharedNode")
                                .getNodeValue();
                    } catch (Exception ex) {
                    }

                    String tmpSharedNodeRes = "";
                    try {
                        tmpSharedNodeRes = children.item(i).getAttributes().getNamedItem("sharedNodeResource")
                                .getNodeValue();
                    } catch (Exception ex) {
                    }

                    try {
                        semanticTag = children.item(i).getAttributes().getNamedItem("semantictag")
                                .getNodeValue();
                        /*
                          else if(children.item(i).getNodeName().equals("semanticTag"))
                          {
                              semanticTag = DomUtils.getInnerXml(children.item(i));
                          }
                          //*/
                    } catch (Exception ex) {
                    }

                    if (tmpSharedRes.equalsIgnoreCase("y"))
                        sharedRes = 1;
                    if (tmpSharedNode.equalsIgnoreCase("y"))
                        sharedNode = 1;
                    if (tmpSharedNodeRes.equalsIgnoreCase("y"))
                        sharedNodeRes = 1;

                    metadata = DomUtils.getNodeAttributesString(children.item(i));
                }
                // On vrifie si l'enfant n'est pas un lement de type code, label ou descr
                else if (children.item(i).getNodeName().equals("label")) {
                    label = DomUtils.getInnerXml(children.item(i));
                } else if (children.item(i).getNodeName().equals("code")) {
                    code = DomUtils.getInnerXml(children.item(i));
                } else if (children.item(i).getNodeName().equals("description")) {
                    descr = DomUtils.getInnerXml(children.item(i));
                } else if (children.item(i).getAttributes() != null) {
                    if (children.item(i).getAttributes().getNamedItem("id") != null) {

                        if (nodeChildrenUuid == null)
                            nodeChildrenUuid = "";
                        if (j > 0)
                            nodeChildrenUuid += ",";
                        nodeChildrenUuid += children.item(i).getAttributes().getNamedItem("id").getNodeValue()
                                .toString();

                        j++;
                    }
                }
            }
        }
    } catch (Exception ex) {
        // Pas d'enfants
        ex.printStackTrace();
    }

    //System.out.println(uuid+":"+node.getNodeName()+":"+parentUuid+":"+nodeChildrenUuid);

    // Si on est au debut de l'arbre, on stocke la dfinition du portfolio
    // dans la table portfolio
    if (uuid != null && node.getParentNode() != null) {
        if (node.getNodeName().equals("asmRoot")) {
            // On retrouve le code cach dans une ressource. blegh
            NodeList childs = node.getChildNodes();
            for (int k = 0; k < childs.getLength(); ++k) {
                Node child = childs.item(k);
                if ("asmResource".equals(child.getNodeName())) {
                    NodeList grandchilds = child.getChildNodes();
                    for (int l = 0; l < grandchilds.getLength(); ++l) {
                        Node gc = grandchilds.item(l);
                        if ("code".equals(gc.getNodeName())) {
                            code = DomUtils.getInnerXml(gc);
                            break;
                        }
                    }
                }
                if (code != null)
                    break;
            }
        } else if (portfolioUuid == null)
            throw new Exception("Il manque la balise asmRoot !!");
    }

    // Si on instancie un portfolio  partir d'un modle
    // Alors on gre les share*
    if (portfolioModelId != null) {
        if (sharedNode == 1) {
            sharedNodeUuid = originUuid;
        }

    } else
        modelNodeUuid = null;

    if (uuid != null && !node.getNodeName().equals("portfolio") && !node.getNodeName().equals("asmResource"))
        returnValue = insertMySqlNode(uuid, parentUuid, nodeChildrenUuid, asmType, xsiType, sharedRes,
                sharedNode, sharedNodeRes, sharedResUuid, sharedNodeUuid, sharedNodeResUuid, metadata,
                metadataWad, metadataEpm, semtag, semanticTag, label, code, descr, format, ordrer, userId,
                portfolioUuid);

    // Si le parent a t forc, cela veut dire qu'il faut mettre  jour les enfants du parent
    //TODO
    // MODIF : On le met  jour tout le temps car dans le cas d'un POST les uuid ne sont pas connus  l'avance
    //if(forcedUuidParent!=null)
    updateMysqlNodeChildren(forcedUuidParent);

    // Si le noeud est de type asmResource, on stocke le innerXML du noeud
    if (node.getNodeName().equals("asmResource")) {
        if (portfolioModelId != null) {
            if (xsiType.equals("nodeRes") && sharedNodeResParent == 1) {
                sharedNodeResUuid = originUuid;
                insertMysqlResource(sharedNodeResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else if (!xsiType.equals("context") && !xsiType.equals("nodeRes") && sharedResParent == 1) {

                sharedResUuid = originUuid;
                insertMysqlResource(sharedResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else {
                insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                        sharedNodeResParent, sharedResParent, userId);
            }
        } else
            insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                    sharedNodeResParent, sharedResParent, userId);

    }

    // On vrifie enfin si on a import des ressources fichiers dont l'UID correspond
    // pour remplacer l'UID d'origine par l'UID gener
    if (portfolioRessourcesImportUuid.size() > 0) {
        for (int k = 0; k < portfolioRessourcesImportUuid.size(); k++) {
            if (portfolioRessourcesImportUuid.get(k).equals(originUuid)) {
                String portfolioRessourcesDestPath = portfolioRessourcesImportPath.get(k).replace(originUuid,
                        uuid);
                File f = new File(portfolioRessourcesImportPath.get(k));
                f.renameTo(new File(portfolioRessourcesDestPath));
                //System.out.println();
                updateMysqlFileUuid(originUuid, uuid);
            }

        }
    }

    // On reparcourt ensuite les enfants pour continuer la recursivit
    //      if(children!=null && sharedNode!=1)
    if (children != null) {
        int k = 0;
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getAttributes() != null) {
                String nodeName = child.getNodeName();
                if ("asmRoot".equals(nodeName) || "asmStructure".equals(nodeName) || "asmUnit".equals(nodeName)
                        || "asmUnitStructure".equals(nodeName) || "asmUnitContent".equals(nodeName)
                        || "asmContext".equals(nodeName)) {
                    //System.out.println("uid="+uuid+":"+",enfant_uuid="+children.item(i).getAttributes().getNamedItem("id")+",ordre="+k);
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, null, uuid, sharedRes,
                            sharedNodeRes, isPut);
                    k++;
                } else if ("asmResource".equals(nodeName)) // Les asmResource pose problme dans l'ordre des noeuds
                {
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, null, uuid, sharedRes,
                            sharedNodeRes, isPut);
                }
            }
        }
    }

    return uuid;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

private String writeNode(Node node, String portfolioUuid, String portfolioModelId, int userId, int ordrer,
        String forcedUuid, String forcedUuidParent, int sharedResParent, int sharedNodeResParent,
        boolean rewriteId, HashMap<String, String> resolve) throws Exception {
    String uuid = "";
    String originUuid = null;//from  w w  w  .j  a  v a  2 s .  co m
    String parentUuid = null;
    String modelNodeUuid = null;
    int sharedRes = 0;
    int sharedNode = 0;
    int sharedNodeRes = 0;

    String sharedResUuid = null;
    String sharedNodeUuid = null;
    String sharedNodeResUuid = null;

    String metadata = "";
    String metadataWad = "";
    String metadataEpm = "";
    String asmType = null;
    String xsiType = null;
    String semtag = null;
    String format = null;
    String label = null;
    String code = null;
    String descr = null;
    String semanticTag = null;

    String nodeRole = null;

    String access = null;

    int returnValue = 0;

    if (node == null)
        return null;

    if (node.getNodeName().equals("portfolio")) {
        // On n'attribue pas d'uuid sur la balise portfolio
    } else {
    }

    String currentid = "";
    Node idAtt = node.getAttributes().getNamedItem("id");
    if (idAtt != null) {
        String tempId = idAtt.getNodeValue();
        if (tempId.length() > 0)
            currentid = tempId;
    }

    // Si uuid forc, alors on ne tient pas compte de l'uuid indiqu dans le xml
    if (rewriteId) // On garde les uuid par dfaut
    {
        uuid = currentid;
    } else {
        uuid = forcedUuid;
    }

    if (resolve != null) // Mapping old id -> new id
        resolve.put(currentid, uuid);

    if (forcedUuidParent != null) {
        // Dans le cas d'un uuid parent forc => POST => on gnre un UUID
        parentUuid = forcedUuidParent;
    }

    /// Rcupration d'autre infos
    try {
        if (node.getNodeName() != null)
            asmType = node.getNodeName();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("xsi_type") != null)
            xsiType = node.getAttributes().getNamedItem("xsi_type").getNodeValue().trim();
    } catch (Exception ex) {
    }
    try {
        if (node.getAttributes().getNamedItem("semtag") != null)
            semtag = node.getAttributes().getNamedItem("semtag").getNodeValue().trim();
    } catch (Exception ex) {

    }
    try {
        if (node.getAttributes().getNamedItem("format") != null)
            format = node.getAttributes().getNamedItem("format").getNodeValue().trim();
    } catch (Exception ex) {
    }

    // Si id dfini, alors on crit en base
    //TODO Transactionnel noeud+enfant
    NodeList children = null;
    try {
        children = node.getChildNodes();
        // On parcourt une premire fois les enfants pour rcuperer la liste  crire en base
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);

            if ("#text".equals(child.getNodeName()))
                continue;

            //if(!children.item(i).getNodeName().equals("#text"))
            //   nodeChildren.add(children.item(i).getAttributes().getNamedItem("id").getNodeValue());
            if (children.item(i).getNodeName().equals("metadata-wad")) {
                metadataWad = DomUtils.getNodeAttributesString(children.item(i));// " attr1=\"wad1\" attr2=\"wad2\" ";
                //               metadataWad = processMeta(userId, metadataWad);

                // Gestion de la securit intgre
                //
                Node metadataWadNode = children.item(i);
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("access") != null) {
                        //if(access.equalsIgnoreCase("public") || access.contains("public"))
                        //   credential.postGroupRight("all",uuid,Credential.READ,portfolioUuid,userId);
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("seenoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("seenoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {

                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("delnoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("delnoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {

                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("editnoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("editnoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {

                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("submitnoderoles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("submitnoderoles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }
                //
                try {
                    if (metadataWadNode.getAttributes().getNamedItem("seeresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("seeresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.READ, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("delresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("delresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.DELETE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("editresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("editresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.WRITE, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    if (metadataWadNode.getAttributes().getNamedItem("submitresroles") != null) {
                        StringTokenizer tokens = new StringTokenizer(
                                metadataWadNode.getAttributes().getNamedItem("submitresroles").getNodeValue(),
                                " ");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            credential.postGroupRight(nodeRole, uuid, Credential.SUBMIT, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try {
                    Node actionroles = metadataWadNode.getAttributes().getNamedItem("actionroles");
                    if (actionroles != null) {
                        /// Format pour l'instant: actionroles="sender:1,2;responsable:4"
                        StringTokenizer tokens = new StringTokenizer(actionroles.getNodeValue(), ";");
                        while (tokens.hasMoreElements()) {
                            nodeRole = tokens.nextElement().toString();
                            StringTokenizer data = new StringTokenizer(nodeRole, ":");
                            String role = data.nextElement().toString();
                            String actions = data.nextElement().toString();
                            credential.postGroupRight(role, uuid, actions, portfolioUuid, userId);
                        }
                    }
                } catch (Exception ex) {
                }

                try /// TODO:  l'intgration avec sakai/LTI
                {
                    Node notifyroles = metadataWadNode.getAttributes().getNamedItem("notifyroles");
                    if (notifyroles != null) {
                        /// Format pour l'instant: actionroles="sender:1,2;responsable:4"
                        StringTokenizer tokens = new StringTokenizer(notifyroles.getNodeValue(), " ");
                        String merge = "";
                        if (tokens.hasMoreElements())
                            merge = tokens.nextElement().toString();
                        while (tokens.hasMoreElements())
                            merge += "," + tokens.nextElement().toString();

                        postNotifyRoles(userId, portfolioUuid, uuid, merge);
                    }
                } catch (Exception ex) {
                }

            } else if (children.item(i).getNodeName().equals("metadata-epm")) {
                metadataEpm = DomUtils.getNodeAttributesString(children.item(i));
            } else if (children.item(i).getNodeName().equals("metadata")) {
                try {
                    String publicatt = children.item(i).getAttributes().getNamedItem("public").getNodeValue();
                    if ("Y".equals(publicatt))
                        setPublicState(userId, portfolioUuid, true);
                    else if ("N".equals(publicatt))
                        setPublicState(userId, portfolioUuid, false);
                } catch (Exception ex) {
                }

                String tmpSharedRes = "";
                try {
                    tmpSharedRes = children.item(i).getAttributes().getNamedItem("sharedResource")
                            .getNodeValue();
                } catch (Exception ex) {
                }

                String tmpSharedNode = "";
                try {
                    tmpSharedNode = children.item(i).getAttributes().getNamedItem("sharedNode").getNodeValue();
                } catch (Exception ex) {
                }

                String tmpSharedNodeRes = "";
                try {
                    tmpSharedNodeRes = children.item(i).getAttributes().getNamedItem("sharedNodeResource")
                            .getNodeValue();
                } catch (Exception ex) {
                }

                try {
                    semanticTag = children.item(i).getAttributes().getNamedItem("semantictag").getNodeValue();
                    /*
                    else if(children.item(i).getNodeName().equals("semanticTag"))
                    {
                       semanticTag = DomUtils.getInnerXml(children.item(i));
                    }
                    //*/
                } catch (Exception ex) {
                }

                if (tmpSharedRes.equalsIgnoreCase("y"))
                    sharedRes = 1;
                if (tmpSharedNode.equalsIgnoreCase("y"))
                    sharedNode = 1;
                if (tmpSharedNodeRes.equalsIgnoreCase("y"))
                    sharedNodeRes = 1;

                metadata = DomUtils.getNodeAttributesString(children.item(i));
            }
            // On vrifie si l'enfant n'est pas un lement de type code, label ou descr
            else if (children.item(i).getNodeName().equals("label")) {
                label = DomUtils.getInnerXml(children.item(i));
            } else if (children.item(i).getNodeName().equals("code")) {
                code = DomUtils.getInnerXml(children.item(i));
            } else if (children.item(i).getNodeName().equals("description")) {
                descr = DomUtils.getInnerXml(children.item(i));
            } else if (children.item(i).getAttributes() != null) {
                /*
                if(children.item(i).getAttributes().getNamedItem("id")!=null)
                {
                        
                   if(nodeChildrenUuid==null) nodeChildrenUuid = "";
                   if(j>0) nodeChildrenUuid += ",";
                   nodeChildrenUuid += children.item(i).getAttributes().getNamedItem("id").getNodeValue().toString();
                        
                   j++;
                }
                //*/
            }
        }
    } catch (Exception ex) {
        // Pas d'enfants
        ex.printStackTrace();
    }

    //System.out.println(uuid+":"+node.getNodeName()+":"+parentUuid+":"+nodeChildrenUuid);

    // Si on est au debut de l'arbre, on stocke la dfinition du portfolio
    // dans la table portfolio
    if (uuid != null && node.getParentNode() != null) {
        // On retrouve le code cach dans les ressources. blegh
        NodeList childs = node.getChildNodes();
        for (int k = 0; k < childs.getLength(); ++k) {
            Node child = childs.item(k);
            if ("asmResource".equals(child.getNodeName())) {
                NodeList grandchilds = child.getChildNodes();
                for (int l = 0; l < grandchilds.getLength(); ++l) {
                    Node gc = grandchilds.item(l);
                    if ("code".equals(gc.getNodeName())) {
                        code = DomUtils.getInnerXml(gc);
                        break;
                    }
                }
            }
            if (code != null)
                break;
        }

        if (node.getNodeName().equals("asmRoot")) {
        } else if (portfolioUuid == null)
            throw new Exception("Il manque la balise asmRoot !!");
    }

    // Si on instancie un portfolio  partir d'un modle
    // Alors on gre les share*
    if (portfolioModelId != null) {
        if (sharedNode == 1) {
            sharedNodeUuid = originUuid;
        }
    } else
        modelNodeUuid = null;

    if (uuid != null && !node.getNodeName().equals("portfolio") && !node.getNodeName().equals("asmResource"))
        returnValue = insertMySqlNode(uuid, parentUuid, "", asmType, xsiType, sharedRes, sharedNode,
                sharedNodeRes, sharedResUuid, sharedNodeUuid, sharedNodeResUuid, metadata, metadataWad,
                metadataEpm, semtag, semanticTag, label, code, descr, format, ordrer, userId, portfolioUuid);

    // Si le parent a t forc, cela veut dire qu'il faut mettre  jour les enfants du parent
    //TODO
    // MODIF : On le met  jour tout le temps car dans le cas d'un POST les uuid ne sont pas connus  l'avance
    //if(forcedUuidParent!=null)

    // Si le noeud est de type asmResource, on stocke le innerXML du noeud
    if (node.getNodeName().equals("asmResource")) {
        if (portfolioModelId != null) {
            if (xsiType.equals("nodeRes") && sharedNodeResParent == 1) {
                sharedNodeResUuid = originUuid;
                insertMysqlResource(sharedNodeResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else if (!xsiType.equals("context") && !xsiType.equals("nodeRes") && sharedResParent == 1) {

                sharedResUuid = originUuid;
                insertMysqlResource(sharedResUuid, parentUuid, xsiType, DomUtils.getInnerXml(node),
                        portfolioModelId, sharedNodeResParent, sharedResParent, userId);
            } else {
                insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                        sharedNodeResParent, sharedResParent, userId);
            }
        } else
            insertMysqlResource(uuid, parentUuid, xsiType, DomUtils.getInnerXml(node), portfolioModelId,
                    sharedNodeResParent, sharedResParent, userId);

    }

    // On vrifie enfin si on a import des ressources fichiers dont l'UID correspond
    // pour remplacer l'UID d'origine par l'UID gener
    /*
    if(portfolioRessourcesImportUuid.size()>0)
    {
       for(int k=0;k<portfolioRessourcesImportUuid.size();k++)
       {
    if(portfolioRessourcesImportUuid.get(k).equals(originUuid))
    {
       String portfolioRessourcesDestPath = portfolioRessourcesImportPath.get(k).replace(originUuid, uuid);
       File f = new File(portfolioRessourcesImportPath.get(k));
       f.renameTo(new File(portfolioRessourcesDestPath));
       //System.out.println();
       updateMysqlFileUuid(originUuid,uuid);
    }
            
       }
    }
    //*/

    // On reparcourt ensuite les enfants pour continuer la recursivit
    //      if(children!=null && sharedNode!=1)
    if (children != null) {
        int k = 0;
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            String childId = null;
            if (!rewriteId)
                childId = UUID.randomUUID().toString();

            if (child.getAttributes() != null) {
                String nodeName = child.getNodeName();
                if ("asmRoot".equals(nodeName) || "asmStructure".equals(nodeName) || "asmUnit".equals(nodeName)
                        || "asmUnitStructure".equals(nodeName) || "asmUnitContent".equals(nodeName)
                        || "asmContext".equals(nodeName)) {
                    //System.out.println("uid="+uuid+":"+",enfant_uuid="+children.item(i).getAttributes().getNamedItem("id")+",ordre="+k);
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, childId, uuid, sharedRes,
                            sharedNodeRes, rewriteId, resolve);
                    k++;
                } else if ("asmResource".equals(nodeName)) // Les asmResource pose problme dans l'ordre des noeuds
                {
                    writeNode(child, portfolioUuid, portfolioModelId, userId, k, childId, uuid, sharedRes,
                            sharedNodeRes, rewriteId, resolve);
                }
            }
        }
    }

    updateMysqlNodeChildren(forcedUuidParent);

    return uuid;
}

From source file:com.codeandpop.android.multilevelmenufragment.MultilevelMenuActivity.java

protected void replaceMenuFragment(Node menuItem) throws Exception {
    MultilevelMenuFragment menuFragment = new MultilevelMenuFragment();
    List<MultilevelMenuItem> menuItems = menu.parse(menuItem);
    ArrayAdapter<MultilevelMenuItem> adapter = getMultilevelMenuViewAdapter(menuItems);
    menuFragment.setListAdapter(adapter);

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

    if (menuItem.getParentNode() == menuItem.getOwnerDocument()) {
        ft.add(getMultilevelMenuFragmentContainerResourceId(), menuFragment);
    } else {//from   ww w. j a  v  a  2  s .  c  o m
        ft.replace(getMultilevelMenuFragmentContainerResourceId(), menuFragment);
        ft.addToBackStack(null); // Enable back button to go back to the previous menu
    }
    ft.commit();
}

From source file:de.uni_weimar.m18.anatomiederstadt.LevelPageFragment.java

private void populateLayoutFromXML() {
    try {/* w ww  .jav a2  s.  c o m*/
        LevelStateManager stateManager = ((AnatomieDerStadtApplication) getActivity().getApplicationContext())
                .getStateManager(getActivity());
        Document levelXml = stateManager.getLevelXML();
        Element rootElement = levelXml.getDocumentElement();
        Log.v(LOG_TAG, "RootElement: " + rootElement.getTagName());
        NodeList pageList = rootElement.getElementsByTagName("page");
        Node page = null; // = pageList.item(mPageNum);
        for (int i = 0; i < pageList.getLength(); ++i) {
            if (pageList.item(i).getAttributes().getNamedItem("id").getNodeValue().equals(mPageId)) {
                page = pageList.item(i);
                // save current page id in shared preferences
                SharedPreferences sharedPref = PreferenceManager
                        .getDefaultSharedPreferences(getActivity().getApplicationContext());
                Editor editor = sharedPref.edit();
                editor.putBoolean(getString(R.string.user_is_playing_boolean), true);
                editor.putString(getString(R.string.resume_base_path), mBasePath);
                editor.putString(getString(R.string.resume_page_id), mPageId);
                editor.commit();
            }
        }
        if (page == null) {
            Log.e(LOG_TAG, "Error! Page with id " + mPageId + " could not be found in level.xml!");
            return;
        }

        Log.v(LOG_TAG, "page: nodename: " + page.getNodeName());
        NodeList childNodes = page.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); ++i) {
            Log.v(LOG_TAG, "at page-childnode " + Integer.toString(i));
            Node item = childNodes.item(i);
            if (item.getNodeName().equals("text")) {
                Log.v(LOG_TAG, "text node found - value: " + item.getTextContent());
                addText(item.getTextContent());
            }
            if (item.getNodeName().equals("image")) {
                NamedNodeMap attributes = item.getAttributes();
                Node src = attributes.getNamedItem("src");
                addImage(src.getNodeValue());
            }
            if (item.getNodeName().equals("quiz")) {
                String target = "";
                String correct = "";
                String button1 = "";
                String button2 = "";
                String button3 = "";
                String button4 = "";
                String hint = "";
                String points = "";
                String penalty = "";

                NodeList quizParamaters = item.getChildNodes();
                for (int k = 0; k < quizParamaters.getLength(); ++k) {
                    Node child = quizParamaters.item(k);
                    String quizParameter = child.getNodeName();
                    switch (quizParameter) {
                    case "target":
                        target = child.getTextContent();
                        break;
                    case "correct":
                        correct = child.getTextContent();
                        break;
                    case "button1":
                        button1 = child.getTextContent();
                        break;
                    case "button2":
                        button2 = child.getTextContent();
                        break;
                    case "button3":
                        button3 = child.getTextContent();
                        break;
                    case "button4":
                        button4 = child.getTextContent();
                        break;
                    case "hint":
                        hint = child.getTextContent();
                        break;
                    case "points":
                        points = child.getTextContent();
                        break;
                    case "penalty":
                        penalty = child.getTextContent();
                        break;
                    default:
                        break;
                    //throw new IllegalArgumentException("Invalid quiz parameter" + quizParameter);
                    }
                }
                addQuiz4Element(target, correct, button1, button2, button3, button4, hint, points, penalty);
            }
            /*
            if (item.getNodeName().equals("quiz")) {
            NamedNodeMap attributes = item.getAttributes();
            Node button1 = attributes.getNamedItem("button1");
            Node button2 = attributes.getNamedItem("button2");
            Node button3 = attributes.getNamedItem("button3");
            Node button4 = attributes.getNamedItem("button4");
            Node correctAnswer = attributes.getNamedItem("correctAnswer");
            Node correctTarget = attributes.getNamedItem("correctTarget");
                    
            addQuizMultipleChoice(button1.getNodeValue(), button2.getNodeValue(),
                    button3.getNodeValue(), button4.getNodeValue(),
                    Integer.parseInt(correctAnswer.getNodeValue()),
                    correctTarget.getNodeValue());
            }
            */
            if (item.getNodeName().equals("latex")) {
                addLatex(item.getTextContent());
            }
            if (item.getNodeName().equals("slider")) {
                NamedNodeMap attributes = item.getAttributes();
                Node min = attributes.getNamedItem("min");
                Node max = attributes.getNamedItem("max");
                Node granularity = attributes.getNamedItem("granularity");
                Node suffix = attributes.getNamedItem("suffix");
                Node var = attributes.getNamedItem("var");
                addSlider(Integer.parseInt(min.getNodeValue()), Integer.parseInt(max.getNodeValue()),
                        Float.parseFloat(granularity.getNodeValue()), suffix.getNodeValue(),
                        var.getNodeValue());
            }
            if (item.getNodeName().equals("location")) {
                NamedNodeMap attributes = item.getAttributes();
                Node latitude = attributes.getNamedItem("latitude");
                Node longitude = attributes.getNamedItem("longitude");
                Node target = attributes.getNamedItem("target");
                addLocation(latitude.getNodeValue(), longitude.getNodeValue(), target.getNodeValue());
            }
            if (item.getNodeName().equals("button")) {
                NamedNodeMap attributes = item.getAttributes();
                Node caption = attributes.getNamedItem("caption");
                Node target = attributes.getNamedItem("target");
                addButton(caption.getNodeValue(), target.getNodeValue());
            }
            if (item.getNodeName().equals("evaluate")) {
                NamedNodeMap attributes = item.getAttributes();
                Node var = attributes.getNamedItem("var");
                String expression = item.getTextContent();
                evaluateMath(var.getNodeValue(), expression);
            }
            if (item.getNodeName().equals("var")) {
                NamedNodeMap attributes = item.getAttributes();
                Node name = attributes.getNamedItem("name");
                storeVariable(name.getNodeValue(), item.getTextContent());
            }
            if (item.getNodeName().equals("input")) {
                NamedNodeMap attributes = item.getAttributes();
                Node buttonCaption = attributes.getNamedItem("caption");
                Node target = attributes.getNamedItem("target");
                Node var = attributes.getNamedItem("var");
                addInput(buttonCaption.getNodeValue(), var.getNodeValue(), target.getNodeValue());
            }
            if (item.getNodeName().equals("inputcheck")) {
                NamedNodeMap attributes = item.getAttributes();
                Node buttonCaption = attributes.getNamedItem("caption");
                Node target = attributes.getNamedItem("target");
                Node var = attributes.getNamedItem("var");
                Node correct = attributes.getNamedItem("correct");
                Node points = attributes.getNamedItem("points");
                Node hint = attributes.getNamedItem("hint");
                addInputCheck(buttonCaption.getNodeValue(), var.getNodeValue(), target.getNodeValue(),
                        correct.getNodeValue(), points.getNodeValue(), hint.getNodeValue());
            }
            if (item.getNodeName().equals("quizmulti")) {
                NamedNodeMap attributes = item.getAttributes();
                Node target = attributes.getNamedItem("target");
                Node points = attributes.getNamedItem("points");
                //NodeList optionsList = item.getElementsByTagName("option");
                Node parent = item.getParentNode();
                ArrayList<String> options = new ArrayList<>();
                ArrayList<String> correctList = new ArrayList<>();
                if (parent instanceof Element) {
                    final Element e = (Element) parent;
                    NodeList optionsList = e.getElementsByTagName("option");
                    for (int k = 0; k < optionsList.getLength(); ++k) {
                        Node option = optionsList.item(k);
                        if (option.getAttributes().getNamedItem("correct").getNodeValue().equals("true"))
                            correctList.add("true");
                        else
                            correctList.add("false");
                        options.add(option.getTextContent());
                    }
                    addQuizMulti(options, correctList, target.getNodeValue(), points.getNodeValue());
                }
            }
            if (item.getNodeName().equals("evalpoints")) {
                NamedNodeMap attributes = item.getAttributes();
                Node var = attributes.getNamedItem("var");
                Node correct = attributes.getNamedItem("correct");
                Node step = attributes.getNamedItem("step");
                Node points = attributes.getNamedItem("points");
                Node penalty = attributes.getNamedItem("penalty");
                evaluatePoints(var.getNodeValue(), correct.getNodeValue(), step.getNodeValue(),
                        points.getNodeValue(), penalty.getNodeValue());
            }
            if (item.getNodeName().equals("score")) {
                addScore();
            }
            if (item.getNodeName().equals("survey")) {
                registerSurveyClickHandler();
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error! Exception " + e.getMessage());
        e.printStackTrace();
        new MaterialDialog.Builder(getActivity()).title("Error")
                .content("Fehler whrend des Verarbeitens der Level-Datei!\n" + e.getMessage())
                .positiveText("OK").show();
    }
    commitChildFragments();
}

From source file:nl.b3p.viewer.stripes.SldActionBean.java

private void addFilterToExistingSld() throws Exception {
    Filter f = CQL.toFilter(filter);

    f = (Filter) f.accept(new ChangeMatchCase(false), null);

    if (featureTypeName == null) {
        featureTypeName = layer;/*w ww  . ja va2 s .  c om*/
    }
    FeatureTypeConstraint ftc = sldFactory.createFeatureTypeConstraint(featureTypeName, f, new Extent[] {});

    if (newSld == null) {

        SLDTransformer sldTransformer = new SLDTransformer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        sldTransformer.transform(ftc, bos);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document sldXmlDoc = db.parse(new ByteArrayInputStream(sldXml));

        Document ftcDoc = db.parse(new ByteArrayInputStream(bos.toByteArray()));

        String sldVersion = sldXmlDoc.getDocumentElement().getAttribute("version");
        if ("1.1.0".equals(sldVersion)) {
            // replace sld:FeatureTypeName element generated by GeoTools
            // by se:FeatureTypeName
            NodeList sldFTNs = ftcDoc.getElementsByTagNameNS(NS_SLD, "FeatureTypeName");
            if (sldFTNs.getLength() == 1) {
                Node sldFTN = sldFTNs.item(0);
                Node seFTN = ftcDoc.createElementNS(NS_SE, "FeatureTypeName");
                seFTN.setTextContent(sldFTN.getTextContent());
                sldFTN.getParentNode().replaceChild(seFTN, sldFTN);
            }
        }

        // Ignore namespaces to tackle both SLD 1.0.0 and SLD 1.1.0
        // Add constraint to all NamedLayers, not only to the layer specified
        // in layers parameter

        NodeList namedLayers = sldXmlDoc.getElementsByTagNameNS(NS_SLD, "NamedLayer");
        for (int i = 0; i < namedLayers.getLength(); i++) {
            Node namedLayer = namedLayers.item(i);

            // Search where to insert the FeatureTypeConstraint from our ftcDoc

            // Insert LayerFeatureConstraints after sld:Name, se:Name or se:Description
            // and before sld:NamedStyle or sld:UserStyle so search backwards.
            // If we find an existing LayerFeatureConstraints, use that
            NodeList childs = namedLayer.getChildNodes();
            Node insertBefore = null;
            Node layerFeatureConstraints = null;
            int j = childs.getLength() - 1;
            do {
                Node child = childs.item(j);

                if ("LayerFeatureConstraints".equals(child.getLocalName())) {
                    layerFeatureConstraints = child;
                    break;
                }
                if ("Description".equals(child.getLocalName()) || "Name".equals(child.getLocalName())) {
                    break;
                }
                insertBefore = child;
                j--;
            } while (j >= 0);
            Node featureTypeConstraint = sldXmlDoc.adoptNode(ftcDoc.getDocumentElement().cloneNode(true));
            if (layerFeatureConstraints == null) {
                layerFeatureConstraints = sldXmlDoc.createElementNS(NS_SLD, "LayerFeatureConstraints");
                layerFeatureConstraints.appendChild(featureTypeConstraint);
                namedLayer.insertBefore(layerFeatureConstraints, insertBefore);
            } else {
                layerFeatureConstraints.appendChild(featureTypeConstraint);
            }
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        DOMSource source = new DOMSource(sldXmlDoc);
        bos = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(bos);
        t.transform(source, result);
        sldXml = bos.toByteArray();
    }
}

From source file:npm.modules.java

public void deletesite(Document doc, int index) throws Exception {
    Node nNode = doc.getElementsByTagName("site").item(index);
    nNode.getParentNode().removeChild(nNode);
    savexml(doc);/*w  w  w. j  a v a  2  s  .  c o  m*/
}

From source file:openblocks.yacodeblocks.BlockSaveFileTest.java

private void assertStringContainsOnlyAsciiCharacters(String s, String description, Node node) {
    if (s != null) {
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch > '~') {
                // Build a failure message that tells where the non-ascii character was found.
                StringBuilder failureMessage = new StringBuilder();

                // Find the id attribute of the containing block.
                Node parent = node;
                while (parent != null) {
                    if (parent.getNodeName().equals("Block") && parent instanceof Element) {
                        String blockId = ((Element) parent).getAttribute("id");
                        failureMessage.append("In the Block whose id attribute is " + blockId + ", ");
                        break;
                    }/*from  w  w w  .  j  a  va2s  .c  o  m*/
                    if (parent instanceof Attr) {
                        parent = ((Attr) parent).getOwnerElement();
                    } else {
                        parent = parent.getParentNode();
                    }
                }

                if (failureMessage.length() == 0) {
                    failureMessage.append("The ");
                } else {
                    failureMessage.append("the ");
                }

                failureMessage.append(description).append(" of the ").append(describeNode(node))
                        .append(" contains the non-ascii character 0x").append(Integer.toHexString(ch))
                        .append(" at index ").append(i).append(": ").append(s).append(".");

                fail(failureMessage.toString());
            }
        }
    }
}