Example usage for org.w3c.dom Element getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:org.osaf.cosmo.dav.property.StandardDavProperty.java

/**
 * <p>//from   w  w  w. j a v  a 2s . c  o  m
 * Returns an instance of <code>StandardDavProperty</code> representing
 * the given element. The element itself is provided as the property value.
 * If either the element or its parent element has the attribute
 * <code>xml:lang</code>, that attribute's value is provided as the
 * property's language. The resulting property is not "protected" (i.e.
 * it will not appear in "allprop" <code>PROPFIND</code> responses).
 * </p>
 */
public static StandardDavProperty createFromXml(Element e) {
    DavPropertyName name = DavPropertyName.createFromXml(e);
    String lang = DomUtil.getAttribute(e, XML_LANG, NAMESPACE_XML);
    if (lang == null && e.getParentNode() != null && e.getParentNode().getNodeType() == Node.ELEMENT_NODE)
        lang = DomUtil.getAttribute((Element) e.getParentNode(), XML_LANG, NAMESPACE_XML);
    return new StandardDavProperty(name, e, lang);
}

From source file:org.pentaho.reporting.engine.classic.core.RotationTest.java

@Test
public void testHandleRotatedTextHTML() throws Exception {
    URL url = getClass().getResource("BACKLOG-10064.prpt");
    MasterReport report = (MasterReport) new ResourceManager().createDirectly(url, MasterReport.class)
            .getResource();/* w  w w.j  a  v  a 2  s  . c  o m*/
    report.getReportConfiguration().setConfigProperty(HtmlTableModule.INLINE_STYLE, "true");

    List<String> elementsIdList = Arrays.asList("topLeft90", "topCenter90", "topRight90", "topJustify90",
            "topLeft-90", "topCenter-90", "topRight-90", "topJustify-90", "middleLeft90", "middleCenter90",
            "middleRight90", "middleJustify90", "middleLeft-90", "middleCenter-90", "middleRight-90",
            "middleJustify-90", "bottomLeft90", "bottomCenter90", "bottomRight90", "bottomJustify90",
            "bottomLeft-90", "bottomCenter-90", "bottomRight-90", "bottomJustify-90");

    XPathFactory xpathFactory = XPathFactory.newInstance();
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        HtmlReportUtil.createStreamHTML(report, stream);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new ByteArrayInputStream(stream.toByteArray()));

        for (String elementId : elementsIdList) {
            org.w3c.dom.Element element = document.getElementById(elementId);
            Node rotatedTextStyle = element.getFirstChild().getAttributes().getNamedItem("style");
            Node trSryle = element.getParentNode().getParentNode().getAttributes().getNamedItem("style");
            assertTrue(isStyleValid(rotatedTextStyle.getNodeValue(), trSryle.getNodeValue(),
                    elementId.contains("middle")));
        }
    } catch (final IOException | ReportProcessingException e) {
        fail();
    }

}

From source file:org.sakaiproject.archive.impl.BasicArchiveService.java

