Example usage for org.w3c.dom Element cloneNode

List of usage examples for org.w3c.dom Element cloneNode

Introduction

In this page you can find the example usage for org.w3c.dom Element cloneNode.

Prototype

public Node cloneNode(boolean deep);

Source Link

Document

Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.

Usage

From source file:org.infoscoop.service.SearchEngineService.java

public String getSearchEngineXmlWithAcl() throws Exception {
    Searchengine entity = this.searchEngineDAO.select(SearchEngineDAO.SEARCHENGINE_FLAG_NOT_TEMP);
    if (entity == null) {
        log.error("searchengine not found.");
        return "";
    }/* w w w  . j  a  va 2s .  c  o m*/
    Document doc = entity.getDocument();
    Element root = doc.getDocumentElement();
    Node newRoot = root.cloneNode(true);
    Element defaultSearch = (Element) XPathAPI.selectSingleNode(newRoot, "defaultSearch");
    checkAcl(defaultSearch);
    Element rssSearch = (Element) XPathAPI.selectSingleNode(newRoot, "rssSearch");
    checkAcl(rssSearch);
    return XmlUtil.dom2String(newRoot);
}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

/**
 * Commiting temporary data.//from   www .  ja v  a 2s. c  o m
 * @param menuType topmenu|sidemenu
 * @param forceUpdateMap
 * @throws Exception
 */
public synchronized void commitMenu(String menuType, Map<String, List<ForceUpdateUserPref>> forceUpdateMap,
        List<String> forceDeleteList, List<String> editSitetopIdList) throws Exception {
    ISPrincipal p = SecurityController.getPrincipalByType("UIDPrincipal");
    String myUid = p.getName();

    Siteaggregationmenu currentEntity = this.siteAggregationMenuDAO.select(menuType);

    Element currentMenuEl = currentEntity.getElement();
    Document currentDoc = currentMenuEl.getOwnerDocument();

    // Get the tree that the user edited
    List<Siteaggregationmenu_temp> myTempList = this.siteAggregationMenuTempDAO.selectByTypeAndUser(menuType,
            myUid);

    checkError(myTempList, editSitetopIdList, menuType);

    // Merge
    Element siteTop;
    WidgetDAO dao = WidgetDAO.newInstance();
    List<Element> deleteSiteTopList = new ArrayList<Element>();
    Siteaggregationmenu_temp orderTemp = null;

    for (Siteaggregationmenu_temp tempEntity : myTempList) {
        if (tempEntity.getId().getSitetopid().equals(SiteAggregationMenuTempDAO.SITEMENU_ORDER_TEMP_ID)) {
            orderTemp = tempEntity;
            continue;
        }

        // Update last modified time
        tempEntity.setLastmodified(new Date());
        this.siteAggregationMenuTempDAO.update(tempEntity);

        siteTop = tempEntity.getElement();
        String siteTopId = tempEntity.getId().getSitetopid();
        Node currentSiteTopEl = XPathAPI.selectSingleNode(currentMenuEl, "site-top[@id=\"" + siteTopId + "\"]");

        // Import
        Node mergeEl = currentDoc.importNode(siteTop.cloneNode(true), true);

        if (siteTop.getAttributeNode("deleteFlag") != null) {
            // If the tree is deleted
            if (currentSiteTopEl != null)
                deleteSiteTopList.add((Element) currentSiteTopEl);
            continue;
        } else {
            if (currentSiteTopEl != null) {
                currentDoc.getDocumentElement().replaceChild(mergeEl, currentSiteTopEl);
            } else {
                currentDoc.getDocumentElement().appendChild(mergeEl);
            }
        }

        // Properties should not be updated if existing data is not changed.
        if (currentSiteTopEl == null)
            continue;

        //Properties of url and authType in current menu is added to Map.
        NodeList sites = siteTop.getElementsByTagName("site");
        for (int i = 0; i < sites.getLength(); i++) {
            Element site = (Element) sites.item(i);
            String type = site.getAttribute("type");
            if (type == null)
                continue;

            String menuId = site.getAttribute("id");
            List<ForceUpdateUserPref> updatePropList = forceUpdateMap.get(menuId);
            if (updatePropList == null || updatePropList.isEmpty())
                continue;

            NodeList properties = XPathAPI.selectNodeList(site, "properties/property");

            Map<String, String> propMap = new HashMap<String, String>();
            for (int j = 0; j < properties.getLength(); j++) {
                Element property = (Element) properties.item(j);
                String name = property.getAttribute("name");
                String value = property.getFirstChild() != null ? property.getFirstChild().getNodeValue() : "";
                propMap.put(name, value);
            }

            String title = null;
            String href = null;
            Map<String, ForceUpdateUserPref> upPropMap = new HashMap<String, ForceUpdateUserPref>();
            Set<ForceUpdateUserPref> removePropNames = new HashSet<ForceUpdateUserPref>();
            for (ForceUpdateUserPref prop : updatePropList) {
                if ("__MENU_TITLE__".equals(prop.name)) {
                    title = site.getAttribute("title");
                } else if ("__MENU_HREF__".equals(prop.name)) {
                    href = site.getAttribute("href");
                } else {
                    String value = propMap.get(prop.name);
                    prop.value = value;
                    if (value != null) {
                        upPropMap.put(prop.name, prop);
                    } else {
                        removePropNames.add(prop);
                    }
                }
            }

            if (title != null || href != null || upPropMap.size() > 0 || removePropNames.size() > 0)
                dao.updateWidgetProperties(menuId, title, href, upPropMap, removePropNames);
        }
    }

    for (String menuId : forceDeleteList) {
        dao.deleteWidgetByMenuId(menuId);
    }
    // Deleting tree
    for (Element deleteSiteTop : deleteSiteTopList) {
        AdminServiceUtil.removeSelf(deleteSiteTop);
    }

    // Changing order of tree
    if (orderTemp != null) {
        Element orderEl = orderTemp.getElement();
        NodeList orderSiteTopList = orderEl.getElementsByTagName("site-top");

        for (int i = 0; i < orderSiteTopList.getLength(); i++) {
            Element orderSiteTop = (Element) orderSiteTopList.item(i);
            Element targetNode = (Element) XPathAPI.selectSingleNode(currentMenuEl,
                    "site-top[@id=\"" + orderSiteTop.getAttribute("id") + "\"]");

            if (targetNode != null)
                targetNode.getParentNode().appendChild(targetNode);
        }
    }

    //Apply the change of menu to widget.
    currentEntity.setElement(currentMenuEl);
    this.siteAggregationMenuDAO.update(currentEntity);
}

