Example usage for org.w3c.dom Element hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private synchronized String duplicate(final Document originalDom, final Element originalRootElement,
        final Element patchElement) throws Exception {

    boolean isdone = false;
    Element parentElement = null;

    DuplicateChildElementObject childElementObject = isChildElement(originalRootElement, patchElement);
    if (!childElementObject.isNeedDuplicate()) {
        isdone = true;//from   w w w. j  av a  2s .  c  o  m
        parentElement = childElementObject.getElement();
    } else if (childElementObject.getElement() != null) {
        parentElement = childElementObject.getElement();
    } else {
        parentElement = originalRootElement;
    }

    String son_name = patchElement.getNodeName();

    Element subITEM = null;
    if (!isdone) {
        subITEM = originalDom.createElement(son_name);

        if (patchElement.hasChildNodes()) {
            if (patchElement.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                subITEM.setTextContent(patchElement.getTextContent());

            }
        }

        if (patchElement.hasAttributes()) {
            NamedNodeMap attributes = patchElement.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                String attribute_name = attributes.item(i).getNodeName();
                String attribute_value = attributes.item(i).getNodeValue();
                subITEM.setAttribute(attribute_name, attribute_value);
            }
        }
        parentElement.appendChild(subITEM);
    } else {
        subITEM = parentElement;
    }

    NodeList sub_messageItems = patchElement.getChildNodes();
    int sub_item_number = sub_messageItems.getLength();
    logger.debug("patchEl: " + DomUtils.elementToString(patchElement) + "length: " + sub_item_number);
    if (sub_item_number == 0) {
        isdone = true;
    } else {
        for (int j = 0; j < sub_item_number; j++) {
            if (sub_messageItems.item(j).getNodeType() == Node.ELEMENT_NODE) {
                Element sub_messageItem = (Element) sub_messageItems.item(j);
                logger.debug("node name: " + DomUtils.elementToString(subITEM) + " node type: "
                        + subITEM.getNodeType());
                duplicate(originalDom, subITEM, sub_messageItem);
            }

        }
    }

    return (parentElement != null) ? DomUtils.elementToString(parentElement) : "";
}

From source file:jp.co.acroquest.jsonic.Formatter.java

public boolean format(final JSON json, final Context context, final Object src, final Object o,
        final OutputSource out) throws Exception {
    Element elem = (Element) o;
    out.append('[');
    StringFormatter.serialize(context, elem.getTagName(), out);

    out.append(',');
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth() + 1; j++)
            out.append('\t');
    }/*w ww.  ja  va2 s.  com*/
    out.append('{');
    if (elem.hasAttributes()) {
        NamedNodeMap names = elem.getAttributes();
        for (int i = 0; i < names.getLength(); i++) {
            if (i != 0) {
                out.append(',');
            }
            if (context.isPrettyPrint() && names.getLength() > 1) {
                out.append('\n');
                for (int j = 0; j < context.getDepth() + 2; j++)
                    out.append('\t');
            }
            Node node = names.item(i);
            if (node instanceof Attr) {
                StringFormatter.serialize(context, node.getNodeName(), out);
                out.append(':');
                if (context.isPrettyPrint())
                    out.append(' ');
                StringFormatter.serialize(context, node.getNodeValue(), out);
            }
        }
        if (context.isPrettyPrint() && names.getLength() > 1) {
            out.append('\n');
            for (int j = 0; j < context.getDepth() + 1; j++)
                out.append('\t');
        }
    }
    out.append('}');
    if (elem.hasChildNodes()) {
        NodeList nodes = elem.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Object value = nodes.item(i);
            if ((value instanceof Element) || (value instanceof CharacterData && !(value instanceof Comment))) {
                out.append(',');
                if (context.isPrettyPrint()) {
                    out.append('\n');
                    for (int j = 0; j < context.getDepth() + 1; j++)
                        out.append('\t');
                }
                context.enter(i + 2);
                value = json.preformatInternal(context, value);
                json.formatInternal(context, value, out);
                context.exit();
                if (out instanceof Flushable)
                    ((Flushable) out).flush();
            }
        }
    }
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth(); j++)
            out.append('\t');
    }
    out.append(']');
    return true;
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/**
 * Shows menu info in compact mode: <br/>
 * <code>//  w w  w .j ava2 s.co  m
 * &nbsp;&nbsp;/tribunales  [c_tribunales, visible]<br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;/tribunales?form  [i_tribunales_new, visible]<br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;/tribunales?page=1&size=${empty param.size ? 10 : param.size}  [i_tribunales_list, hidden]<br/>
 * </code>
 * 
 * @param element
 * @param tabSize
 * @return
 */