/**
* Merge the the permission-roles settings into the site
* @param element The XML DOM tree of messages to merge.
* @param siteId The id of the site getting imported into.
*///from   w w  w  .  j a  v  a  2  s  . c  o  m
protected void mergeSiteRoles(Element el, String siteId, HashMap useIdTrans) throws PermissionException {
    // heck security (throws if not permitted)
    unlock(SiteService.SECURE_UPDATE_SITE, SiteService.siteReference(siteId));

    String source = "";

    // el: <roles> node         
    Node parent0 = el.getParentNode(); // parent0: <site> node
    Node parent1 = parent0.getParentNode(); // parent1: <service> node
    Node parent = parent1.getParentNode(); // parent: <archive> node containing "system"

    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    List roles = new Vector();
    // to add this user with this role inito this realm
    String realmId = "/site/" + siteId;
    try {
        //AuthzGroup realmEdit = AuthzGroupService.getRealm(realmId);
        AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);

        //roles.addAll(realmEdit.getRoles());
        roles.addAll(realm.getRoles());

        NodeList children = el.getChildNodes();
        final int length = children.getLength();
        for (int i = 0; i < length; i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element element2 = (Element) child;

            if (source.equalsIgnoreCase(FROM_WT)) {
                // from WT, merge the users with roles into the new site

                NodeList children2 = element2.getChildNodes();
                final int length2 = children2.getLength();
                for (int i2 = 0; i2 < length2; i2++) {
                    Node child2 = children2.item(i2);
                    if (child2.getNodeType() != Node.ELEMENT_NODE)
                        continue;
                    Element element3 = (Element) child2;
                    if (!element3.getTagName().equals("ability"))
                        continue;

                    String userId = element3.getAttribute("userId");

                    // under 2 conditions the userIdTrans would be empty
                    // 1st is, even from WT, no user id has been processed
                    // 2nd is, this user is not from WT. userIdTrans is always empty
                    if (!userIdTrans.isEmpty()) {
                        // user the new id if the old one from WT has been replaced
                        String newId = (String) useIdTrans.get(userId);
                        if (newId != null)
                            userId = newId;
                    }
                    try {
                        User user = UserDirectoryService.getUser(userId);
                        String roleId = element3.getAttribute("roleId");
                        //Role role = realmEdit.getRole(roleId);
                        Role role = realm.getRole(roleId);
                        if (role != null) {
                            AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
                            realmEdit.addMember(user.getId(), role.getId(), true, false);
                            AuthzGroupService.save(realmEdit);
                        }
                    } catch (UserNotDefinedException e) {
                        M_log.warn("UserNotDefined in mergeSiteRoles: " + userId);
                    } catch (AuthzPermissionException e) {
                        M_log.warn("AuthzPermissionException in mergeSiteRoles", e);
                    }
                }
            } else {
                // for both CT classic and Sakai CTools

                // check is this roleId is a qualified one
                if (!checkSystemRole(source, element2.getTagName()))
                    continue;

                NodeList children2 = element2.getChildNodes();
                final int length2 = children2.getLength();
                for (int i2 = 0; i2 < length2; i2++) {
                    Node child2 = children2.item(i2);
                    if (child2.getNodeType() != Node.ELEMENT_NODE)
                        continue;
                    Element element3 = (Element) child2;
                    if (!element3.getTagName().equals("ability"))
                        continue;

                    String userId = element3.getAttribute("userId");

                    // this user has a qualified role, his/her resource will be imported
                    usersListAllowImport.add(userId);
                }
            } // if - elseif - elseif
        } // for
    } catch (GroupNotDefinedException err) {
        M_log.warn("()mergeSiteRoles realm edit exception caught GroupNotDefinedException " + realmId);
    }
    return;

}

From source file:org.sakaiproject.archive.impl.BasicArchiveService.java

/**
* Merge the user list into the the system.
* Translate the id to the siteId./*  www .j av  a 2s.  c o  m*/
* @param element The XML DOM tree of messages to merge.
*/