From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java

/**
 * Alter content.xml, content.jar, content.xml.xz to:
 * remove default "Uncategorized" category, 
 * remove 3rd party associate sites, and 
 * add associate sites defined in site's pom.xml
 *
 * @param p2repository//from  ww w.  j  a va 2s .  com
 * @throws FileNotFoundException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws MojoFailureException
 */
private void alterContentJar(File p2repository) throws FileNotFoundException, IOException, SAXException,
        ParserConfigurationException, TransformerFactoryConfigurationError, TransformerConfigurationException,
        TransformerException, MojoFailureException {
    File contentJar = new File(p2repository, "content.jar");
    ZipInputStream contentStream = new ZipInputStream(new FileInputStream(contentJar));
    ZipEntry entry = null;
    Document contentDoc = null;
    boolean done = false;
    while (!done && (entry = contentStream.getNextEntry()) != null) {
        if (entry.getName().equals("content.xml")) {
            contentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(contentStream);
            Element repoElement = (Element) contentDoc.getElementsByTagName("repository").item(0);
            {
                NodeList references = repoElement.getElementsByTagName("references");
                // remove default references
                for (int i = 0; i < references.getLength(); i++) {
                    Node currentRef = references.item(i);
                    currentRef.getParentNode().removeChild(currentRef);
                }
                // add associateSites
                if (this.associateSites != null && this.associateSites.size() > 0
                        && this.referenceStrategy == ReferenceStrategy.embedReferences) {
                    Element refElement = contentDoc.createElement("references");
                    refElement.setAttribute("size", Integer.valueOf(2 * associateSites.size()).toString());
                    for (String associate : associateSites) {
                        Element rep0 = contentDoc.createElement("repository");
                        rep0.setAttribute("uri", associate);
                        rep0.setAttribute("url", associate);
                        rep0.setAttribute("type", "0");
                        rep0.setAttribute("options", "1");
                        refElement.appendChild(rep0);
                        Element rep1 = (Element) rep0.cloneNode(true);
                        rep1.setAttribute("type", "1");
                        refElement.appendChild(rep1);
                    }
                    repoElement.appendChild(refElement);
                }
            }
            // remove default "Uncategorized" category
            if (this.removeDefaultCategory) {
                Element unitsElement = (Element) repoElement.getElementsByTagName("units").item(0);
                NodeList units = unitsElement.getElementsByTagName("unit");
                for (int i = 0; i < units.getLength(); i++) {
                    Element unit = (Element) units.item(i);
                    String id = unit.getAttribute("id");
                    if (id != null && id.contains(".Default")) {
                        unit.getParentNode().removeChild(unit);
                    }
                }
                unitsElement.setAttribute("size",
                        Integer.toString(unitsElement.getElementsByTagName("unit").getLength()));
            }
            done = true;
        }
    }
    // .close and .closeEntry raise exception:
    // https://issues.apache.org/bugzilla/show_bug.cgi?id=3862
    ZipOutputStream outContentStream = new ZipOutputStream(new FileOutputStream(contentJar));
    ZipEntry contentXmlEntry = new ZipEntry("content.xml");
    outContentStream.putNextEntry(contentXmlEntry);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    DOMSource source = new DOMSource(contentDoc);
    StreamResult result = new StreamResult(outContentStream);
    transformer.transform(source, result);
    contentStream.close();
    outContentStream.closeEntry();
    outContentStream.close();
    alterXzFile(new File(p2repository, "content.xml"), new File(p2repository, "content.xml.xz"), transformer,
            source);
}

