Example usage for org.w3c.dom Element removeChild

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

Introduction

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

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:es.bsc.servicess.ide.ProjectMetadata.java

/**Remove element from all the elements packages
 * @param elementLabel Label of a service element
 *///from   ww w  .ja v a 2s  .c  o m
public void removeElementFromPackages(String elementLabel) {
    NodeList nl = projectElement.getElementsByTagName(PACKAGE_TAG);
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element dependency = (Element) nl.item(i);
            NodeList childs = dependency.getElementsByTagName(ELEMENT_TAG);
            if (childs != null && childs.getLength() > 0) {
                for (int j = 0; j < childs.getLength(); j++) {
                    Element el = (Element) childs.item(j);
                    if (el.getAttribute(LABEL_ATTR).equals(elementLabel)) {
                        dependency.removeChild(childs.item(j));
                        return;
                    }
                }
            }

        }
    }
}

From source file:es.bsc.servicess.ide.ProjectMetadata.java

/**Remove an element form all the dependencies of the project
 * @param elementLabel Label of a service element
 *///from   ww  w  .j a v  a  2  s. c om
public void removeElementFromDepencies(String elementLabel) {
    NodeList nl = projectElement.getElementsByTagName(DEPENDENCY_TAG);
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element dependency = (Element) nl.item(i);
            NodeList childs = dependency.getElementsByTagName(ELEMENT_TAG);
            if (childs != null && childs.getLength() > 0) {
                for (int j = 0; j < childs.getLength(); j++) {
                    Element el = (Element) childs.item(j);
                    if (el.getAttribute(LABEL_ATTR).equals(elementLabel)) {
                        dependency.removeChild(childs.item(j));
                        return;
                    }
                }
            }

        }
    }
}

From source file:com.mirth.connect.model.util.ImportConverter.java