private String getCompactInfo(Element element, int tabSize) {
    StringBuilder builder = new StringBuilder();
    StringBuilder indent = new StringBuilder();

    // tab string to align children
    for (int i = 0; i < tabSize; i++) {
        indent.append(" ");
    }

    String url = element.getAttribute(URL);
    if (StringUtils.isNotBlank(url)) {
        builder.append(indent).append(url).append("  ");
    }

    // string containing "[ID, visibility]: "
    StringBuilder idVisibility = new StringBuilder();
    idVisibility.append("[").append(element.getAttribute("id"));
    String hidden = element.getAttribute(HIDDEN);
    if (!StringUtils.isNotBlank(hidden)) {
        hidden = "false"; // visible by default
    }
    if (Boolean.valueOf(hidden)) {
        idVisibility.append(", hidden");
    } else {
        idVisibility.append(", visible");
    }
    if (!StringUtils.isNotBlank(url)) {
        idVisibility.append(", no-URL");
    }
    idVisibility.append("]");

    // build Element info
    builder.append(idVisibility);

    // get children info
    if (element.hasChildNodes()) {
        builder.append("\n").append(getCompactInfo(element.getChildNodes(), tabSize + 10)).append("\n");
    } else {
        builder.append("\n"); // empty line
    }
    return builder.toString();
}

From source file:com.buaa.cfs.conf.Configuration.java

private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
    String name = UNKNOWN_RESOURCE;
    try {/*  w w  w.j a  v  a 2  s  . c o  m*/
        Object resource = wrapper.getResource();
        name = wrapper.getName();

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        //ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        //allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;
        boolean returnCachedProperties = false;

        if (resource instanceof URL) { // an URL resource
            doc = parse(builder, (URL) resource);
        } else if (resource instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) resource);
            doc = parse(builder, url);
        } else if (resource instanceof Path) { // a file resource
            // Can't use FileSystem API or we get an infinite loop
            // since FileSystem uses Configuration API.  Use java.io.File instead.
            File file = new File(((Path) resource).toUri().getPath()).getAbsoluteFile();
            if (file.exists()) {
                if (!quiet) {
                    LOG.debug("parsing File " + file);
                }
                doc = parse(builder, new BufferedInputStream(new FileInputStream(file)),
                        ((Path) resource).toString());
            }
        } else if (resource instanceof InputStream) {
            doc = parse(builder, (InputStream) resource, null);
            returnCachedProperties = true;
        } else if (resource instanceof Properties) {
            overlay(properties, (Properties) resource);
        } else if (resource instanceof Element) {
            root = (Element) resource;
        }

        if (root == null) {
            if (doc == null) {
                if (quiet) {
                    return null;
                }
                throw new RuntimeException(resource + " not found");
            }
            root = doc.getDocumentElement();
        }
        Properties toAddTo = properties;
        if (returnCachedProperties) {
            toAddTo = new Properties();
        }
        if (!"configuration".equals(root.getTagName()))
            LOG.fatal("bad conf file: top-level element not <configuration>");
        NodeList props = root.getChildNodes();
        DeprecationContext deprecations = deprecationContext.get();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element))
                continue;
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(toAddTo, new Resource(prop, name), quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            LinkedList<String> source = new LinkedList<String>();
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes())
                    attr = StringInterner.weakIntern(((Text) field.getFirstChild()).getData().trim());
                if ("value".equals(field.getTagName()) && field.hasChildNodes())
                    value = StringInterner.weakIntern(((Text) field.getFirstChild()).getData());
                if ("final".equals(field.getTagName()) && field.hasChildNodes())
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
                if ("source".equals(field.getTagName()) && field.hasChildNodes())
                    source.add(StringInterner.weakIntern(((Text) field.getFirstChild()).getData()));
            }
            source.add(name);

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null) {
                if (deprecations.getDeprecatedKeyMap().containsKey(attr)) {
                    DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(attr);
                    keyInfo.clearAccessed();
                    for (String key : keyInfo.newKeys) {
                        // update new keys with deprecated key's value
                        loadProperty(toAddTo, name, key, value, finalParameter,
                                source.toArray(new String[source.size()]));
                    }
                } else {
                    loadProperty(toAddTo, name, attr, value, finalParameter,
                            source.toArray(new String[source.size()]));
                }
            }
        }

        if (returnCachedProperties) {
            overlay(properties, toAddTo);
            return new Resource(toAddTo, name);
        }
        return null;
    } catch (IOException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    }
}

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * {@inheritDoc}/*from ww w.  j  av  a2 s. c o m*/
 */