From source file:org.jbpm.bpel.tools.WebAppDescriptorTool.java

private void generateServlet(Element webAppElem, String servletName, String servletClass) {
    Document webAppDoc = webAppElem.getOwnerDocument();

    // servlet//from w w w .ja  va2 s  .c o m
    Element servletElem = webAppDoc.createElementNS(NS_J2EE, ELEM_SERVLET);
    webAppElem.appendChild(servletElem);

    // servlet name
    Element servletNameElem = webAppDoc.createElementNS(NS_J2EE, ELEM_SERVLET_NAME);
    XmlUtil.setStringValue(servletNameElem, servletName);
    servletElem.appendChild(servletNameElem);

    // servlet class
    Element servletClassElem = webAppDoc.createElementNS(NS_J2EE, ELEM_SERVLET_CLASS);
    XmlUtil.setStringValue(servletClassElem, servletClass);
    servletElem.appendChild(servletClassElem);

    // servlet mapping
    Element servletMappingElem = webAppDoc.createElementNS(NS_J2EE, ELEM_SERVLET_MAPPING);
    webAppElem.appendChild(servletMappingElem);

    // servlet name
    servletMappingElem.appendChild(servletNameElem.cloneNode(true));

    // url pattern
    Element urlPatternElem = webAppDoc.createElementNS(NS_J2EE, ELEM_URL_PATTERN);
    XmlUtil.setStringValue(urlPatternElem, generateUrlPattern(servletName));
    servletMappingElem.appendChild(urlPatternElem);
}

From source file:org.jdal.xml.XMLUtils.java

/**
 * Get a DOM Element from xml string/*from w ww  . j  a va  2 s .com*/
 * @param xml the string to parse 
 * @return a new DOM Element
 */
public static Element stringToElement(String xml) {
    Document doc = newDocument(xml);
    Element elto = doc.getDocumentElement();
    return (Element) elto.cloneNode(true);

}

From source file:org.kuali.rice.edl.impl.components.NetworkIdWorkflowEDLConfigComponent.java

@Override
public Element getReplacementConfigElement(Element element) {
    Element replacementEl = (Element) element.cloneNode(true);
    Element type = (Element) ((NodeList) replacementEl.getElementsByTagName(EDLXmlUtils.TYPE_E)).item(0);
    type.setTextContent("text");

    //find the validation element if required is true set a boolean and determin if blanks
    //are allowed based on that
    Element validation = (Element) ((NodeList) replacementEl.getElementsByTagName(EDLXmlUtils.VALIDATION_E))
            .item(0);//from w ww.  ja  va  2 s.c o m
    if (validation != null && validation.getAttribute("required").equals("true")) {
        required = true;
    }
    return replacementEl;
}

From source file:org.opendedup.sdfs.replication.ArchiveImporter.java