private static String convertChannel(Document document) throws Exception {
    String channelXML = "";
    Element channelRoot = document.getDocumentElement();

    String version = channelRoot.getElementsByTagName("version").item(0).getTextContent();

    int majorVersion = Integer.parseInt(version.split("\\.")[0]);
    int minorVersion = Integer.parseInt(version.split("\\.")[1]);
    int patchVersion = Integer.parseInt(version.split("\\.")[2]);

    if (majorVersion < 2) {
        if (minorVersion < 4) {
            Direction direction = null;//from  ww w. ja  v a 2 s.  co  m
            Element sourceConnectorRoot = (Element) document.getDocumentElement()
                    .getElementsByTagName("sourceConnector").item(0);
            Element destinationConnectorRoot = (Element) document.getDocumentElement()
                    .getElementsByTagName("destinationConnectors").item(0);
            NodeList destinationsConnectors = getElements(destinationConnectorRoot, "connector",
                    "com.mirth.connect.model.Connector");

            Node channelDirection = channelRoot.getElementsByTagName("direction").item(0);

            if (channelDirection.getTextContent().equals("INBOUND"))
                direction = Direction.INBOUND;
            else if (channelDirection.getTextContent().equals("OUTBOUND"))
                direction = Direction.OUTBOUND;

            channelRoot.removeChild(channelDirection);

            NodeList modeElements = channelRoot.getElementsByTagName("mode");

            for (int i = 0; i < modeElements.getLength(); i++) {
                if (((Element) modeElements.item(i)).getParentNode() == channelRoot) {
                    channelRoot.removeChild(modeElements.item(i));
                }
            }

            channelRoot.removeChild(channelRoot.getElementsByTagName("protocol").item(0));

            NodeList transportNames = channelRoot.getElementsByTagName("transportName");
            for (int i = 0; i < transportNames.getLength(); i++) {
                if (transportNames.item(i).getTextContent().equals("PDF Writer")) {
                    transportNames.item(i).setTextContent("Document Writer");
                }
            }

            NodeList properyNames = channelRoot.getElementsByTagName("property");
            for (int i = 0; i < properyNames.getLength(); i++) {
                Node nameAttribute = properyNames.item(i).getAttributes().getNamedItem("name");
                if (properyNames.item(i).getAttributes().getLength() > 0 && nameAttribute != null) {
                    if (nameAttribute.getNodeValue().equals("DataType")) {
                        if (properyNames.item(i).getTextContent().equals("PDF Writer")) {
                            properyNames.item(i).setTextContent("Document Writer");
                        }
                    }
                }
            }

            Element modeElement = document.createElement("mode");
            modeElement.setTextContent("SOURCE");
            sourceConnectorRoot.appendChild(modeElement);

            updateFilterFor1_4((Element) sourceConnectorRoot.getElementsByTagName("filter").item(0));
            if (direction == Direction.OUTBOUND)
                updateTransformerFor1_4(document,
                        (Element) sourceConnectorRoot.getElementsByTagName("transformer").item(0), XML, XML);
            else
                updateTransformerFor1_4(document,
                        (Element) sourceConnectorRoot.getElementsByTagName("transformer").item(0), HL7V2,
                        HL7V2);

            for (int i = 0; i < destinationsConnectors.getLength(); i++) {
                modeElement = document.createElement("mode");
                modeElement.setTextContent("DESTINATION");

                Element destinationsConnector = (Element) destinationsConnectors.item(i);
                destinationsConnector.appendChild(modeElement);

                updateFilterFor1_4((Element) destinationsConnector.getElementsByTagName("filter").item(0));

                if (direction == Direction.OUTBOUND)
                    updateTransformerFor1_4(document,
                            (Element) destinationsConnector.getElementsByTagName("transformer").item(0), XML,
                            HL7V2);
                else
                    updateTransformerFor1_4(document,
                            (Element) destinationsConnector.getElementsByTagName("transformer").item(0), HL7V2,
                            HL7V2);

            }
        }

        if (minorVersion < 5) {
            updateTransformerFor1_5(document);
        }

        if (minorVersion < 6) {
            // Go through each connector and set it to enabled if that
            // property doesn't exist.

            Element sourceConnectorRoot = (Element) document.getDocumentElement()
                    .getElementsByTagName("sourceConnector").item(0);
            Element destinationConnectorRoot = (Element) document.getDocumentElement()
                    .getElementsByTagName("destinationConnectors").item(0);
            NodeList destinationsConnectors = getElements(destinationConnectorRoot, "connector",
                    "com.mirth.connect.model.Connector");

            // Check SOURCE CONNECTOR node for "enabled" element which is
            // added by migration automatically. Add it if not found.
            if (!nodeChildrenContains(sourceConnectorRoot, "enabled")) {
                Element enabledSource = document.createElement("enabled");
                enabledSource.setTextContent("true");
                sourceConnectorRoot.appendChild(enabledSource);
            } else {
                // set it anyway, in case xstream auto set it to false.
                setBooleanNode(sourceConnectorRoot, "enabled", true);
            }

            // Check CONNECTOR node for "enabled" element which is added by
            // migration automatically. Add it if not found.
            for (int i = 0; i < destinationsConnectors.getLength(); i++) {
                Element destinationConnector = (Element) destinationsConnectors.item(i);

                if (!nodeChildrenContains(destinationConnector, "enabled")) {
                    Element enabledDestination = document.createElement("enabled");
                    enabledDestination.setTextContent("true");
                    destinationConnector.appendChild(enabledDestination);
                } else {
                    // set it anyway, in case xstream auto set it to false.
                    setBooleanNode(destinationConnector, "enabled", true);
                }
            }

            if (!nodeChildrenContains(channelRoot, "deployScript")) {
                Element deployScript = document.createElement("deployScript");
                deployScript.setTextContent(
                        "// This script executes once when the channel is deployed\n// You only have access to the globalMap and globalChannelMap here to persist data\nreturn;");
                channelRoot.appendChild(deployScript);
            }

            if (!nodeChildrenContains(channelRoot, "shutdownScript")) {
                Element shutdownScript = document.createElement("shutdownScript");
                shutdownScript.setTextContent(
                        "// This script executes once when the channel is undeployed\n// You only have access to the globalMap and globalChannelMap here to persist data\nreturn;");
                channelRoot.appendChild(shutdownScript);
            }

            if (!nodeChildrenContains(channelRoot, "postprocessingScript")) {
                Element postprocessorScript = document.createElement("postprocessingScript");
                postprocessorScript.setTextContent(
                        "// This script executes once after a message has been processed\nreturn;");
                channelRoot.appendChild(postprocessorScript);
            }
        }

        if (minorVersion < 7) {
            if (!nodeChildrenContains(channelRoot, "lastModified")) {
                Element lastModified = document.createElement("lastModified");
                Element time = document.createElement("time");
                Element timezone = document.createElement("timezone");

                Calendar calendar = Calendar.getInstance();
                time.setTextContent(calendar.getTimeInMillis() + "");
                timezone.setTextContent(calendar.getTimeZone().getDisplayName());

                lastModified.appendChild(time);
                lastModified.appendChild(timezone);

                channelRoot.appendChild(lastModified);
            }

            updateFilterFor1_7(document);
            updateTransformerFor1_7(document);
        }

        if (minorVersion < 8) {
            // Run for all versions prior to 1.7.1
            if (minorVersion < 7 || (minorVersion == 7 && patchVersion < 1)) {
                updateTransformerFor1_7_1(document);
            }
            convertChannelConnectorsFor1_8(document, channelRoot);
        }

        // Run for all versions prior to 1.8.2
        if (minorVersion < 8 || (minorVersion == 8 && patchVersion < 1)) {
            updateTransformerFor1_8_1(document);
        }

        // Run for all versions prior to 2.0

        // MIRTH-1402 - Fix old channels from oracle that did not have
        // description because they were blank
        if (channelRoot.getElementsByTagName("description").getLength() == 0) {
            Element descriptionElement = document.createElement("description");
            channelRoot.appendChild(descriptionElement);
        }

        convertChannelConnectorsFor2_0(document, channelRoot);
        updateFilterFor2_0(document);
    }

    // Run for all versions prior to 3.x
    if (majorVersion < 3) {
        // Run for all versions prior to 2.2
        if (minorVersion < 2) {
            convertChannelConnectorsFor2_2(document, channelRoot);
        }
    }

    DocumentSerializer docSerializer = new DocumentSerializer();
    channelXML = docSerializer.toXML(document);

    return updateLocalAndGlobalVariables(channelXML);
}

