Example usage for org.w3c.dom Element getTagName

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

Introduction

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

Prototype

public String getTagName();

Source Link

Document

The name of the element.

Usage

From source file:org.osaf.cosmo.cmp.UserResource.java

/**
 *///from w  ww  . ja  v  a 2  s. c  o m
protected void setUser(Document doc, EntityFactory factory) {
    if (doc == null) {
        return;
    }

    Element root = doc.getDocumentElement();
    if (!DomUtil.matches(root, EL_USER, NS_CMP)) {
        throw new CmpException("root element not user");
    }

    for (ElementIterator i = DomUtil.getChildren(root); i.hasNext();) {
        Element e = i.nextElement();

        if (DomUtil.matches(e, EL_USERNAME, NS_CMP)) {
            if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) {
                throw new CmpException("root user's username may not " + "be changed");
            }
            user.setUsername(DomUtil.getTextTrim(e));
        } else if (DomUtil.matches(e, EL_PASSWORD, NS_CMP)) {
            user.setPassword(DomUtil.getTextTrim(e));
        } else if (DomUtil.matches(e, EL_FIRSTNAME, NS_CMP)) {
            if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) {
                throw new CmpException("root user's first name may not " + "be changed");
            }
            user.setFirstName(DomUtil.getTextTrim(e));
        } else if (DomUtil.matches(e, EL_LASTNAME, NS_CMP)) {
            if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) {
                throw new CmpException("root user's last name may not " + "be changed");
            }
            user.setLastName(DomUtil.getTextTrim(e));
        } else if (DomUtil.matches(e, EL_EMAIL, NS_CMP)) {
            user.setEmail(DomUtil.getTextTrim(e));
        } else if (DomUtil.matches(e, EL_ADMINISTRATOR, NS_CMP)) {
            if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)
                    && !DomUtil.getTextTrim(e).toLowerCase().equals("true")) {
                throw new CmpException("root user's admin status " + "must be true");
            }
            user.setAdmin(Boolean.parseBoolean(DomUtil.getTextTrim(e)));
        } else if (DomUtil.matches(e, EL_LOCKED, NS_CMP)) {
            if (user.isOverlord())
                throw new CmpException("root user cannot be locked");
            user.setLocked(Boolean.parseBoolean(DomUtil.getTextTrim(e)));
        } else if (DomUtil.matches(e, EL_SUBSCRIPTION, NS_CMP)) {
            String uuid = DomUtil.getTextTrim(e);
            String ticketKey = e.getAttribute(ATTR_SUBSCRIPTION_TICKET);
            String displayName = e.getAttribute(ATTR_SUBSCRIPTION_NAME);
            if (displayName == null)
                throw new CmpException("Subscription requires a display name");
            if (uuid == null)
                throw new CmpException("Subscription requires a collection uuid");
            if (ticketKey == null)
                throw new CmpException("Subscription requires a ticket key");
            if (user.getSubscription(displayName) != null)
                throw new CmpException("Subscription with this name already exists");
            CollectionSubscription subscription = factory.createCollectionSubscription();
            subscription.setDisplayName(displayName);
            subscription.setCollectionUid(uuid);
            subscription.setTicketKey(ticketKey);
            user.addSubscription(subscription);
        } else if (DomUtil.matches(e, EL_PREFERENCE, NS_CMP)) {
            String prefKey = e.getAttribute(ATTR_PREFERENCE_KEY);
            String prefValue = e.getAttribute(ATTR_PREFERENCE_VALUE);
            if (prefKey == null)
                throw new CmpException("Preference requires a key");
            if (prefValue == null)
                throw new CmpException("Preference requires a value");
            if (user.getPreference(prefKey) != null)
                throw new CmpException("Preference with this key already exists");
            Preference preference = factory.createPreference(prefKey, prefValue);

            user.addPreference(preference);
        } else {
            throw new CmpException("unknown user attribute element " + e.getTagName());
        }
    }
}

From source file:org.osaf.cosmo.dav.caldav.report.CaldavOutputFilter.java