protected String mergeUsers(Element element, HashMap useIdTrans)
        throws IdInvalidException, IdUsedException, PermissionException {
    String msg = "";
    int count = 0;

    // The flag showing from WT
    boolean fromWT = false;
    boolean fromCTclassic = false;
    boolean fromCTools = false;
    String source = "";

    Node parent = element.getParentNode();
    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    if (source != null) {
        if (source.equalsIgnoreCase(FROM_CT))
            fromCTclassic = true;
        else if (source.equalsIgnoreCase(FROM_WT))
            fromWT = true;
        else
            fromCTools = true;
    } else
        fromCTools = true;

    NodeList children = element.getChildNodes();
    final int length = children.getLength();
    for (int i = 0; i < length; i++) {
        Node child = children.item(i);
        if (child.getNodeType() != Node.ELEMENT_NODE)
            continue;
        Element element2 = (Element) child;
        if (!element2.getTagName().equals("user"))
            continue;

        //for WorkTools
        if (fromWT) {
            // Worktools use email address as Id
            String wtId = element2.getAttribute("id");
            // check if this is an umich address
            if (wtId.endsWith("umich.edu")) {
                // if this id is a UM unique name
                // trim the first part of the email as the id
                String userId = wtId.substring(0, wtId.indexOf("@"));
                // change the id to be the first part of wtId
                element2.setAttribute("id", userId);

                // add the entry (wtEmail <-> userId) into map
                useIdTrans.put(wtId, userId);

                try {
                    User user = UserDirectoryService.getUser(userId);
                    // if this user id exists, do nothing.
                } catch (UserNotDefinedException e) {
                    // this umich id does not exit, merging will create a new user with this id
                    try {
                        UserEdit userEdit = UserDirectoryService.mergeUser(element2);
                        UserDirectoryService.commitEdit(userEdit);
                        count++;
                        // because it is an UM id, report it in the merge log.
                        msg = msg.concat("The user id " + userId + "(" + wtId
                                + ") doesn't exist, and was just created. \n");
                    } catch (UserIdInvalidException error) {
                        msg = msg.concat("This user with id -" + wtId
                                + ", can't be merged because of the invalid email address.\n");
                    } catch (UserAlreadyDefinedException error) {
                    } catch (UserPermissionException error) {
                    }
                }

            } else {
                // for non-UM email, process as a friend account id
                try {
                    // test if it is a friend account id
                    User user = UserDirectoryService.getUser(wtId);
                    // if the user exists, do nothing.
                } catch (UserNotDefinedException e) {
                    try {
                        // if this isn't such a friend email address,
                        // create a new friend account for it
                        UserEdit userEdit = UserDirectoryService.mergeUser(element2);
                        UserDirectoryService.commitEdit(userEdit);
                        count++;
                    } catch (UserIdInvalidException error) {
                        msg = msg.concat("This user with id -" + wtId
                                + ", can't be merged because of the invalid email address.\n");
                    } catch (UserAlreadyDefinedException error) {
                    } catch (UserPermissionException error) {
                    }
                }

            }
        }
        // not allowing merging users form CT classic or CTools.
        /*
        else if (fromCTclassic)
        {
           String ctId = element2.getAttribute("id");
                
           try
           {
              User user = UserDirectoryService.getUser(ctId);
           }
           catch(IdUnusedException e)
           {
              // if this umich id does not exit, report it in importing log.
              msg.concat("The user id " + ctId + " doesn't exist, and was just created. \n");
           }
                      
           try
           {
              // override the old one or create a new user with this id
              UserEdit userEdit = UserDirectoryService.mergeUser(element2);
              UserDirectoryService.commitEdit(userEdit);
              count++;
           }
           catch(IdInvalidException error)
           {
              msg.concat("This user with id -" + ctId + ", can't be merged because of the invalid email address.\n");
           }
           catch(IdUsedException error)
           {
           }
           catch(PermissionException error)
           {
           }
                        
        }
        else if (fromCTools)
        {
           try
           {
              UserEdit userEdit = UserDirectoryService.mergeUser(element2);
              UserDirectoryService.commitEdit(userEdit);
              count++;
           }
           catch(IdInvalidException error)
           {
              msg.concat("This user with id -" + element2.getAttribute("id") + ", can't be merged because of the invalid email address.\n");
           }
           catch(IdUsedException error)
           {
           }
           catch(PermissionException error)
           {
           }
        }
        */
    }

    msg = msg + "merging user" + "(" + count + ") users\n";
    return msg;

}

From source file:org.sakaiproject.archive.impl.SiteArchiver.java

/**
* Archive the site definition.//from  w  ww  .  j  av a 2  s . co m
* @param site the site.
* @param doc The document to contain the xml.
* @param stack The stack of elements, the top of which will be the containing
* element of the "site" element.
*/