From source file:es.bsc.servicess.ide.ProjectMetadata.java

private void deleteConstraintFromElement(Element oe, String constraintName) {
    NodeList consElements = oe.getElementsByTagName(CONSTRAINT_TAG);
    if (consElements != null) {
        for (int i = 0; i < consElements.getLength(); i++) {
            Element cons = (Element) (consElements.item(i));
            if (cons.getAttribute(NAME_ATTR).equals(constraintName)) {
                log.debug("Constraint " + constraintName + " found. Removing...");
                oe.removeChild(cons);
                return;
            }//from w w w.j  a  v a 2 s  .  com
        }
    }
    log.warn("Constraint " + constraintName + " not found. Nothing done");

}

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

public Document getSections(User user, SectionCriteria criteria) {

    Connection con = null;//  w  w w . j a va2 s .c  om
    PreparedStatement preparedStmt = null;
    ResultSet resultSet = null;
    Document doc = null;
    SectionView sectionView = SectionView.getInstance();

    try {
        con = getConnection();
        StringBuffer sql;
        SiteKey[] siteKeys = criteria.getSiteKeys();
        MenuItemKey[] menuItemKeys = criteria.getMenuItemKeys();
        int sectionKey = criteria.getSectionKey();
        int superSectionKey = criteria.getSuperSectionKey();
        boolean includeSection = criteria.isIncludeSection();
        int level = criteria.getLevel();
        int[] sectionKeys = criteria.getSectionKeys();
        int contentKey = criteria.getContentKey();
        int contentKeyExcludeFilter = criteria.getContentKeyExcludeFilter();
        int contentTypeKeyFilter = criteria.getContentTypeKeyFilter();
        boolean treeStructure = criteria.isTreeStructure();
        boolean markContentFilteredSections = criteria.isMarkContentFilteredSections();
        boolean includeAll = criteria.isIncludeAll();

        // Generate SQL
        if (siteKeys != null) {
            if (siteKeys.length == 0) {
                return XMLTool.createDocument("sections");
            }
            sql = XDG.generateSelectWhereInSQL(sectionView, (Column[]) null, false, sectionView.mei_men_lKey,
                    siteKeys.length);
        } else if (menuItemKeys != null) {
            if (menuItemKeys.length == 0) {
                return XMLTool.createDocument("sections");
            }
            sql = XDG.generateSelectWhereInSQL(sectionView, (Column[]) null, false, sectionView.mei_lKey,
                    menuItemKeys.length);
        } else if (sectionKey != -1) {
            sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lKey);
        } else if (sectionKeys != null) {
            if (sectionKeys.length == 0) {
                return XMLTool.createDocument("sections");
            }
            sql = XDG.generateSelectWhereInSQL(sectionView, (Column[]) null, false, sectionView.mei_lKey,
                    sectionKeys.length);
        } else if (superSectionKey != -1) {
            if (includeSection) {
                sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lKey);
                if (level > 0) {
                    level += 1;
                }
            } else {
                sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lParent);
            }
        } else if (contentKey != -1) {
            sql = XDG.generateSelectSQL(sectionView);
            sql.append(" WHERE mei_lKey IN (SELECT sco_mei_lKey FROM tSectionContent2 WHERE sco_con_lKey = ?)");
        } else {
            sql = XDG.generateSelectSQL(sectionView);
        }

        if (contentKeyExcludeFilter > -1 && !markContentFilteredSections) {
            if (sql.toString().toLowerCase().indexOf("where") < 0) {
                sql.append(" WHERE");
            } else {
                sql.append(" AND");
            }
            sql.append(" mei_lKey NOT IN (SELECT sco_mei_lKey FROM tSectionContent2 WHERE sco_con_lKey = ?)");
        }

        if (contentTypeKeyFilter > -1) {
            if (sql.toString().toLowerCase().indexOf("where") < 0) {
                sql.append(" WHERE");
            } else {
                sql.append(" AND");
            }
            sql.append(" (");
            sql.append(" mei_lKey IN (SELECT sctf_mei_lKey FROM tSecConTypeFilter2 WHERE sctf_cty_lkey = ?)");
            if (criteria.isIncludeSectionsWithoutContentTypeEvenWhenFilterIsSet()) {
                sql.append(
                        " OR NOT EXISTS (SELECT sctf_mei_lKey FROM tSecConTypeFilter2 WHERE sctf_mei_lkey = mei_lKey)");
            }
            sql.append(" )");
        }

        SecurityHandler securityHandler = getSecurityHandler();
        if (!includeAll) {
            securityHandler.appendSectionSQL(user, sql, criteria);
        }

        sql.append(" ORDER BY mei_sName");

        preparedStmt = con.prepareStatement(sql.toString());

        int index = 1;
        // Set parameters
        if (siteKeys != null) {
            for (SiteKey siteKey : siteKeys) {
                preparedStmt.setInt(index++, siteKey.toInt());
            }
        } else if (menuItemKeys != null) {
            for (MenuItemKey menuItemKey : menuItemKeys) {
                preparedStmt.setInt(index++, menuItemKey.toInt());
            }
        } else if (sectionKey != -1) {
            preparedStmt.setInt(index++, sectionKey);
        } else if (sectionKeys != null) {
            for (int loopSectionKey : sectionKeys) {
                preparedStmt.setInt(index++, loopSectionKey);
            }
        } else if (superSectionKey != -1) {
            preparedStmt.setInt(index++, superSectionKey);
        } else if (contentKey != -1) {
            preparedStmt.setInt(index++, contentKey);
        }

        if (contentKeyExcludeFilter > -1 && !markContentFilteredSections) {
            preparedStmt.setInt(index++, contentKeyExcludeFilter);
        }
        if (contentTypeKeyFilter > -1) {
            preparedStmt.setInt(index, contentTypeKeyFilter);
        }

        resultSet = preparedStmt.executeQuery();

        ElementProcessor childCountProcessor = null;
        if (criteria.getIncludeChildCount()) {
            childCountProcessor = new ChildCountProcessor();
        }

        Map<String, Element> elemMap = new HashMap<String, Element>();
        CollectionProcessor collectionProcessor = new CollectionProcessor(elemMap, null);
        ElementProcessor[] processors;
        ElementProcessor aep = null;
        if (contentKeyExcludeFilter >= 0) {
            if (markContentFilteredSections) {
                int[] keys = getSectionKeysByContent(contentKeyExcludeFilter, -1);
                aep = new FilteredAttributeElementProcessor("filtered", "true", keys);
            }
        }
        if (contentKey >= 0 && markContentFilteredSections) {
            int[] keys = getSectionKeysByContent(contentKey, -1);
            aep = new FilteredAttributeElementProcessor("filtered", "true", keys);
        }

        SectionProcessor sectionProcessorThatIncludesContentTypes = null;

        if (criteria.isIncludeSectionContentTypesInfo()) {
            sectionProcessorThatIncludesContentTypes = new SectionProcessor();
        }

        processors = new ElementProcessor[] { aep,
                // mark content in original query
                new AttributeElementProcessor("marked", "true"), sectionProcessorThatIncludesContentTypes,
                collectionProcessor, childCountProcessor };

        doc = XDG.resultSetToXML(sectionView, resultSet, null, processors, null, -1);
        close(resultSet);
        close(preparedStmt);

        // If treeStructure is true, all parents of the retrieved section
        // are retrieved:
        if (treeStructure) {
            sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lKey);
            preparedStmt = con.prepareStatement(sql.toString());

            Element sectionsRootElement = doc.getDocumentElement();
            List<Element> sectionsElementList = XMLTool.getElementsAsList(sectionsRootElement);
            collectionProcessor.elemList = sectionsElementList;

            // remove marking of sections ("filtered"(0) and "marked"(1) attributes)
            processors[0] = null;
            processors[1] = null;

            for (int i = 0; i < sectionsElementList.size(); i++) {
                Element sectionElement = sectionsElementList.get(i);
                String superKey = sectionElement.getAttribute("supersectionkey");
                if (superKey != null && superKey.length() > 0) {
                    sectionsRootElement.removeChild(sectionElement);

                    // find parent element and append current element
                    Element parentElem = elemMap.get("section_" + superKey);
                    if (parentElem == null) {
                        int key = Integer.parseInt(superKey);
                        preparedStmt.setInt(1, key);
                        resultSet = preparedStmt.executeQuery();
                        XDG.resultSetToXML(sectionView, resultSet, doc.getDocumentElement(), processors, "name",
                                -1);
                        close(resultSet);
                        parentElem = collectionProcessor.lastElem;
                    }
                    Element elem = XMLTool.createElementIfNotPresent(doc, parentElem, "sections");
                    elem.appendChild(sectionElement);
                }
            }
        }

        // If specified, get sections recursivly, i.e. retrieve all sections below the
        // the retrieved sections:
        else if (criteria.getSectionsRecursivly()) {
            if (level > 1 || level == 0) {
                Element sectionsElement = doc.getDocumentElement();
                Element[] sections = XMLTool.getElements(sectionsElement, "section");

                for (Element section : sections) {
                    int currentSectionKey = Integer.parseInt(section.getAttribute("key"));
                    int[] subSectionKeys = getSectionKeysBySuperSection(currentSectionKey, false);

                    if (subSectionKeys.length > 0) {

                        criteria.setSectionKey(-1);
                        criteria.setSectionKeys(subSectionKeys);
                        criteria.setLevel((level > 1 ? level - 1 : 0));

                        Document subSectionsDoc = getSections(user, criteria);
                        section.appendChild(doc.importNode(subSectionsDoc.getDocumentElement(), true));
                    }
                }
            }
        }

        if (criteria.appendAccessRights()) {
            securityHandler.appendAccessRights(user, doc, true, true);
        }
    } catch (SQLException sqle) {
        String message = "Failed to get sections: %t";
        VerticalEngineLogger.error(this.getClass(), 1, message, sqle);
        doc = XMLTool.createDocument("sections");
    } finally {
        close(resultSet);
        close(preparedStmt);
        close(con);
    }
    return doc;
}

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