public Element importArchive(String srcArchive, String dest, String server, String password, int port,
        int maxSz, SDFSEvent evt, boolean useSSL, boolean useLz4) throws Exception {
    ievt = SDFSEvent.archiveImportEvent(
            "Importing " + srcArchive + " from " + server + ":" + port + " to " + dest, evt);
    ReadLock l = GCMain.gclock.readLock();
    l.lock();//from w ww  . j  a va  2s . c  o  m
    runningJobs.put(evt.uid, this);
    String sdest = dest + "." + RandomGUID.getGuid();
    File f = new File(srcArchive);
    File fDstFiles = new File(Main.volume.getPath() + File.separator + sdest);
    try {

        SDFSLogger.getLog().info("setting up staging at " + sdest);
        try {
            SDFSLogger.getLog()
                    .info("Importing " + srcArchive + " from " + server + ":" + port + " to " + dest);
            if (!f.exists())
                throw new IOException("File does not exist " + srcArchive);
            if (OSValidator.isWindows()) {

                TFile srcRoot = new TFile(new File(srcArchive + "/"));
                ievt.maxCt = FileCounts.getSize(srcRoot);

                SDFSLogger.getLog().info("Tar file size is " + ievt.maxCt);
                TFile srcFilesRoot = new TFile(new File(srcArchive + "/files/"));
                TFile srcFiles = null;
                try {
                    srcFiles = srcFilesRoot.listFiles()[0];
                } catch (Exception e) {
                    SDFSLogger.getLog().error("Replication archive is corrupt " + srcArchive + " size of "
                            + new File(srcArchive).length(), e);
                    throw e;
                }
                TFile tfDstFiles = new TFile(Main.volume.getPath() + File.separator + sdest);
                this.export(srcFiles, tfDstFiles);
                srcFiles = new TFile(new File(srcArchive + "/ddb/"));
                File ddb = new File(Main.dedupDBStore + File.separator);
                if (!ddb.exists())
                    ddb.mkdirs();
                TFile mDstFiles = new TFile(Main.dedupDBStore + File.separator);
                this.export(srcFiles, mDstFiles);
                TVFS.umount(srcFiles);
                TVFS.umount(mDstFiles);
                TVFS.umount(srcRoot.getInnerArchive());
            } else {
                ievt.maxCt = 3;
                File stg = null;
                try {
                    stg = new File(new File(srcArchive).getParentFile().getPath() + File.separator
                            + RandomGUID.getGuid());
                    stg.mkdirs();

                    String expFile = "tar -xzpf " + srcArchive + " -C " + stg.getPath();
                    if (useLz4)
                        expFile = "lz4 -dc " + srcArchive + " | tar -xpf -";
                    int xt = ProcessWorker.runProcess(expFile);
                    if (xt != 0)
                        throw new IOException("expand failed in " + expFile + " exit value was " + xt);
                    ievt.curCt++;
                    SDFSLogger.getLog().info("executed " + expFile + " exit code was " + xt);
                    File srcFilesRoot = new File(stg.getPath() + File.separator + "files");
                    File srcFiles = null;
                    try {
                        srcFiles = srcFilesRoot.listFiles()[0];
                    } catch (Exception e) {
                        SDFSLogger.getLog().error("Replication archive is corrupt " + srcArchive + " size of "
                                + new File(srcArchive).length(), e);
                        throw e;
                    }
                    SDFSLogger.getLog().info("setting up staging at " + fDstFiles.getPath());
                    fDstFiles.getParentFile().mkdirs();
                    String cpCmd = "cp -rfap " + srcFiles + " " + fDstFiles;

                    xt = ProcessWorker.runProcess(cpCmd);
                    if (xt != 0)
                        throw new IOException("copy failed in " + cpCmd + " exit value was " + xt);
                    SDFSLogger.getLog().info("executed " + cpCmd + " exit code was " + xt);
                    ievt.curCt++;
                    srcFiles = new File(stg.getPath() + File.separator + "ddb");
                    File ddb = new File(Main.dedupDBStore + File.separator);
                    if (!ddb.exists())
                        ddb.mkdirs();
                    if (srcFiles.exists()) {
                        cpCmd = "cp -rfap " + srcFiles + File.separator + " " + ddb.getParentFile().getPath();
                        xt = ProcessWorker.runProcess(cpCmd);
                        if (xt != 0)
                            throw new IOException("copy failed in " + cpCmd + " exit value was " + xt);
                    }
                    SDFSLogger.getLog().info("executed " + cpCmd + " exit code was " + xt);
                    ievt.endEvent("Staging completed successfully");
                } catch (Exception e) {
                    ievt.endEvent(e.getMessage(), SDFSEvent.ERROR);
                    throw e;
                } finally {
                    // FileUtils.deleteDirectory(stg);
                    Process p = Runtime.getRuntime().exec("rm -rf " + stg);
                    p.waitFor();
                    f.delete();
                }

            }
            imp = new MetaFileImport(Main.volume.getPath() + File.separator + sdest, server, password, port,
                    maxSz, evt, useSSL);
            imp.runImport();
            if (imp.isCorrupt()) {

                // evt.endEvent("Import failed for " + srcArchive +
                // " because not all the data could be imported from " +
                // server,SDFSEvent.WARN);
                SDFSLogger.getLog().warn("Import failed for " + srcArchive
                        + " because not all the data could be imported from " + server);
                SDFSLogger.getLog().warn("rolling back import");
                rollBackImport(Main.volume.getPath() + File.separator + sdest);
                SDFSLogger.getLog().warn("Import rolled back");
                throw new IOException("uable to import files: There are files that are missing blocks");
            } else {
                if (!Main.chunkStoreLocal)
                    new ClusterRedundancyCheck(ievt, new File(Main.volume.getPath() + File.separator + sdest),
                            true);
                commitImport(Main.volume.getPath() + File.separator + dest,
                        Main.volume.getPath() + File.separator + sdest);
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder;
                builder = factory.newDocumentBuilder();

                DOMImplementation impl = builder.getDOMImplementation();
                // Document.
                Document doc = impl.createDocument(null, "replication-import", null);
                // Root element.
                Element root = doc.getDocumentElement();
                root.setAttribute("src", srcArchive);
                root.setAttribute("dest", dest);
                root.setAttribute("srcserver", server);
                root.setAttribute("srcserverport", Integer.toString(port));
                root.setAttribute("batchsize", Integer.toString(maxSz));
                root.setAttribute("filesimported", Long.toString(imp.getFilesProcessed()));
                root.setAttribute("bytesimported", Long.toString(imp.getBytesTransmitted()));
                root.setAttribute("entriesimported", Long.toString(imp.getEntries()));
                root.setAttribute("virtualbytesimported", Long.toString(imp.getVirtualBytesTransmitted()));
                root.setAttribute("starttime", Long.toString(imp.getStartTime()));
                root.setAttribute("endtime", Long.toString(imp.getEndTime()));
                root.setAttribute("volume", Main.volume.getName());
                root.setAttribute("volumeconfig", Main.volume.getConfigPath());
                evt.endEvent(
                        srcArchive + " from " + server + ":" + port + " to " + dest + " imported successfully");
                return (Element) root.cloneNode(true);
            }
        } catch (Exception e) {
            SDFSLogger.getLog().warn("rolling back import ", e);
            rollBackImport(Main.volume.getPath() + File.separator + sdest);
            SDFSLogger.getLog().warn("Import rolled back");

            if (!evt.isDone())
                evt.endEvent("Import failed and was rolled back ", SDFSEvent.ERROR, e);
            throw e;
        }
    } finally {
        try {

        } catch (Exception e) {
            if (SDFSLogger.isDebug())
                SDFSLogger.getLog().debug("error", e);
        }
        runningJobs.remove(evt.uid);
        l.unlock();
    }

}