public void addToJava2wsPlugin(JavaType serviceClass, String serviceName, String addressName,
        String fullyQualifiedTypeName) {

    // Get pom
    String pomPath = getPomFilePath();
    Validate.isTrue(pomPath != null, "Cxf configuration file not found, export again the service.");
    MutableFile pomMutableFile = getFileManager().updateFile(pomPath);
    Document pom = getInputDocument(pomMutableFile.getInputStream());
    Element root = pom.getDocumentElement();

    // Gets java2ws plugin element
    Element jaxWsPlugin = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[groupId='org.apache.cxf' and artifactId='cxf-java2ws-plugin']",
            root);

    // Install it if it's missing
    if (jaxWsPlugin == null) {

        logger.log(Level.INFO, "Jax-Ws plugin is not defined in the pom.xml. Installing in project.");
        // Installs jax2ws plugin.
        addPlugin();
    }

    // Checks if already exists the execution.
    Element serviceExecution = XmlUtils
            .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='"
                    .concat(serviceClass.getFullyQualifiedTypeName()).concat("']"), root);

    if (serviceExecution != null) {
        logger.log(Level.FINE, "A previous Wsdl generation with CXF plugin for '".concat(serviceName)
                .concat("' service has been found."));
        return;
    }

    // Checks if name of java class has been changed comparing current
    // service class and name declared in annotation
    boolean classNameChanged = false;
    if (!serviceClass.getFullyQualifiedTypeName().contentEquals(fullyQualifiedTypeName)) {
        classNameChanged = true;
    }

    // if class has been changed (package or name) update execution
    if (classNameChanged) {
        serviceExecution = XmlUtils
                .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='"
                        .concat(fullyQualifiedTypeName).concat("']"), root);

        // Update with serviceClass.getFullyQualifiedTypeName().
        if (serviceExecution != null && serviceExecution.hasChildNodes()) {

            Node updateServiceExecution;
            updateServiceExecution = (serviceExecution.getFirstChild() != null)
                    ? serviceExecution.getFirstChild().getNextSibling()
                    : null;

            // Find node which contains old class name
            while (updateServiceExecution != null) {

                if (updateServiceExecution.getNodeName().contentEquals("className")) {
                    // Update node content with new value
                    updateServiceExecution.setTextContent(serviceClass.getFullyQualifiedTypeName());

                    // write pom
                    XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
                    logger.log(Level.INFO,
                            "Wsdl generation with CXF plugin for '" + serviceName
                                    + " service, updated className attribute for '"
                                    + serviceClass.getFullyQualifiedTypeName() + "'.");
                    // That's all
                    return;
                }

                // Check next node.
                updateServiceExecution = updateServiceExecution.getNextSibling();

            }
        }
    }

    // Prepare Execution configuration
    String executionID = "${project.basedir}/src/test/resources/generated/wsdl/".concat(addressName)
            .concat(".wsdl");
    serviceExecution = createJava2wsExecutionElement(pom, serviceClass, addressName, executionID);

    // Checks if already exists the execution.

    // XXX ??? this is hard difficult because previously it's already
    // checked
    // using class name
    Element oldExecution = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin/executions/execution[id='" + executionID + "']", root);

    if (oldExecution != null) {
        logger.log(Level.FINE, "Wsdl generation with CXF plugin for '" + serviceName
                + " service, has been configured before.");
        return;
    }

    // Checks if already exists the executions to update or create.
    Element oldExecutions = DomUtils.findFirstElementByName(EXECUTIONS, jaxWsPlugin);

    Element newExecutions;

    // To Update execution definitions It must be replaced in pom.xml to
    // maintain the format.
    if (oldExecutions != null) {
        newExecutions = oldExecutions;
        newExecutions.appendChild(serviceExecution);
        oldExecutions.getParentNode().replaceChild(oldExecutions, newExecutions);
    } else {
        newExecutions = pom.createElement(EXECUTIONS);
        newExecutions.appendChild(serviceExecution);

        jaxWsPlugin.appendChild(newExecutions);
    }

    XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems, User oldUser, boolean createContent, int unitKey,
        int categoryKey, int contentTypeKey, int contentKey, int versionKey) throws VerticalAdminException {
    ContentAccessResolver contentAccessResolver = new ContentAccessResolver(groupDao);
    UserEntity executor = securityService.getUser(oldUser);

    ContentVersionEntity selectedVersion = contentVersionDao.findByKey(new ContentVersionKey(versionKey));

    if (!createContent && selectedVersion == null) {
        throw new IllegalArgumentException(
                "No version found for content key " + contentKey + " with version key " + versionKey);
    }/*from   ww w .  j a v a2 s  .co m*/

    if (!createContent && !contentAccessResolver.hasReadContentAccess(securityService.getUser(oldUser),
            selectedVersion.getContent())) {
        throw new IllegalArgumentException("No read access to content with key: " + contentKey);
    }

    //should not be able to view deleted content
    if (!createContent && selectedVersion.getContent().isDeleted()) {
        formItems.put("feedback", "9");
        redirectToReferer(request, response, formItems);
    }

    Integer populateContentDataFromVersion = null;
    if (formItems.containsKey("populateFromVersion")) {
        populateContentDataFromVersion = formItems.getInt("populateFromVersion");
    }

    Document doc = getContentDocument(admin, oldUser, contentKey, categoryKey, versionKey,
            populateContentDataFromVersion);
    Element root = doc.getDocumentElement();

    if (!root.hasChildNodes()) {
        String message = "Access denied.";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, null);
    }

    if (!createContent) {
        // add repository path to related contents
        Element relatedcontentsElem = XMLTool.getElement(doc.getDocumentElement(), "relatedcontents");
        addRepositoryPath(admin, relatedcontentsElem);

        ContentEditFormModelFactory contentEditFormModelFactory = new ContentEditFormModelFactory(contentDao,
                securityService, new MenuItemAccessRightAccumulator(securityService));
        ContentEditFormModel model = contentEditFormModelFactory
                .createContentEditFormModel(new ContentKey(contentKey), executor);

        XMLTool.mergeDocuments(doc, model.locationsToXML().getAsDOMDocument(), true);
        XMLTool.mergeDocuments(doc, model.locationMenuitemsToXML().getAsDOMDocument(), true);
        XMLTool.mergeDocuments(doc, model.locationSitesToXML().getAsDOMDocument(), true);

    }

    String xmlCat = admin.getSuperCategoryNames(categoryKey, false, true);
    XMLTool.mergeDocuments(doc, xmlCat, true);

    addUserRightToDocument(admin, oldUser, doc, categoryKey);
    addEditorDataToDocument(admin, doc);

    if (!createContent && memberOfResolver.hasDeveloperPowers(oldUser.getKey())) {
        ContentVersionEntity includeSourceContentVerision;
        if (populateContentDataFromVersion != null) {
            includeSourceContentVerision = contentVersionDao
                    .findByKey(new ContentVersionKey(populateContentDataFromVersion));
        } else {
            includeSourceContentVerision = selectedVersion;
        }
        appendContentSource(doc, includeSourceContentVerision);
    }

    // Feedback
    addFeedback(doc, formItems);

    // pre-process content document
    preProcessContentDocument(oldUser, admin, doc, formItems, request);

    for (String extraFormXMLFile : extraFormXMLFiles) {
        Document tmpDoc = XMLTool.domparse(AdminStore.getXML(session, extraFormXMLFile));
        XMLTool.mergeDocuments(doc, tmpDoc, true);
    }

    VerticalAdminLogger.debug(this.getClass(), 0, doc);

    // Stylesheet parameters
    ExtendedMap parameters = new ExtendedMap();
    addCustomData(session, oldUser, admin, doc, contentKey, contentTypeKey, formItems, parameters);

    addCommonParameters(admin, oldUser, request, parameters, unitKey, -1);

    addDefaultParameters(admin, request, parameters, contentKey, unitKey, categoryKey, contentTypeKey,
            formItems);

    addAccessLevelParameters(oldUser, parameters);

    DOMSource xslSource = buildXSL(session, admin, contentTypeKey);

    if (xslSource != null) {
        transformXML(request, response, doc, xslSource, parameters);
    } else {
        transformXML(request, response, doc, FORM_XSL, parameters);
    }

    // log read access
    if (formItems.getString("logread", "false").equalsIgnoreCase("true")) {
        logVisited(oldUser, contentKey, selectedVersion, selectedVersion.getContent().getPathAsString());
    }

}