/**
 * based on our use case, it only check the children of the root node...
 * //from ww w.  j  ava 2  s .c o  m
 * @param originalDom
 * @param modifiedDom
 * @return Document
 */
private Document replace(final Document originalDom, final Document modifiedDom) {

    /**
     * the children nodes of a xml Document is the first level nodes in the
     * xml doc, for example, for a protocol xml, the children nodes of the
     * doc is <code><protocol></code>
     */

    // it needs to find the latest identical node then start replacing
    // whatever under it...
    Element rootNode = (Element) modifiedDom.getFirstChild();

    Document finalDom = originalDom;

    Element finalDomRoot = (Element) finalDom.getFirstChild();

    NodeList modifiedNodes = rootNode.getChildNodes();

    int l = modifiedNodes.getLength();

    logger.trace("lenght: " + l);
    for (int i = 0; i < l; i++) {
        Node currentNode = modifiedNodes.item(i);

        logger.trace("currentNode: " + currentNode.getNodeName());

        NodeList matchedNodes = finalDomRoot.getElementsByTagName(currentNode.getNodeName());

        for (int j = 0; j < matchedNodes.getLength(); j++) {
            try {
                finalDomRoot.removeChild(matchedNodes.item(j));
            } catch (Exception e) {
                logger.debug("Failed to remove node: " + matchedNodes.item(j).getNodeName());
            }

        }

        finalDomRoot.appendChild(finalDom.importNode(currentNode, true));
    }

    logger.trace("finalDom: " + DomUtils.elementToString(finalDom));

    return finalDom;
}