protected String archiveSite(Site site, Document doc, Stack stack, String fromSystem) {
    Element element = doc.createElement(SiteService.APPLICATION_ID);
    ((Element) stack.peek()).appendChild(element);
    stack.push(element);

    Element siteNode = site.toXml(doc, stack);

    // By default, do not include fields that have secret or password in the name
    String filter = m_serverConfigurationService.getString("archive.toolproperties.excludefilter",
            "password|secret");
    Pattern pattern = null;
    if ((!"none".equals(filter)) && filter.length() > 0) {
        try {
            pattern = Pattern.compile(filter);
        } catch (Exception e) {
            pattern = null;
        }
    }

    if (pattern != null) {
        NodeList nl = siteNode.getElementsByTagName("property");
        List<Element> toRemove = new ArrayList<Element>();

        for (int i = 0; i < nl.getLength(); i++) {
            Element proptag = (Element) nl.item(i);
            String propname = proptag.getAttribute("name");
            if (propname == null)
                continue;
            propname = propname.toLowerCase();
            Matcher matcher = pattern.matcher(propname);
            if (matcher.find()) {
                toRemove.add(proptag);
            }
        }
        for (Element proptag : toRemove) {
            proptag.getParentNode().removeChild(proptag);
        }
    }

    stack.push(siteNode);

    // to add the realm node with user list into site
    List roles = new Vector();
    String realmId = m_siteService.siteReference(site.getId()); //SWG "/site/" + site.getId();
    try {
        Role role = null;
        AuthzGroup realm = m_authzGroupService.getAuthzGroup(realmId);

        Element realmNode = doc.createElement("roles");
        ((Element) stack.peek()).appendChild(realmNode);
        stack.push(realmNode);

        roles.addAll(realm.getRoles());

        for (int i = 0; i < roles.size(); i++) {
            role = (Role) roles.get(i);
            String roleId = role.getId();
            Element node = null;
            if (ArchiveService.FROM_SAKAI_2_8.equals(fromSystem)) {
                node = doc.createElement("role");
                node.setAttribute("roleId", roleId);
            } else {
                node = doc.createElement(roleId);
            }
            realmNode.appendChild(node);

            List users = new Vector();
            users.addAll(realm.getUsersHasRole(role.getId()));
            for (int j = 0; j < users.size(); j++) {
                Element abilityNode = doc.createElement("ability");
                abilityNode.setAttribute("roleId", roleId);
                abilityNode.setAttribute("userId", ((String) users.get(j)));
                node.appendChild(abilityNode);
            }
        }
    } catch (Exception any) {
        M_log.warn("archve: exception archiving site: " + site.getId() + ": ", any);
    }

    stack.pop();

    return "archiving Site: " + site.getId() + "\n";

}

From source file:org.sakaiproject.archive.impl.SiteMerger.java

/**
* Merge the site definition from the site part of the archive file into the site service.
* Translate the id to the siteId.//from  w w  w  .j  a  v a 2s. c o m
* @param siteId The id of the site getting imported into.
* @param fromSiteId The id of the site the archive was made from.
* @param element The XML DOM tree of messages to merge.
* @param creatorId The creator id
*/
protected void mergeSite(String siteId, String fromSiteId, Element element, HashMap useIdTrans,
        String creatorId, boolean filterSakaiRoles, String[] filteredSakaiRoles) {
    String source = "";

    Node parent = element.getParentNode();
    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    NodeList children = element.getChildNodes();
    final int length = children.getLength();
    for (int i = 0; i < length; i++) {
        Node child = children.item(i);
        if (child.getNodeType() != Node.ELEMENT_NODE)
            continue;
        Element element2 = (Element) child;
        if (!element2.getTagName().equals("site"))
            continue;

        NodeList toolChildren = element2.getElementsByTagName("tool");
        final int tLength = toolChildren.getLength();
        for (int i2 = 0; i2 < tLength; i2++) {
            Element element3 = (Element) toolChildren.item(i2);
            String toolId = element3.getAttribute("toolId");
            if (toolId != null) {
                toolId = toolId.replaceAll(old_toolId_prefix, new_toolId_prefix);
                for (int j = 0; j < old_toolIds.length; j++) {
                    toolId = toolId.replaceAll(old_toolIds[i], new_toolIds[i]);
                }
            }
            element3.setAttribute("toolId", toolId);
        }

        // merge the site info first
        try {
            m_siteService.merge(siteId, element2, creatorId);
            mergeSiteInfo(element2, siteId);
        } catch (Exception any) {
            M_log.warn(any, any);
        }

        Site site = null;
        try {
            site = m_siteService.getSite(siteId);
        } catch (IdUnusedException e) {
            M_log.warn(this + "The site with id " + siteId + " doesn't exit", e);
            return;
        }

        if (site != null) {
            NodeList children2 = element2.getChildNodes();
            final int length2 = children2.getLength();
            for (int i2 = 0; i2 < length2; i2++) {
                Node child2 = children2.item(i2);
                if (child2.getNodeType() != Node.ELEMENT_NODE)
                    continue;
                Element element3 = (Element) child2;
                if (!element3.getTagName().equals("roles"))
                    continue;

                try {
                    mergeSiteRoles(element3, siteId, useIdTrans, filterSakaiRoles, filteredSakaiRoles);
                } catch (PermissionException e1) {
                    M_log.warn(e1, e1);
                }
            }
        }
    }
}

From source file:org.sakaiproject.archive.impl.SiteMerger.java