/**
 * Returns an <code>OutputFilter</code> representing the given
 * <code>&lt;C:calendar-data/&gt;> element.
 *//* ww w.  j  av  a  2s.c  om*/
public static OutputFilter createFromXml(Element cdata) throws DavException {
    OutputFilter result = null;
    Period expand = null;
    Period limit = null;
    Period limitfb = null;

    String contentType = DomUtil.getAttribute(cdata, ATTR_CALDAV_CONTENT_TYPE, NAMESPACE_CALDAV);
    if (contentType != null && !contentType.equals(ICALENDAR_MEDIA_TYPE))
        throw new UnsupportedCalendarDataException(contentType);
    String version = DomUtil.getAttribute(cdata, ATTR_CALDAV_CONTENT_TYPE, NAMESPACE_CALDAV);
    if (version != null && !version.equals(ICALENDAR_VERSION))
        throw new UnsupportedCalendarDataException();

    // Look at each child element of calendar-data
    for (ElementIterator iter = DomUtil.getChildren(cdata); iter.hasNext();) {

        Element child = iter.nextElement();
        if (ELEMENT_CALDAV_COMP.equals(child.getLocalName())) {

            // At the top-level of calendar-data there should only be one
            // <comp> element as VCALENDAR components are the only top-level
            // components allowed in iCalendar data
            if (result != null)
                return null;

            // Get required name attribute and verify it is VCALENDAR
            String name = DomUtil.getAttribute(child, ATTR_CALDAV_NAME, null);
            if ((name == null) || !Calendar.VCALENDAR.equals(name))
                return null;

            // Now parse filter item
            result = parseCalendarDataComp(child);

        } else if (ELEMENT_CALDAV_EXPAND.equals(child.getLocalName())) {
            expand = parsePeriod(child, true);
        } else if (ELEMENT_CALDAV_LIMIT_RECURRENCE_SET.equals(child.getLocalName())) {
            limit = parsePeriod(child, true);
        } else if (ELEMENT_CALDAV_LIMIT_FREEBUSY_SET.equals(child.getLocalName())) {
            limitfb = parsePeriod(child, true);
        } else {
            log.warn("Ignoring child " + child.getTagName() + " of " + cdata.getTagName());
        }
    }

    // Now add any limit/expand options, creating a filter if one is not
    // already present
    if ((result == null) && ((expand != null) || (limit != null) || (limitfb != null))) {
        result = new OutputFilter("VCALENDAR");
        result.setAllSubComponents();
        result.setAllProperties();
    }
    if (expand != null) {
        result.setExpand(expand);
    }
    if (limit != null) {
        result.setLimit(limit);
    }
    if (limitfb != null) {
        result.setLimitfb(limitfb);
    }

    return result;
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.MondrianUtil.java

private static String parseXmlDocument(final InputStream stream)
        throws ResourceCreationException, ParserConfigurationException {
    final DocumentBuilderFactory dbf = XMLParserFactoryProducer.createSecureDocBuilderFactory();
    dbf.setNamespaceAware(true);//from  w ww.  java2s  .c  om
    dbf.setValidating(false);

    try {
        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(ParserEntityResolver.getDefaultResolver());
        db.setErrorHandler(new LoggingErrorHandler());
        final InputSource input = new InputSource(stream);
        final Document document = db.parse(input);
        final Element documentElement = document.getDocumentElement();
        if ("Schema".equals(documentElement.getTagName())) { // NON-NLS
            return documentElement.getAttribute("name");
        }
        return null;
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document.", e);
    } catch (IOException e) {
        throw new ResourceCreationException("Unable to parse the document.", e);
    }
}

From source file:org.pepstock.jem.jbpm.JBpmFactory.java

/**
 * Validates the JCL content, calling the JBPM API 
 * @param jcl default JCL to store into job
 * @param content JCL content/* w w w.  j a v  a 2s. co  m*/
 * @throws JBpmException if any error occurs
 */
private void validate(Jcl jcl, String content) throws JBpmException {
    // read the BPMN Metadata, loading in properties object
    Properties p = new Properties();

    // creates all readers
    StringReader reader = new StringReader(content);
    InputSource source = new InputSource(reader);
    SimpleRuntimeEnvironment jbpmEnvironment = null;
    String jobName = null;

    // SCANS JCL to get JOBNAME
    // JOBNAME = attribute ID of PROCESS element
    try {
        // creates DOM objects
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setIgnoringComments(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(source);

        // scan XML to read comment
        NodeList nl = doc.getDocumentElement().getChildNodes();
        // scans all nodes
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node.getNodeType() == Element.ELEMENT_NODE) {
                Element el = (Element) node;

                String tagName = null;
                // checks if name space
                if (el.getTagName().contains(":")) {
                    tagName = StringUtils.substringAfter(el.getTagName(), ":");
                } else {
                    tagName = el.getTagName();
                }
                // checks only if is a PROCESS element
                if (tagName.equalsIgnoreCase(PROCESS_XML_ELEMENT)) {
                    // gets ID attribute to set JOBNAME
                    String jobNameAttr = el.getAttribute(ID_XML_ATTRIBUTE);
                    if (jobNameAttr != null) {
                        // puts on properties
                        p.setProperty(JBpmKeys.JBPM_JOB_NAME, jobNameAttr);
                    } else {
                        throw new JBpmException(JBpmMessage.JEMM031E);
                    }
                }
            }
        }

        // checks if project has attribute name, if yes, uses it as JOB NAME
        // otherwise get the JEM property to define it
        jobName = p.getProperty(JBpmKeys.JBPM_JOB_NAME);

        // Anyway job name can't be null. if yes, exception occurs
        if (jobName == null) {
            throw new JBpmException(JBpmMessage.JEMM031E);
        }
        // loads JCL jobname
        jcl.setJobName(jobName);

        // creates JBPM environment to check BPMN2 syntax
        SimpleRegisterableItemsFactory factory = new SimpleRegisterableItemsFactory();
        jbpmEnvironment = new SimpleRuntimeEnvironment(factory);
        jbpmEnvironment.setUsePersistence(false);
        Resource res = ResourceFactory.newReaderResource(new StringReader(content),
                CharSet.DEFAULT_CHARSET_NAME);
        jbpmEnvironment.addAsset(res, ResourceType.BPMN2);
        // gets process to read metadata
        org.kie.api.definition.process.Process process = jbpmEnvironment.getKieBase().getProcess(jobName);
        // if process is null, exception
        if (process == null) {
            throw new JBpmException(JBpmMessage.JEMM063E);
        }
        // loads all METADATA
        p.putAll(process.getMetaData());

        // check again because you could put the job name on metadata
        jcl.setJobName(p.getProperty(JBpmKeys.JBPM_JOB_NAME));

        // loads the JBPM process ID in a map to reuse when a JBPM task will be scheduled
        Map<String, Object> jclMap = new HashMap<String, Object>();
        jclMap.put(JBpmKeys.JBPM_JOB_NAME, jobName);
        jcl.setProperties(jclMap);

    } catch (DOMException e) {
        throw new JBpmException(JBpmMessage.JEMM047E, e, e.getMessage());
    } catch (ParserConfigurationException e) {
        throw new JBpmException(JBpmMessage.JEMM047E, e, e.getMessage());
    } catch (SAXException e) {
        throw new JBpmException(JBpmMessage.JEMM047E, e, e.getMessage());
    } catch (Exception e) {
        throw new JBpmException(JBpmMessage.JEMM047E, e, e.getMessage());
    } finally {
        // clean up of JBPM environment
        if (jbpmEnvironment != null && jobName != null) {
            try {
                jbpmEnvironment.getKieBase().removeProcess(jobName);
            } catch (Exception e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
        }
    }

    // if I'm here, JCL is correct

    // extracts the locking scope and checks if the value is correct
    // the value is not save in JCL because is not helpful to node but
    // at runtime so it will be read again from ANT listener
    String lockingScopeProperty = p.getProperty(JBpmKeys.JBPM_LOCKING_SCOPE);
    if (lockingScopeProperty != null && !lockingScopeProperty.equalsIgnoreCase(JBpmKeys.JBPM_JOB_SCOPE)
            && !lockingScopeProperty.equalsIgnoreCase(JBpmKeys.JBPM_STEP_SCOPE)
            && !lockingScopeProperty.equalsIgnoreCase(JBpmKeys.JBPM_TASK_SCOPE)) {
        throw new JBpmException(JBpmMessage.JEMM032E, JBpmKeys.JBPM_LOCKING_SCOPE, lockingScopeProperty);
    }

    // Extracts from ANT enviroment property
    String environment = p.getProperty(JBpmKeys.JBPM_ENVIRONMENT);
    // if null, uses current environment assigned to JEM NODE
    if (environment == null) {
        environment = Main.EXECUTION_ENVIRONMENT.getEnvironment();
    }

    // Extracts from ANT domain property
    String domain = p.getProperty(JBpmKeys.JBPM_DOMAIN);
    // if null, uses domain default
    if (domain == null) {
        domain = Jcl.DEFAULT_DOMAIN;
    }

    // Extracts from ANT email addresses notification property
    String emailAddresses = p.getProperty(JBpmKeys.JBPM_EMAILS_NOTIFICATION);
    if (null != emailAddresses) {
        jcl.setEmailNotificationAddresses(emailAddresses);
    }
    // Extracts from ANT affinity property
    String affinity = p.getProperty(JBpmKeys.JBPM_AFFINITY);
    // if null, uses affinity default
    if (affinity == null) {
        affinity = Jcl.DEFAULT_AFFINITY;
    }

    // Extracts from ANT user property
    String user = p.getProperty(JBpmKeys.JBPM_USER);
    if (null != user) {
        jcl.setUser(user);
    }

    // Extracts from ANT classpath property
    String classPath = p.getProperty(JBpmKeys.JBPM_CLASSPATH);
    // if classpath is not set, changes if some variables are in
    if (classPath != null) {
        jcl.setClassPath(super.resolvePathNames(classPath, ConfigKeys.JEM_CLASSPATH_PATH_NAME));
    }

    // Extracts from ANT prior classpath property
    String priorClassPath = p.getProperty(JBpmKeys.JBPM_PRIOR_CLASSPATH);
    // if classpath is not set, changes if some variables are in
    if (priorClassPath != null) {
        jcl.setPriorClassPath(super.resolvePathNames(priorClassPath, ConfigKeys.JEM_CLASSPATH_PATH_NAME));
    }

    // Extracts from ANT memory property. If missing, default is 256 
    int memory = Parser.parseInt(p.getProperty(JBpmKeys.JBPM_MEMORY), Jcl.DEFAULT_MEMORY);
    // Extracts from ANT hold property. If missing, default is FALSE
    boolean hold = Parser.parseBoolean(p.getProperty(JBpmKeys.JBPM_HOLD), false);
    // Extracts from ANT priority property. If missing, default is 10
    int priority = Parser.parseInt(p.getProperty(JBpmKeys.JBPM_PRIORITY), Jcl.DEFAULT_PRIORITY);

    // saves all info inside of JCL object for further computing

    jcl.setEnvironment(environment);
    jcl.setDomain(domain);
    jcl.setAffinity(affinity);
    jcl.setHold(hold);
    jcl.setPriority(priority);
    jcl.setMemory(memory);

}

From source file:org.pepstock.jem.jbpm.XmlParser.java

/**
 * Returns the tag name , removing the namespace
 * @param node node to use to extract the tag name
 * @return tag name of node/*from   ww w .  ja  v a 2  s.co  m*/
 */
private static String getElementName(Node node) {
    // ONLY if is a element returns the name
    if (node.getNodeType() == Element.ELEMENT_NODE) {
        Element el = (Element) node;
        String tagName = null;
        // checks if name space
        if (el.getTagName().contains(":")) {
            tagName = StringUtils.substringAfter(el.getTagName(), ":");
        } else {
            tagName = el.getTagName();
        }
        return tagName;
    }
    return null;
}

From source file:org.rhq.core.clientapi.agent.metadata.i18n.PropertiesGenerator.java

private void generateNode(Element element, String partialKey) {
    String childKey = partialKey + element.getTagName();

    String keyAttribute = TAG_KEY_ATTRIBUTES.get(element.getNodeName());
    if (keyAttribute == null) {
        keyAttribute = "name";
    }/*  ww  w  .  j a  v a  2  s. c o  m*/

    String tagKey = element.getAttribute(keyAttribute);
    if ((tagKey != null) && (tagKey.length() > 0)) {
        childKey += "[" + tagKey + "].";
    } else {
        childKey += ".";
    }

    generateAtributes(element, childKey);

    generateChildren(element, childKey);
}

From source file:org.rhq.core.clientapi.agent.metadata.i18n.PropertiesGenerator.java

private void generateAtributes(Element element, String partialKey) {
    if (element.getNodeName().equals("server") || element.getNodeName().equals("service")) {
        this.contentWriter.println();
    }/*  www. j a v a 2 s  . c om*/

    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Node n = attrs.item(i);

        Set<String> localizedProperties = TAG_LOCALIZED_ATTRIBUTES.get(element.getTagName());
        if ((localizedProperties != null) && localizedProperties.contains(n.getNodeName())) {
            String key = partialKey + n.getNodeName();
            String value = "    # " + n.getNodeValue();

            if (!this.previousProperties.containsKey(key)) {
                this.contentWriter.println(key + "=" + value);
                properties.put(key, value);
            }
        }
    }
}