From source file:loci.formats.in.LIFReader.java

private void translateMetadata(Element root) throws FormatException {
    Element realRoot = (Element) root.getChildNodes().item(0);

    NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master");
    if (toPrune != null) {
        for (int i = 0; i < toPrune.getLength(); i++) {
            Element prune = (Element) toPrune.item(i);
            Element parent = (Element) prune.getParentNode();
            parent.removeChild(prune);
        }//from   w w w .java 2  s.com
    }

    NodeList images = getNodes(realRoot, "Image");
    List<Element> imageNodes = new ArrayList<Element>();
    Long[] oldOffsets = null;
    if (images.getLength() > offsets.size()) {
        oldOffsets = offsets.toArray(new Long[offsets.size()]);
        offsets.clear();
    }

    int nextOffset = 0;
    for (int i = 0; i < images.getLength(); i++) {
        Element image = (Element) images.item(i);
        Element grandparent = (Element) image.getParentNode();
        if (grandparent == null) {
            continue;
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent == null) {
            continue;
        }
        if (!"ProcessingHistory".equals(grandparent.getNodeName())) {
            // image is being referenced from an event list
            imageNodes.add(image);
            if (oldOffsets != null && nextOffset < oldOffsets.length) {
                offsets.add(oldOffsets[nextOffset]);
            }
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent == null) {
            continue;
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent != null) {
            if (!"Image".equals(grandparent.getNodeName())) {
                nextOffset++;
            }
        }
    }

    tileCount = new int[imageNodes.size()];
    Arrays.fill(tileCount, 1);
    core = new ArrayList<CoreMetadata>(imageNodes.size());
    acquiredDate = new double[imageNodes.size()];
    descriptions = new String[imageNodes.size()];
    laserWavelength = new List[imageNodes.size()];
    laserIntensity = new List[imageNodes.size()];
    laserActive = new List[imageNodes.size()];
    laserFrap = new List[imageNodes.size()];
    timestamps = new double[imageNodes.size()][];
    activeDetector = new List[imageNodes.size()];
    serialNumber = new String[imageNodes.size()];
    lensNA = new Double[imageNodes.size()];
    magnification = new Double[imageNodes.size()];
    immersions = new String[imageNodes.size()];
    corrections = new String[imageNodes.size()];
    objectiveModels = new String[imageNodes.size()];
    posX = new Length[imageNodes.size()];
    posY = new Length[imageNodes.size()];
    posZ = new Length[imageNodes.size()];
    refractiveIndex = new Double[imageNodes.size()];
    cutIns = new List[imageNodes.size()];
    cutOuts = new List[imageNodes.size()];
    filterModels = new List[imageNodes.size()];
    microscopeModels = new String[imageNodes.size()];
    detectorModels = new List[imageNodes.size()];
    detectorIndexes = new HashMap[imageNodes.size()];
    zSteps = new Double[imageNodes.size()];
    tSteps = new Double[imageNodes.size()];
    pinholes = new Double[imageNodes.size()];
    zooms = new Double[imageNodes.size()];

    expTimes = new Double[imageNodes.size()][];
    gains = new Double[imageNodes.size()][];
    detectorOffsets = new Double[imageNodes.size()][];
    channelNames = new String[imageNodes.size()][];
    exWaves = new Double[imageNodes.size()][];
    imageROIs = new ROI[imageNodes.size()][];
    imageNames = new String[imageNodes.size()];

    core.clear();
    for (int i = 0; i < imageNodes.size(); i++) {
        Element image = imageNodes.get(i);

        CoreMetadata ms = new CoreMetadata();
        core.add(ms);

        int index = core.size() - 1;
        setSeries(index);

        translateImageNames(image, index);
        translateImageNodes(image, index);
        translateAttachmentNodes(image, index);
        translateScannerSettings(image, index);
        translateFilterSettings(image, index);
        translateTimestamps(image, index);
        translateLaserLines(image, index);
        translateROIs(image, index);
        translateSingleROIs(image, index);
        translateDetectors(image, index);

        final Deque<String> nameStack = new ArrayDeque<String>();
        populateOriginalMetadata(image, nameStack);
        addUserCommentMeta(image, i);
    }
    setSeries(0);

    int totalSeries = 0;
    for (int count : tileCount) {
        totalSeries += count;
    }
    ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>();
    for (int i = 0; i < core.size(); i++) {
        for (int tile = 0; tile < tileCount[i]; tile++) {
            newCore.add(core.get(i));
        }
    }
    core = newCore;
}