/**
* Merge the the permission-roles settings into the site
* @param element The XML DOM tree of messages to merge.
* @param siteId The id of the site getting imported into.
*///from   w  w w  .ja  v a  2s. c om
protected void mergeSiteRoles(Element el, String siteId, HashMap useIdTrans, boolean filterSakaiRoles,
        String[] filteredSakaiRoles) throws PermissionException {
    // heck security (throws if not permitted)
    unlock(SiteService.SECURE_UPDATE_SITE, m_siteService.siteReference(siteId));

    String source = "";

    // el: <roles> node         
    Node parent0 = el.getParentNode(); // parent0: <site> node
    Node parent1 = parent0.getParentNode(); // parent1: <service> node
    Node parent = parent1.getParentNode(); // parent: <archive> node containing "system"

    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    List roles = new Vector();
    //List maintainUsers = new Vector();
    //List accessUsers = new Vector();

    // to add this user with this role inito this realm
    String realmId = m_siteService.siteReference(siteId); //SWG "/site/" + siteId;
    try {
        AuthzGroup realm = m_authzGroupService.getAuthzGroup(realmId);
        roles.addAll(realm.getRoles());

        NodeList children = el.getChildNodes();
        final int length = children.getLength();
        for (int i = 0; i < length; i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element element2 = (Element) child;
            String roleId = null;

            if (ArchiveService.FROM_SAKAI_2_8.equals(source)) {
                if (!"role".equals(element2.getTagName()))
                    continue;

                roleId = element2.getAttribute("roleId");
            } else {
                roleId = element2.getTagName();
            }

            //SWG Getting rid of WT part above, this was previously the else branch labeled "for both CT classic and Sakai CTools"
            // check is this roleId is a qualified one
            if (!checkSystemRole(source, roleId, filterSakaiRoles, filteredSakaiRoles))
                continue;

            NodeList children2 = element2.getChildNodes();
            final int length2 = children2.getLength();
            for (int i2 = 0; i2 < length2; i2++) {
                Node child2 = children2.item(i2);
                if (child2.getNodeType() != Node.ELEMENT_NODE)
                    continue;
                Element element3 = (Element) child2;
                if (!element3.getTagName().equals("ability"))
                    continue;

                String userId = element3.getAttribute("userId");
                // this user has a qualified role, his/her resource will be imported
                usersListAllowImport.add(userId);
            }
        } // for
    } catch (Exception err) {
        M_log.warn("()mergeSiteRoles realm edit exception caught" + realmId, err);
    }
    return;

}

From source file:org.sakaiproject.content.impl.BaseContentService.java

/**
 * Merge the resources from the archive into the given site.
 * /*from  www.ja v a 2 s.com*/
 * @param siteId
 *        The id of the site getting imported into.
 * @param root
 *        The XML DOM tree of content to merge.
 * @param archviePath
 *        The path to the folder where we are reading auxilary files.
 * @return A log of status messages from the archive.
 */