From source file:org.sakaiproject.announcement.impl.DbAnnouncementService.java

/**
 * fill in the draft and owner db fields
 *//*  ww w  . ja va 2  s. co  m*/
protected void convertToDraft() {
    M_log.info("convertToDraft");

    try {
        // get a connection
        final Connection connection = m_sqlService.borrowConnection();
        boolean wasCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);

        // read all message records that need conversion
        String sql = "select CHANNEL_ID, MESSAGE_ID, XML from " + m_rTableName /* + " where OWNER is null" */;
        m_sqlService.dbRead(connection, sql, null, new SqlReader() {
            private int count = 0;

            public Object readSqlResultRecord(ResultSet result) {
                try {
                    // create the Resource from the db xml
                    String channelId = result.getString(1);
                    String messageId = result.getString(2);
                    String xml = result.getString(3);

                    // read the xml
                    Document doc = Xml.readDocumentFromString(xml);

                    // verify the root element
                    Element root = doc.getDocumentElement();
                    if (!root.getTagName().equals("message")) {
                        M_log.warn("convertToDraft(): XML root element not message: " + root.getTagName());
                        return null;
                    }
                    Message m = new BaseMessageEdit(null, root);

                    // pick up the fields
                    String owner = m.getHeader().getFrom().getId();
                    boolean draft = m.getHeader().getDraft();

                    // update
                    String update = "update " + m_rTableName
                            + " set OWNER = ?, DRAFT = ? where CHANNEL_ID = ? and MESSAGE_ID = ?";
                    Object fields[] = new Object[4];
                    fields[0] = owner;
                    fields[1] = (draft ? "1" : "0");
                    fields[2] = channelId;
                    fields[3] = messageId;
                    boolean ok = m_sqlService.dbWrite(connection, update, fields);

                    if (!ok)
                        M_log.info("convertToDraft: channel: " + channelId + " message: " + messageId
                                + " owner: " + owner + " draft: " + draft + " ok: " + ok);

                    count++;
                    if (count % 100 == 0) {
                        M_log.info("convertToDraft: " + count);
                    }
                    return null;
                } catch (Throwable ignore) {
                    return null;
                }
            }
        });

        connection.commit();
        connection.setAutoCommit(wasCommit);
        m_sqlService.returnConnection(connection);
    } catch (Throwable t) {
        M_log.warn("convertToDraft: failed: " + t);
    }

    M_log.info("convertToDraft: done");
}