From source file:es.bsc.servicess.ide.ProjectMetadata.java

/** Remove element from a elements package
 * @param name Package name/* ww w .ja va  2 s  . co m*/
 * @param elementLabel Label of a service element
 */
public void removeElementFromPackage(String name, String elementLabel) {
    NodeList nl = projectElement.getElementsByTagName(PACKAGE_TAG);
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element dependency = (Element) nl.item(i);
            if (dependency.getAttribute(NAME_ATTR).equals(name)) {
                NodeList childs = dependency.getElementsByTagName(ELEMENT_TAG);
                if (childs != null && childs.getLength() > 0) {
                    for (int j = 0; j < childs.getLength(); j++) {
                        Element el = (Element) childs.item(j);
                        if (el.getAttribute(LABEL_ATTR).equals(elementLabel)) {
                            dependency.removeChild(childs.item(j));
                            return;
                        }
                    }
                }
            }
        }
    }
}

From source file:es.bsc.servicess.ide.ProjectMetadata.java

/**Remove an element form a the dependency
 * @param loc Dependency location (file or folder location)
 * @param elementLabel Label of a service element
 *///from  www  .  j a v  a  2s  .  c  o  m
public void removeElementFromDependency(String loc, String elementLabel) {
    NodeList nl = projectElement.getElementsByTagName(DEPENDENCY_TAG);
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element dependency = (Element) nl.item(i);
            if (dependency.getAttribute(LOCATION_ATTR).equals(loc)) {
                NodeList childs = dependency.getElementsByTagName(ELEMENT_TAG);
                if (childs != null && childs.getLength() > 0) {
                    for (int j = 0; j < childs.getLength(); j++) {
                        Element el = (Element) childs.item(j);
                        if (el.getAttribute(LABEL_ATTR).equals(elementLabel)) {
                            dependency.removeChild(childs.item(j));
                            return;
                        }
                    }
                }
            }
        }
    }
}