From source file:org.openmrs.module.metadatasharing.converter.ConceptMap19Converter.java

@Override
public void convert(Document doc, Version fromVersion, Version toVersion, ConverterContext context)
        throws SerializationException {
    if (fromVersion.compareTo(new Version("1.9")) >= 0 || toVersion.compareTo(new Version("1.9")) < 0) {
        return;//from w  w  w  .j a v a 2  s . c om
    }

    Map<String, Element> mapTypeElements = new HashMap<String, Element>();

    NodeList maps = doc.getElementsByTagName("org.openmrs.ConceptMap");
    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);

        Element commentElement = getChildElement(map, "comment");
        if (commentElement == null) {
            continue;
        }

        map.removeChild(commentElement);

        String mapTypeName = getMapTypeName(commentElement);

        if (mapTypeName == null) {
            continue;
        }

        Element mapTypeElement = mapTypeElements.get(mapTypeName);

        if (mapTypeElement == null) {
            ConceptMapType mapType = Context.getConceptService().getConceptMapTypeByName(mapTypeName);

            if (mapType == null) {
                continue;
            }

            mapTypeElement = newElement(doc, "conceptMapType", mapType, context);
            mapTypeElements.put(mapTypeName, mapTypeElement);

            map.appendChild(mapTypeElement);
        } else {
            Element reference = doc.createElement("conceptMapTye");
            newReferenced(reference, mapTypeElement);
            map.appendChild(reference);
        }
    }

    Map<String, Element> referenceTermElements = new HashMap<String, Element>();

    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);
        Element source = getChildElement(map, "source");
        map.removeChild(source);
        Element referencedSource = (Element) reference(source, context);

        Element sourceCode = getChildElement(map, "sourceCode");
        map.removeChild(sourceCode);

        //ConceptReferenceTerms are the same if source and sourceCode are the same
        String key = referencedSource.getAttribute("uuid") + sourceCode.getTextContent();

        Element referenceTermElement = referenceTermElements.get(key);

        if (referenceTermElement == null) {
            ConceptReferenceTerm referenceTerm = new ConceptReferenceTerm();
            String uuid = UUID.nameUUIDFromBytes(((Element) map).getAttribute("uuid").getBytes()).toString();
            referenceTerm.setUuid(uuid);
            referenceTerm.setCode(sourceCode.getTextContent());
            referenceTermElement = newElement(doc, "conceptReferenceTerm", referenceTerm, context);
            source = (Element) source.cloneNode(true);
            source = (Element) doc.renameNode(source, "", "conceptSource");
            referenceTermElement.appendChild(source);

            referenceTermElements.put(key, referenceTermElement);
            map.appendChild(referenceTermElement);
        } else {
            Element reference = doc.createElement("conceptReferenceTerm");
            newReferenced(reference, referenceTermElement);
            map.appendChild(reference);
        }
    }
}