From source file:org.sakaiproject.announcement.impl.DbAnnouncementService.java

/**
 * fill in the pubview db fields//from  ww w. j  a  va2  s  . c o m
 */
protected void convertToPubView() {
    M_log.info("convertToPubView");

    try {
        // get a connection
        final Connection connection = m_sqlService.borrowConnection();
        boolean wasCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);

        // read all message records that need conversion
        String sql = "select CHANNEL_ID, MESSAGE_ID, XML, PUBVIEW from " + m_rTableName;
        m_sqlService.dbRead(connection, sql, null, new SqlReader() {
            public Object readSqlResultRecord(ResultSet result) {
                try {
                    // create the Resource from the db xml
                    String channelId = result.getString(1);
                    String messageId = result.getString(2);
                    String xml = result.getString(3);
                    String pubViewSetting = result.getString(4);

                    // read the xml
                    Document doc = Xml.readDocumentFromString(xml);

                    // verify the root element
                    Element root = doc.getDocumentElement();
                    if (!root.getTagName().equals("message")) {
                        M_log.warn("convertToPubView(): XML root element not message: " + root.getTagName());
                        return null;
                    }
                    BaseMessageEdit m = new BaseMessageEdit(null, root);

                    // check if the record already has pub view set in the properties
                    boolean pubview = false;
                    if (m.getProperties().getProperty(ResourceProperties.PROP_PUBVIEW) != null) {
                        // pub view set in properties and in db indicates all is well with this one
                        if ("1".equals(pubViewSetting)) {
                            return null;
                        }

                        // having the property overrides any realm setting...
                        pubview = true;
                    }

                    // if we don't know pubview from the props, check the realm
                    else {
                        // m.getReference() won't work cause we didn't give it its channel...
                        Reference channel = m_entityManager.newReference(channelId);
                        String ref = messageReference(channel.getContext(), channel.getId(), m.getId());
                        pubview = getPubView(ref);

                        // if the pubview setting matches the db, and it's false, all is well
                        if ((!pubview) && ("0".equals(pubViewSetting))) {
                            return null;
                        }
                    }

                    // update those that have no pubview
                    if (!pubview) {
                        String update = "update " + m_rTableName
                                + " set PUBVIEW = ? where CHANNEL_ID = ? and MESSAGE_ID = ?";
                        Object fields[] = new Object[3];
                        fields[0] = "0";
                        fields[1] = channelId;
                        fields[2] = messageId;
                        boolean ok = m_sqlService.dbWrite(connection, update, fields);

                        if (!ok)
                            M_log.info("convertToPubView: channel: " + channelId + " message: " + messageId
                                    + " pubview: " + pubview + " ok: " + ok);
                    }

                    // update those that have pubview
                    else {
                        // set the property
                        m.getPropertiesEdit().addProperty(ResourceProperties.PROP_PUBVIEW,
                                Boolean.TRUE.toString());

                        // form updated XML
                        doc = Xml.createDocument();
                        m.toXml(doc, new Stack());
                        xml = Xml.writeDocumentToString(doc);

                        String update = "update " + m_rTableName
                                + " set PUBVIEW = ?, XML = ? where CHANNEL_ID = ? and MESSAGE_ID = ?";
                        Object fields[] = new Object[4];
                        fields[0] = "1";
                        fields[1] = xml;
                        fields[2] = channelId;
                        fields[3] = messageId;
                        boolean ok = m_sqlService.dbWrite(connection, update, fields);

                        if (!ok)
                            M_log.info("convertToPubView: channel: " + channelId + " message: " + messageId
                                    + " pubview: " + pubview + " ok: " + ok);
                    }

                    return null;
                } catch (Throwable ignore) {
                    return null;
                }
            }
        });

        connection.commit();
        connection.setAutoCommit(wasCommit);
        m_sqlService.returnConnection(connection);
    } catch (Throwable t) {
        M_log.warn("convertToPubView: failed: " + t);
    }

    M_log.info("convertToPubView: done");
}

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