From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java

/**
 * This method:<ul>/*  w  w  w .  j  a va  2 s .  co m*/
 *     <li>Copies POM from original project to archetype-resources</li>
 *     <li>Generates <code></code>archetype-descriptor.xml</code></li>
 *     <li>Generates Archetype's <code>pom.xml</code> if not present in target directory.</li>
 * </ul>
 *
 * @param projectPom POM file of original project
 * @param archetypeDir target directory of created Maven Archetype project
 * @param archetypePom created POM file for Maven Archetype project
 * @param metadataXmlOutFile generated archetype-metadata.xml file
 * @param replaceFn replace function
 * @throws IOException
 */
private void createArchetypeDescriptors(File projectPom, File archetypeDir, File archetypePom,
        File metadataXmlOutFile, Replacement replaceFn) throws IOException {
    LOG.debug("Parsing " + projectPom);
    String text = replaceFn.replace(FileUtils.readFileToString(projectPom));

    // lets update the XML
    Document doc = archetypeUtils.parseXml(new InputSource(new StringReader(text)));
    Element root = doc.getDocumentElement();

    // let's get some values from the original project
    String originalArtifactId, originalName, originalDescription;
    Element artifactIdEl = (Element) findChild(root, "artifactId");

    Element nameEl = (Element) findChild(root, "name");
    Element descriptionEl = (Element) findChild(root, "description");
    if (artifactIdEl != null && artifactIdEl.getTextContent() != null
            && artifactIdEl.getTextContent().trim().length() > 0) {
        originalArtifactId = artifactIdEl.getTextContent().trim();
    } else {
        originalArtifactId = archetypeDir.getName();
    }
    if (nameEl != null && nameEl.getTextContent() != null && nameEl.getTextContent().trim().length() > 0) {
        originalName = nameEl.getTextContent().trim();
    } else {
        originalName = originalArtifactId;
    }
    if (descriptionEl != null && descriptionEl.getTextContent() != null
            && descriptionEl.getTextContent().trim().length() > 0) {
        originalDescription = descriptionEl.getTextContent().trim();
    } else {
        originalDescription = originalName;
    }

    Set<String> propertyNameSet = new TreeSet<String>();

    if (root != null) {
        // remove the parent element and the following text Node
        NodeList parents = root.getElementsByTagName("parent");
        if (parents.getLength() > 0) {
            if (parents.item(0).getNextSibling().getNodeType() == Node.TEXT_NODE) {
                root.removeChild(parents.item(0).getNextSibling());
            }
            root.removeChild(parents.item(0));
        }

        // lets load all the properties defined in the <properties> element in the pom.
        Set<String> pomPropertyNames = new LinkedHashSet<String>();

        NodeList propertyElements = root.getElementsByTagName("properties");
        if (propertyElements.getLength() > 0) {
            Element propertyElement = (Element) propertyElements.item(0);
            NodeList children = propertyElement.getChildNodes();
            for (int cn = 0; cn < children.getLength(); cn++) {
                Node e = children.item(cn);
                if (e instanceof Element) {
                    pomPropertyNames.add(e.getNodeName());
                }
            }
        }
        LOG.debug("Found <properties> in the pom: {}", pomPropertyNames);

        // lets find all the property names
        NodeList children = root.getElementsByTagName("*");
        for (int cn = 0; cn < children.getLength(); cn++) {
            Node e = children.item(cn);
            if (e instanceof Element) {
                //val text = e.childrenText
                String cText = e.getTextContent();
                String prefix = "${";
                if (cText.startsWith(prefix)) {
                    int offset = prefix.length();
                    int idx = cText.indexOf("}", offset + 1);
                    if (idx > 0) {
                        String name = cText.substring(offset, idx);
                        if (!pomPropertyNames.contains(name) && isValidRequiredPropertyName(name)) {
                            propertyNameSet.add(name);
                        }
                    }
                }
            }
        }

        // now lets replace the contents of some elements (adding new elements if they are not present)
        List<String> beforeNames = Arrays.asList("artifactId", "version", "packaging", "name", "properties");
        replaceOrAddElementText(doc, root, "version", "${version}", beforeNames);
        replaceOrAddElementText(doc, root, "artifactId", "${artifactId}", beforeNames);
        replaceOrAddElementText(doc, root, "groupId", "${groupId}", beforeNames);
    }
    archetypePom.getParentFile().mkdirs();

    archetypeUtils.writeXmlDocument(doc, archetypePom);

    // lets update the archetype-metadata.xml file
    String archetypeXmlText = defaultArchetypeXmlText();

    Document archDoc = archetypeUtils.parseXml(new InputSource(new StringReader(archetypeXmlText)));
    Element archRoot = archDoc.getDocumentElement();

    // replace @name attribute on root element
    archRoot.setAttribute("name", archetypeDir.getName());

    LOG.debug(("Found property names: {}"), propertyNameSet);
    // lets add all the properties
    Element requiredProperties = replaceOrAddElement(archDoc, archRoot, "requiredProperties",
            Arrays.asList("fileSets"));

    // lets add the various properties in
    for (String propertyName : propertyNameSet) {
        requiredProperties.appendChild(archDoc.createTextNode("\n" + indent + indent));
        Element requiredProperty = archDoc.createElement("requiredProperty");
        requiredProperties.appendChild(requiredProperty);
        requiredProperty.setAttribute("key", propertyName);
        requiredProperty.appendChild(archDoc.createTextNode("\n" + indent + indent + indent));
        Element defaultValue = archDoc.createElement("defaultValue");
        requiredProperty.appendChild(defaultValue);
        defaultValue.appendChild(archDoc.createTextNode("${" + propertyName + "}"));
        requiredProperty.appendChild(archDoc.createTextNode("\n" + indent + indent));
    }
    requiredProperties.appendChild(archDoc.createTextNode("\n" + indent));

    metadataXmlOutFile.getParentFile().mkdirs();
    archetypeUtils.writeXmlDocument(archDoc, metadataXmlOutFile);

    File archetypeProjectPom = new File(archetypeDir, "pom.xml");
    // now generate Archetype's pom
    if (!archetypeProjectPom.exists()) {
        StringWriter sw = new StringWriter();
        IOUtils.copy(getClass().getResourceAsStream("default-archetype-pom.xml"), sw, "UTF-8");
        Document pomDocument = archetypeUtils.parseXml(new InputSource(new StringReader(sw.toString())));

        List<String> emptyList = Collections.emptyList();

        // artifactId = original artifactId with "-archetype"
        Element artifactId = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "artifactId",
                emptyList);
        artifactId.setTextContent(archetypeDir.getName());

        // name = "Fabric8 :: Qickstarts :: xxx" -> "Fabric8 :: Archetypes :: xxx"
        Element name = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "name", emptyList);
        if (originalName.contains(" :: ")) {
            String[] originalNameTab = originalName.split(" :: ");
            if (originalNameTab.length > 2) {
                StringBuilder sb = new StringBuilder();
                sb.append("Fabric8 :: Archetypes");
                for (int idx = 2; idx < originalNameTab.length; idx++) {
                    sb.append(" :: ").append(originalNameTab[idx]);
                }
                name.setTextContent(sb.toString());
            } else {
                name.setTextContent("Fabric8 :: Archetypes :: " + originalNameTab[1]);
            }
        } else {
            name.setTextContent("Fabric8 :: Archetypes :: " + originalName);
        }

        // description = "Creates a new " + originalDescription
        Element description = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "description",
                emptyList);
        description.setTextContent("Creates a new " + originalDescription);

        archetypeUtils.writeXmlDocument(pomDocument, archetypeProjectPom);
    }
}