From source file:com.photon.phresco.framework.rest.api.QualityService.java

private List<String> getScreenShot(String testAgainst, String resultFile, String rootModulePath,
        String subModule, String from) throws PhrescoException {
    List<String> imgSources = new ArrayList<String>();
    try {/*from   w  ww  .j  a v a2  s .  co  m*/
        String testDir = "";
        if (PERFORMACE.equals(from)) {
            testDir = FrameworkServiceUtil.getPerformanceTestDir(rootModulePath, subModule);
        } else {
            testDir = FrameworkServiceUtil.getLoadTestDir(rootModulePath, subModule);
        }

        ProjectInfo projectInfo = Utility.getProjectInfo(rootModulePath, subModule);
        File testFolderLocation = Utility.getTestFolderLocation(projectInfo, rootModulePath, subModule);
        StringBuilder sb = new StringBuilder(testFolderLocation.getPath());
        sb.append(testDir).append(File.separator).append(testAgainst);
        int lastDot = resultFile.lastIndexOf(".");
        String resultName = resultFile.substring(0, lastDot);

        File testPomFile = new File(sb.toString() + File.separator + POM_XML);
        PomProcessor pomProcessor = new PomProcessor(testPomFile);
        Plugin plugin = pomProcessor.getPlugin(COM_LAZERYCODE_JMETER, JMETER_MAVEN_PLUGIN);
        com.phresco.pom.model.Plugin.Configuration jmeterConfiguration = plugin.getConfiguration();
        List<Element> jmeterConfigs = jmeterConfiguration.getAny();
        for (Element element : jmeterConfigs) {
            if (PLUGIN_TYPES.equalsIgnoreCase(element.getTagName()) && element.hasChildNodes()) {
                NodeList types = element.getChildNodes();
                for (int i = 0; i < types.getLength(); i++) {
                    Node pluginType = types.item(i);
                    if (StringUtils.isNotEmpty(pluginType.getTextContent())) {
                        File imgFile = new File(sb.toString() + RESULTS_JMETER_GRAPHS + resultName + HYPHEN
                                + pluginType.getTextContent() + PNG);
                        if (imgFile.exists()) {
                            InputStream imageStream = new FileInputStream(imgFile);
                            String imgSrc = new String(Base64.encodeBase64(IOUtils.toByteArray(imageStream)));
                            imgSources.add(
                                    imgSrc + "#NAME_SEP#" + resultName + HYPHEN + pluginType.getTextContent());
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new PhrescoException(e);
    }

    return imgSources;
}

From source file:com.aurel.track.exchange.track.exporter.TrackExportBL.java

/**
 * Creates the history element//from  w w  w .j a v a2  s  .c o m
 * @param historyList
 * @param dom
 * @return
 */
private static Element createHistoryElement(Map<Integer, Map<Integer, HistoryValues>> historyTransactionsMap,
        DropDownContainer dropDownContainer, Document dom,
        Map<String, Map<Integer, Map<String, String>>> serializedLookupsMap,
        Map<String, Map<Integer, Map<String, String>>> additionalSerializedLookupsMap,
        Set<Integer> pseudoHistoryFields, Set<Integer> linkedWorkItemIDs) {
    if (historyTransactionsMap != null && !historyTransactionsMap.isEmpty()) {
        Element transactionElement = null;
        Element historyTransactionsList = dom.createElement(ExchangeFieldNames.HISTORY_LIST);
        Iterator<Integer> transactionsItr = historyTransactionsMap.keySet().iterator();
        while (transactionsItr.hasNext()) {
            Integer transactionID = transactionsItr.next();
            Map<Integer, HistoryValues> fieldChanges = historyTransactionsMap.get(transactionID);
            if (fieldChanges != null) {
                Iterator<Integer> fieldChangeItr = fieldChanges.keySet().iterator();
                boolean firstFieldChange = true;
                while (fieldChangeItr.hasNext()) {
                    Integer fieldChangeID = fieldChangeItr.next();
                    HistoryValues historyValues = fieldChanges.get(fieldChangeID);
                    if (firstFieldChange) {
                        ExchangeHistoryTransactionEntry exchangeHistoryTransactionEntry = new ExchangeHistoryTransactionEntry();
                        Integer changedBy = historyValues.getChangedByID();
                        if (changedBy != null) {
                            exchangeHistoryTransactionEntry.setChangedBy(changedBy.toString());
                        }
                        Date changedAt = historyValues.getLastEdit();
                        if (changedAt != null) {
                            exchangeHistoryTransactionEntry
                                    .setChangedAt(DateTimeUtils.getInstance().formatISODateTime(changedAt));
                        }
                        exchangeHistoryTransactionEntry.setUuid(historyValues.getTransactionUuid());
                        Map<String, String> attributesMap = exchangeHistoryTransactionEntry.serializeBean();
                        transactionElement = createElementWithAttributes(ExchangeFieldNames.TRANSACTION, null,
                                false, attributesMap, dom);
                    }
                    firstFieldChange = false;
                    Integer fieldID = historyValues.getFieldID();
                    IFieldTypeRT fieldTypeRT = null;
                    if (pseudoHistoryFields.contains(fieldID)) {
                        fieldTypeRT = FieldTypeManager.getFieldTypeRT(SystemFields.INTEGER_DESCRIPTION);
                    } else {
                        fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
                    }
                    Object newValue = historyValues.getNewValue();
                    Object oldValue = historyValues.getOldValue();
                    Integer timesEdited = null;
                    if (SystemFields.INTEGER_COMMENT.equals(fieldID)) {
                        timesEdited = historyValues.getTimesEdited();
                    }
                    appendHistoryValue(transactionElement, newValue, oldValue, fieldID, timesEdited,
                            fieldTypeRT, dropDownContainer, dom, serializedLookupsMap,
                            additionalSerializedLookupsMap, linkedWorkItemIDs);
                    if (transactionElement.hasChildNodes()) {
                        //add only if there are child elements
                        historyTransactionsList.appendChild(transactionElement);
                    }
                }
            }
        }
        return historyTransactionsList;
    }
    return null;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private SOAPElement addSoapElement(Context context, SOAPEnvelope se, SOAPElement soapParent, Node node)
        throws Exception {
    String prefix = node.getPrefix();
    String namespace = node.getNamespaceURI();
    String nodeName = node.getNodeName();
    String localName = node.getLocalName();
    String value = node.getNodeValue();

    boolean includeResponseElement = true;
    if (context.sequenceName != null) {
        includeResponseElement = ((Sequence) context.requestedObject).isIncludeResponseElement();
    }//ww w . j  a va 2s.  co  m

    SOAPElement soapElement = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        boolean toAdd = true;
        if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
            toAdd = false;
        }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(element.getParentNode().getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/".equals(namespace)
                || nodeName.toLowerCase().endsWith(":envelope") || nodeName.toLowerCase().endsWith(":body")
        //element.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 ||
        //nodeName.toUpperCase().indexOf("NS0:") != -1
        ) {
            toAdd = false;
        }

        if (toAdd) {
            if (prefix == null || prefix.equals("")) {
                soapElement = soapParent.addChildElement(nodeName);
            } else {
                soapElement = soapParent.addChildElement(se.createName(localName, prefix, namespace));
            }
        } else {
            soapElement = soapParent;
        }

        if (soapElement != null) {
            if (soapParent.equals(se.getBody()) && !soapParent.equals(soapElement)) {
                if (XsdForm.qualified == context.project.getSchemaElementForm()) {
                    if (soapElement.getAttribute("xmlns") == null) {
                        soapElement.addAttribute(se.createName("xmlns"), context.project.getTargetNamespace());
                    }
                }
            }

            if (element.hasAttributes()) {
                String attrType = element.getAttribute("type");
                if (("attachment").equals(attrType)) {
                    if (context.requestedObject instanceof AbstractHttpTransaction) {
                        AttachmentDetails attachment = AttachmentManager.getAttachment(element);
                        if (attachment != null) {
                            byte[] raw = attachment.getData();
                            if (raw != null)
                                soapElement.addTextNode(Base64.encodeBase64String(raw));
                        }

                        /* DON'T WORK YET *\
                        AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), element.getAttribute("content-type"));
                        ap.setContentId(key);
                        ap.setContentLocation(element.getAttribute("url"));
                        responseMessage.addAttachmentPart(ap);
                        \* DON'T WORK YET */
                    }
                }

                if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
                    // do not add attributes
                } else {
                    NamedNodeMap attributes = element.getAttributes();
                    int len = attributes.getLength();
                    for (int i = 0; i < len; i++) {
                        Node item = attributes.item(i);
                        addSoapElement(context, se, soapElement, item);
                    }
                }
            }

            if (element.hasChildNodes()) {
                NodeList childNodes = element.getChildNodes();
                int len = childNodes.getLength();
                for (int i = 0; i < len; i++) {
                    Node item = childNodes.item(i);
                    switch (item.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        addSoapElement(context, se, soapElement, item);
                        break;
                    case Node.CDATA_SECTION_NODE:
                    case Node.TEXT_NODE:
                        String text = item.getNodeValue();
                        text = (text == null) ? "" : text;
                        soapElement.addTextNode(text);
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        if (prefix == null || prefix.equals("")) {
            soapElement = soapParent.addAttribute(se.createName(nodeName), value);
        } else {
            soapElement = soapParent.addAttribute(se.createName(localName, prefix, namespace), value);
        }
    }
    return soapElement;
}