From source file:org.openmrs.module.metadatasharing.converter.ConceptMapConverter.java

/**
 * @see org.openmrs.module.metadatasharing.converter.BaseConverter#convert(org.w3c.dom.Document, org.openmrs.module.metadatasharing.util.Version, org.openmrs.module.metadatasharing.util.Version, org.openmrs.module.metadatasharing.converter.BaseConverter.ConverterContext)
 * @should replace source if the from version is pre one nine
 * @should replace nothing if the to version is post one nine
 *//*from w w  w .j  av  a  2 s .  com*/
@Override
public void convert(Document doc, Version fromVersion, Version toVersion, ConverterContext context)
        throws SerializationException {
    if (fromVersion.compareTo(new Version("1.9")) >= 0 || toVersion.compareTo(new Version("1.9")) < 0) {
        return;
    }

    Map<String, Element> mapTypeElements = new HashMap<String, Element>();

    NodeList maps = doc.getElementsByTagName("org.openmrs.ConceptMap");
    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);

        Element commentElement = getChildElement(map, "comment");
        if (commentElement == null) {
            continue;
        }

        map.removeChild(commentElement);

        String mapTypeName = getMapTypeName(commentElement);

        if (mapTypeName == null) {
            continue;
        }

        Element mapTypeElement = mapTypeElements.get(mapTypeName);

        if (mapTypeElement == null) {
            ConceptMapType mapType = Context.getConceptService().getConceptMapTypeByName(mapTypeName);

            if (mapType == null) {
                continue;
            }

            mapTypeElement = newElement(doc, "conceptMapType", mapType, context);
            mapTypeElements.put(mapTypeName, mapTypeElement);

            map.appendChild(mapTypeElement);
        } else {
            Element reference = doc.createElement("conceptMapTye");
            newReferenced(reference, mapTypeElement);
            map.appendChild(reference);
        }
    }

    Map<String, Element> referenceTermElements = new HashMap<String, Element>();

    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);
        Element source = getChildElement(map, "source");
        map.removeChild(source);
        Element referencedSource = (Element) reference(source, context);

        Element sourceCode = getChildElement(map, "sourceCode");
        map.removeChild(sourceCode);

        //ConceptReferenceTerms are the same if source and sourceCode are the same
        String key = referencedSource.getAttribute("uuid") + sourceCode.getTextContent();

        Element referenceTermElement = referenceTermElements.get(key);

        if (referenceTermElement == null) {
            ConceptReferenceTerm referenceTerm = new ConceptReferenceTerm();
            String uuid = UUID.nameUUIDFromBytes(((Element) map).getAttribute("uuid").getBytes()).toString();
            referenceTerm.setUuid(uuid);
            referenceTerm.setCode(sourceCode.getTextContent());
            referenceTermElement = newElement(doc, "conceptReferenceTerm", referenceTerm, context);
            source = (Element) source.cloneNode(true);
            source = (Element) doc.renameNode(source, "", "conceptSource");
            referenceTermElement.appendChild(source);

            referenceTermElements.put(key, referenceTermElement);
            map.appendChild(referenceTermElement);
        } else {
            Element reference = doc.createElement("conceptReferenceTerm");
            newReferenced(reference, referenceTermElement);
            map.appendChild(reference);
        }
    }
}