/**
* Read in an archive file and merge the entries into the specified site.
* @param fileName The site name (for the archive file) to read from.
* @param siteId The id of the site to merge the content into.
* @param results A buffer to accumulate result messages.
* @param attachmentNames A map of old to new attachment names.
* @param useIdTrans A map of old WorkTools id to new Ctools id
* @param creatorId The creator id//from w  ww. j  av a2  s. c om
*/
protected void processMerge(String fileName, String siteId, StringBuilder results, Map attachmentNames,
        String creatorId) {
    // correct for windows backslashes
    fileName = fileName.replace('\\', '/');

    if (M_log.isDebugEnabled())
        M_log.debug("merge(): processing file: " + fileName);

    Site theSite = null;
    try {
        theSite = SiteService.getSite(siteId);
    } catch (IdUnusedException ignore) {
    }

    // read the whole file into a DOM
    Document doc = Xml.readDocument(fileName);
    if (doc == null) {
        results.append("Error reading xml from: " + fileName + "\n");
        return;
    }

    // verify the root element
    Element root = doc.getDocumentElement();
    if (!root.getTagName().equals("archive")) {
        results.append("File: " + fileName + " does not contain archive xml.  Found this root tag: "
                + root.getTagName() + "\n");
        return;
    }

    // get the from site id
    String fromSite = root.getAttribute("source");
    String system = root.getAttribute("system");

    // the children
    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;

        // look for site stuff
        if (element.getTagName().equals(SiteService.APPLICATION_ID)) {
            //if the xml file is from WT site, merge it with the translated user ids
            if (system.equalsIgnoreCase(FROM_WT))
                mergeSite(siteId, fromSite, element, userIdTrans, creatorId);
            else
                mergeSite(siteId, fromSite, element, new HashMap()/*empty userIdMap */, creatorId);
        } else if (element.getTagName().equals(UserDirectoryService.APPLICATION_ID)) {
            try {
                // merge the users in only when they are from WorkTools
                if (system.equalsIgnoreCase(FROM_WT)) {
                    String msg = mergeUsers(element, userIdTrans);
                    results.append(msg);
                }
            } catch (Exception any) {
            }
        }

        else {
            // we need a site now
            if (theSite == null) {
                results.append("Site: " + siteId + " not found.\n");
                return;
            }

            // get the service name
            String serviceName = translateServiceName(element.getTagName());

            // get the service
            try {
                EntityProducer service = (EntityProducer) ComponentManager.get(serviceName);

                try {
                    String msg = "";
                    // if the xml file is from WT site, merge it with user id translation
                    if (system.equalsIgnoreCase(FROM_WT))
                        msg = service.merge(siteId, element, fileName, fromSite, attachmentNames, userIdTrans,
                                new HashSet());
                    else if ((system.equalsIgnoreCase(FROM_SAKAI) || system.equalsIgnoreCase(FROM_SAKAI_2_8))
                            && (checkSakaiService(serviceName)))
                        msg = service.merge(siteId, element, fileName, fromSite, attachmentNames,
                                new HashMap() /* empty userIdTran map */, usersListAllowImport);
                    else if (system.equalsIgnoreCase(FROM_CT))
                        msg = service.merge(siteId, element, fileName, fromSite, attachmentNames,
                                new HashMap() /* empty userIdTran map */, usersListAllowImport);

                    results.append(msg);
                } catch (Throwable t) {
                    results.append("Error merging: " + serviceName + " in file: " + fileName + " : "
                            + t.toString() + "\n");
                }
            } catch (Throwable t) {
                results.append("Did not recognize the resource service: " + serviceName + " in file: "
                        + fileName + "\n");
            }
        }
    }

}