public String merge(String siteId, Element root, String archivePath, String mergeId, Map attachmentNames,
        Map userIdTrans, Set userListAllowImport) {
    // get the system name: FROM_WT, FROM_CT, FROM_SAKAI
    String source = "";
    // root: <service> node
    Node parent = root.getParentNode(); // parent: <archive> node containing "system"
    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    // prepare the buffer for the results log
    StringBuilder results = new StringBuilder();

    try {
        NodeList children = root.getChildNodes();
        final int length = children.getLength();
        for (int i = 0; i < length; i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element element = (Element) child;

            // for "collection" kids
            if (element.getTagName().equals("collection")) {
                // replace the WT userid when needed
                if (!userIdTrans.isEmpty()) {
                    // replace the WT user id with new user id
                    WTUserIdTrans(element, userIdTrans);
                }

                // from the relative id form a full id for the target site,
                // updating the xml element
                String relId = StringUtils.trimToNull(element.getAttribute("rel-id"));
                if (relId == null) {
                    // Note: the site's root collection will have a "" rel-id, which will be null.
                    continue;
                }
                String id = getSiteCollection(siteId) + relId;
                element.setAttribute("id", id);

                // collection: add if missing, else merge in
                ContentCollection c = mergeCollection(element);
                if (c == null) {
                    results.append("collection: " + id + " already exists and was not replaced.\n");
                } else {
                    results.append("collection: " + id + " imported.\n");
                }
            }

            // for "resource" kids
            else if (element.getTagName().equals("resource")) {
                // a flag showing if continuing merging this resource
                boolean goAhead = true;

                // check if the person who last modified this source has the right role
                // if not, set the goAhead flag to be false when fromSakai or fromCT
                if (source.equalsIgnoreCase("Sakai 1.0") || source.equalsIgnoreCase("CT")) {
                    NodeList children2 = element.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;

                            // get the "channel" child
                            if (element2.getTagName().equals("properties")) {
                                NodeList children3 = element2.getChildNodes();
                                final 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;

                                        // for "message" children
                                        if (element3.getTagName().equals("property")) {
                                            if (element3.getAttribute("name")
                                                    .equalsIgnoreCase("CHEF:modifiedby")) {
                                                if ("BASE64".equalsIgnoreCase(element3.getAttribute("enc"))) {
                                                    String creatorId = Xml.decodeAttribute(element3, "value");
                                                    if (!userListAllowImport.contains(creatorId))
                                                        goAhead = false;
                                                } else {
                                                    String creatorId = element3.getAttribute("value");
                                                    if (!userListAllowImport.contains(creatorId))
                                                        goAhead = false;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } // the end to if fromSakai or fromCT

                if (goAhead) {
                    // replace the WT userid when needed
                    if (!userIdTrans.isEmpty()) {
                        // replace the WT user id with new user id
                        WTUserIdTrans(element, userIdTrans);
                    }

                    // from the relative id form a full id for the target site,
                    // updating the xml element
                    String id = StringUtils.trimToNull(element.getAttribute("id"));
                    String relId = StringUtils.trimToNull(element.getAttribute("rel-id"));

                    // escape the invalid characters
                    id = Validator.escapeQuestionMark(id);
                    relId = Validator.escapeQuestionMark(relId);

                    // if it's attachment, assign a new attachment folder
                    if (id.startsWith(ATTACHMENTS_COLLECTION)) {
                        String oldRef = getReference(id);

                        // take the name from after /attachment/whatever/
                        id = ATTACHMENTS_COLLECTION + idManager.createUuid()
                                + id.substring(id.indexOf('/', ATTACHMENTS_COLLECTION.length()));

                        // record the rename
                        attachmentNames.put(oldRef, id);
                    }

                    // otherwise move it into the site
                    else {
                        if (relId == null) {
                            M_log.warn("mergeContent(): no rel-id attribute in resource");
                            continue;
                        }

                        id = getSiteCollection(siteId) + relId;
                    }

                    element.setAttribute("id", id);

                    ContentResource r = null;

                    // if the body-location attribute points at another file for the body, get this
                    String bodyLocation = StringUtils.trimToNull(element.getAttribute("body-location"));
                    if (bodyLocation != null) {
                        // the file name is relative to the archive file
                        String bodyPath = StringUtil.fullReference(archivePath, bodyLocation);

                        // get a stream from the file
                        FileInputStream in = new FileInputStream(bodyPath);

                        // resource: add if missing
                        r = mergeResource(element, in);
                    }

                    else {
                        // resource: add if missing
                        r = mergeResource(element);
                    }

                    if (r == null) {
                        results.append("resource: " + id + " already exists and was not replaced.\n");
                    } else {
                        results.append("resource: " + id + " imported.\n");
                    }
                }
            }
        }
    } catch (Exception any) {
        results.append("import interrputed: " + any.toString() + "\n");
        M_log.error("mergeContent(): exception: ", any);
    }

    return results.toString();

}

From source file:org.sakaiproject.message.impl.BaseMessageService.java

/**
 * {@inheritDoc}//from w w  w. j  a v a2  s.c  o m
 */
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames,
        Map userIdTrans, Set userListAllowImport) {
    // get the system name: FROM_WT, FROM_CT, FROM_SAKAI
    String source = "";
    // root: <service> node
    Node parent = root.getParentNode(); // parent: <archive> node containing "system"
    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    HashSet userSet = (HashSet) userListAllowImport;

    Map ids = new HashMap();

    // prepare the buffer for the results log
    StringBuilder results = new StringBuilder();

    // get the channel associated with this site
    String channelRef = channelReference(siteId, SiteService.MAIN_CONTAINER);

    int count = 0;

    try {
        MessageChannel channel = null;
        try {
            channel = getChannel(channelRef);
        } catch (IdUnusedException e) {
            MessageChannelEdit edit = addChannel(channelRef);
            commitChannel(edit);
            channel = edit;
        }

        // pass the DOM to get new message ids, record the mapping from old to new, 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;

                // get the "channel" child
                if (element2.getTagName().equals("channel")) {
                    NodeList children3 = element2.getChildNodes();
                    final 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;

                            parseMergeChannelExtra(element3, channelRef);

                            // for "message" children
                            if (element3.getTagName().equals("message")) {
                                // get the header child
                                NodeList children4 = element3.getChildNodes();
                                final int length4 = children4.getLength();
                                for (int i4 = 0; i4 < length4; i4++) {
                                    Node child4 = children4.item(i4);
                                    if (child4.getNodeType() == Node.ELEMENT_NODE) {
                                        Element element4 = (Element) child4;

                                        // for "header" children
                                        if (element4.getTagName().equals("header")) {
                                            String oldUserId = element4.getAttribute("from");

                                            // userIdTrans is not empty only when from WT
                                            if (!userIdTrans.isEmpty()) {
                                                if (userIdTrans.containsKey(oldUserId)) {
                                                    element4.setAttribute("from",
                                                            (String) userIdTrans.get(oldUserId));
                                                }
                                            }

                                            // adjust the id
                                            String oldId = element4.getAttribute("id");
                                            String newId = m_idManager.createUuid();
                                            ids.put(oldId, newId);
                                            element4.setAttribute("id", newId);

                                            // get the attachment kids
                                            NodeList children5 = element4.getChildNodes();
                                            final int length5 = children5.getLength();
                                            for (int i5 = 0; i5 < length5; i5++) {
                                                Node child5 = children5.item(i5);
                                                if (child5.getNodeType() == Node.ELEMENT_NODE) {
                                                    Element element5 = (Element) child5;

                                                    // for "attachment" children
                                                    if (element5.getTagName().equals("attachment")) {
                                                        // map the attachment area folder name
                                                        String oldUrl = element5.getAttribute("relative-url");
                                                        if (oldUrl.startsWith("/content/attachment/")) {
                                                            String 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(15 + fromSiteId.length());
                                                            element5.setAttribute("relative-url",
                                                                    Validator.escapeQuestionMark(newUrl));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // merge synoptic tool
                else if (element2.getTagName().equals(SYNOPTIC_TOOL)) {
                    Site site = m_siteService.getSite(siteId);
                    ToolConfiguration synTool = site.getToolForCommonId("sakai.synoptic." + getLabel());
                    Properties synProps = synTool.getPlacementConfig();

                    NodeList synPropNodes = element2.getChildNodes();
                    for (int props = 0; props < synPropNodes.getLength(); props++) {
                        Node propsNode = synPropNodes.item(props);
                        if (propsNode.getNodeType() == Node.ELEMENT_NODE) {
                            Element synPropEl = (Element) propsNode;
                            if (synPropEl.getTagName().equals(PROPERTIES)) {
                                NodeList synProperties = synPropEl.getChildNodes();
                                for (int p = 0; p < synProperties.getLength(); p++) {
                                    Node propertyNode = synProperties.item(p);
                                    if (propertyNode.getNodeType() == Node.ELEMENT_NODE) {
                                        Element propEl = (Element) propertyNode;
                                        if (propEl.getTagName().equals(PROPERTY)) {
                                            String propName = propEl.getAttribute(NAME);
                                            String propValue = propEl.getAttribute(VALUE);

                                            if (propName != null && propName.length() > 0 && propValue != null
                                                    && propValue.length() > 0) {
                                                if (propName.equals(CHANNEL_PROP)) {
                                                    int index = propValue.lastIndexOf("/");
                                                    propValue = propValue.substring(index + 1);
                                                    if (propValue != null && propValue.length() > 0) {
                                                        String synChannelRef = channelReference(siteId,
                                                                propValue);
                                                        try {
                                                            MessageChannelEdit c = editChannel(synChannelRef);
                                                            synProps.setProperty(propName,
                                                                    channelRef.toString());
                                                        } catch (IdUnusedException e) {
                                                            // do not add channel b/c it does not exist in tool
                                                            M_log.warn(
                                                                    "Synoptic Tool Channel option not added- "
                                                                            + synChannelRef + ":" + e);
                                                        }
                                                    }
                                                } else {
                                                    synProps.setProperty(propName, propValue);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Session session = m_sessionManager.getCurrentSession();
                    ToolSession toolSession = session.getToolSession(synTool.getId());
                    if (toolSession.getAttribute(STATE_UPDATE) == null) {
                        toolSession.setAttribute(STATE_UPDATE, STATE_UPDATE);
                    }
                    m_siteService.save(site);
                }
            }
        }

        // one more pass to update reply-to (now we have a complte id mapping),
        // and we are ready then to create the message
        children2 = root.getChildNodes();
        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;

                // get the "channel" child
                if (element2.getTagName().equals("channel")) {
                    NodeList children3 = element2.getChildNodes();
                    final 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;

                            // for "message" children
                            if (element3.getTagName().equals("message")) {
                                // a flag showing if continuing merging the message
                                boolean goAhead = true;

                                // get the header child
                                NodeList children4 = element3.getChildNodes();
                                final int length4 = children4.getLength();
                                for (int i4 = 0; i4 < length4; i4++) {
                                    Node child4 = children4.item(i4);
                                    if (child4.getNodeType() == Node.ELEMENT_NODE) {
                                        Element element4 = (Element) child4;

                                        // for "header" children
                                        if (element4.getTagName().equals("header")) {
                                            // adjust the replyTo
                                            String oldReplyTo = element4.getAttribute("replyTo");
                                            if ((oldReplyTo != null) && (oldReplyTo.length() > 0)) {
                                                String newReplyTo = (String) ids.get(oldReplyTo);
                                                if (newReplyTo != null) {
                                                    element4.setAttribute("replyTo", newReplyTo);
                                                }
                                            }

                                            // only merge this message when the userId has the right role
                                            String fUserId = element4.getAttribute("from");
                                            if (!fUserId.equalsIgnoreCase("postmaster")
                                                    && !userSet.contains(element4.getAttribute("from"))) {
                                                goAhead = false;
                                            }
                                            // TODO: reall want a draft? -ggolden
                                            // set draft status based upon property setting
                                            if ("false".equalsIgnoreCase(m_serverConfigurationService
                                                    .getString("import.importAsDraft"))) {
                                                String draftAttribute = element4.getAttribute("draft");
                                                if (draftAttribute.equalsIgnoreCase("true")
                                                        || draftAttribute.equalsIgnoreCase("false"))
                                                    element4.setAttribute("draft", draftAttribute);
                                                else
                                                    element4.setAttribute("draft", "true");
                                            } else {
                                                element4.setAttribute("draft", "true");
                                            }
                                        }
                                    }
                                }

                                // merge if ok
                                if (goAhead) {
                                    // create a new message in the channel
                                    MessageEdit edit = channel.mergeMessage(element3);
                                    // commit the new message without notification
                                    channel.commitMessage(edit, NotificationService.NOTI_NONE);
                                    count++;
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception any) {
        M_log.warn("mergeMessages(): exception in handling " + serviceName() + " : ", any);
    }

    results.append("merging " + getLabel() + " channel " + channelRef + " (" + count + ") messages.\n");
    return results.toString();

}

From source file:org.sakaiproject.portal.xsltcharon.impl.XsltRenderContext.java

protected Element createPageCategories(Document doc, List pageTools) throws ToolRenderException {
    Element categories = doc.createElement("categories");

    int index = 0;
    String lastCategory = null;//from  ww w  .j ava2 s.  c o m
    Element lastCategoryElement = null;
    for (Iterator<Map> i = pageTools.iterator(); i.hasNext();) {
        Map page = i.next();
        Map pageProps = (Map) page.get("pageProps");
        String currentCategory = (String) pageProps.get("sitePage.pageCategory"); //todo put the static final here

        if (currentCategory == null || !isDisplayToolCategories()) {
            lastCategory = null;
            lastCategoryElement = null;
            categories.appendChild(createUncategorizedPage(doc, page, index));
            index++;
        } else if (currentCategory.equals(lastCategory)) {
            lastCategoryElement.appendChild(createPageXml(doc, page));
            if ("true".equalsIgnoreCase(page.get("current").toString())) {
                ((Element) lastCategoryElement.getParentNode()).setAttribute("selected", "true");
            }
        } else {
            lastCategory = currentCategory;
            lastCategoryElement = createCategory(doc, categories, page, currentCategory, index);
            lastCategoryElement.appendChild(createPageXml(doc, page));
            categories.appendChild(lastCategoryElement.getParentNode());
            index++;
        }
    }

    return categories;
}