From source file:org.sakaiproject.assignment.impl.BaseAssignmentService.java

/**
 * {@inheritDoc}/*ww w .j  ava  2  s  .c o  m*/
 */
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames,
        Map userIdTrans, Set userListAllowImport) {
    // prepare the buffer for the results log
    StringBuilder results = new StringBuilder();

    int count = 0;

    try {
        // pass the DOM to get new assignment ids, and adjust attachments
        NodeList children2 = root.getChildNodes();

        int length2 = children2.getLength();
        for (int i2 = 0; i2 < length2; i2++) {
            Node child2 = children2.item(i2);
            if (child2.getNodeType() == Node.ELEMENT_NODE) {
                Element element2 = (Element) child2;

                if (element2.getTagName().equals("assignment")) {
                    // a flag showing if continuing merging the assignment
                    boolean goAhead = true;
                    AssignmentContentEdit contentEdit = null;

                    // element2 now - assignment node
                    // adjust the id of this assignment
                    // String newId = IdManager.createUuid();
                    element2.setAttribute("id", IdManager.createUuid());
                    element2.setAttribute("context", siteId);

                    // cloneNode(false) - no children cloned
                    Element el2clone = (Element) element2.cloneNode(false);

                    // traverse this assignment node first to check if the person who last modified, has the right role.
                    // if no right role, mark the flag goAhead to be false.
                    NodeList children3 = element2.getChildNodes();
                    int length3 = children3.getLength();
                    for (int i3 = 0; i3 < length3; i3++) {
                        Node child3 = children3.item(i3);
                        if (child3.getNodeType() == Node.ELEMENT_NODE) {
                            Element element3 = (Element) child3;

                            // add the properties childnode to the clone of assignment node
                            if (element3.getTagName().equals("properties")) {
                                NodeList children6 = element3.getChildNodes();
                                int length6 = children6.getLength();
                                for (int i6 = 0; i6 < length6; i6++) {
                                    Node child6 = children6.item(i6);
                                    if (child6.getNodeType() == Node.ELEMENT_NODE) {
                                        Element element6 = (Element) child6;

                                        if (element6.getTagName().equals("property")) {
                                            if (element6.getAttribute("name")
                                                    .equalsIgnoreCase("CHEF:modifiedby")) {
                                                if ("BASE64".equalsIgnoreCase(element6.getAttribute("enc"))) {
                                                    String creatorId = Xml.decodeAttribute(element6, "value");
                                                    if (!userListAllowImport.contains(creatorId))
                                                        goAhead = false;
                                                } else {
                                                    String creatorId = element6.getAttribute("value");
                                                    if (!userListAllowImport.contains(creatorId))
                                                        goAhead = false;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } // for

                    // then, go ahead to merge the content and assignment
                    if (goAhead) {
                        for (int i3 = 0; i3 < length3; i3++) {
                            Node child3 = children3.item(i3);
                            if (child3.getNodeType() == Node.ELEMENT_NODE) {
                                Element element3 = (Element) child3;

                                // add the properties childnode to the clone of assignment node
                                if (element3.getTagName().equals("properties")) {
                                    // add the properties childnode to the clone of assignment node
                                    el2clone.appendChild(element3.cloneNode(true));
                                } else if (element3.getTagName().equals("content")) {
                                    // element3 now- content node
                                    // adjust the id of this content
                                    String newContentId = IdManager.createUuid();
                                    element3.setAttribute("id", newContentId);
                                    element3.setAttribute("context", siteId);

                                    // clone the content node without the children of <properties>
                                    Element el3clone = (Element) element3.cloneNode(false);

                                    // update the assignmentcontent id in assignment node
                                    String assignContentId = "/assignment/c/" + siteId + "/" + newContentId;
                                    el2clone.setAttribute("assignmentcontent", assignContentId);

                                    // for content node, process the attachment or properties kids
                                    NodeList children5 = element3.getChildNodes();
                                    int length5 = children5.getLength();
                                    int attCount = 0;
                                    for (int i5 = 0; i5 < length5; i5++) {
                                        Node child5 = children5.item(i5);
                                        if (child5.getNodeType() == Node.ELEMENT_NODE) {
                                            Element element5 = (Element) child5;

                                            // for the node of "properties"
                                            if (element5.getTagName().equals("properties")) {
                                                // for the file from WT, preform userId translation when needed
                                                if (!userIdTrans.isEmpty()) {
                                                    WTUserIdTrans(element3, userIdTrans);
                                                }
                                            } // for the node of properties
                                            el3clone.appendChild(element5.cloneNode(true));

                                            // for "attachment" children
                                            if (element5.getTagName().equals("attachment")) {
                                                // map the attachment area folder name
                                                // filter out the invalid characters in the attachment id
                                                // map the attachment area folder name
                                                String oldUrl = element5.getAttribute("relative-url");
                                                if (oldUrl.startsWith(
                                                        "/content/attachment/" + fromSiteId + "/")) {
                                                    String newUrl = "/content/attachment/" + siteId
                                                            + oldUrl.substring(
                                                                    ("/content/attachment" + fromSiteId)
                                                                            .length());
                                                    element5.setAttribute("relative-url",
                                                            Validator.escapeQuestionMark(newUrl));

                                                    // transfer attachment, replace the context string and add new attachment if necessary
                                                    newUrl = transferAttachment(fromSiteId, siteId, null,
                                                            oldUrl.substring("/content".length()));
                                                    element5.setAttribute("relative-url",
                                                            Validator.escapeQuestionMark(newUrl));

                                                    newUrl = (String) attachmentNames.get(oldUrl);
                                                    if (newUrl != null) {
                                                        if (newUrl.startsWith("/attachment/"))
                                                            newUrl = "/content".concat(newUrl);

                                                        element5.setAttribute("relative-url",
                                                                Validator.escapeQuestionMark(newUrl));
                                                    }
                                                }

                                                // map any references to this site to the new site id
                                                else if (oldUrl
                                                        .startsWith("/content/group/" + fromSiteId + "/")) {
                                                    String newUrl = "/content/group/" + siteId
                                                            + oldUrl.substring(
                                                                    ("/content/group/" + fromSiteId).length());
                                                    element5.setAttribute("relative-url",
                                                            Validator.escapeQuestionMark(newUrl));
                                                }
                                                // put the attachment back to the attribute field of content
                                                // to satisfy the input need of mergeAssignmentContent
                                                String attachmentString = "attachment" + attCount;
                                                el3clone.setAttribute(attachmentString,
                                                        element5.getAttribute("relative-url"));
                                                attCount++;

                                            } // if
                                        } // if
                                    } // for

                                    // create a newassignment content
                                    contentEdit = mergeAssignmentContent(el3clone);
                                    commitEdit(contentEdit);
                                }
                            }
                        } // for

                        // when importing, refer to property to determine draft status
                        if ("false".equalsIgnoreCase(
                                m_serverConfigurationService.getString("import.importAsDraft"))) {
                            String draftAttribute = el2clone.getAttribute("draft");
                            if (draftAttribute.equalsIgnoreCase("true")
                                    || draftAttribute.equalsIgnoreCase("false"))
                                el2clone.setAttribute("draft", draftAttribute);
                            else
                                el2clone.setAttribute("draft", "true");
                        } else {
                            el2clone.setAttribute("draft", "true");
                        }

                        // merge in this assignment
                        AssignmentEdit edit = mergeAssignment(el2clone);
                        edit.setContent(contentEdit);
                        commitEdit(edit);

                        count++;
                    } // if goAhead
                } // if
            } // if
        } // for
    } catch (Exception any) {
        M_log.warn(" merge(): exception: " + any.getMessage() + " siteId=" + siteId + " from site id="
                + fromSiteId);
    }

    results.append("merging assignment " + siteId + " (" + count + ") assignments.\n");
    return results.toString();

}