Example usage for org.dom4j Element remove

List of usage examples for org.dom4j Element remove

Introduction

In this page you can find the example usage for org.dom4j Element remove.

Prototype

boolean remove(Text text);

Source Link

Document

Removes the given Text if the node is an immediate child of this element.

Usage

From source file:com.globalsight.everest.tm.exporter.TmxChecker.java

License:Apache License

/**
* When export TM, "internal='yes' type='style'" will be merged to
* "type='x-internal-style'"; When import back, need revert back.
* 
* @param segment/* w ww  .  ja va2 s.  com*/
* @return
*/
public String revertInternalTag(String segment) {
    Document dom = getDom(segment);
    Element root = dom.getRootElement();
    for (String tag : dtdMap.keySet()) {
        String nodeName = "//" + tag;
        List nodes = root.selectNodes(nodeName);
        for (int x = 0; x < nodes.size(); x++) {
            Element node = (Element) nodes.get(x);
            if (node.attribute("type") != null && node.attribute("type").getValue() != null) {
                Attribute typeAttr = node.attribute("type");
                String type = typeAttr.getValue();
                if ("x-internal".equalsIgnoreCase(type)) {
                    node.remove(typeAttr);
                    node.add(new DefaultAttribute("internal", "yes"));
                } else if (type.startsWith("x-internal")) {
                    String realTypeValue = type.substring("x-internal".length() + 1);
                    typeAttr.setValue(realTypeValue);
                    node.add(new DefaultAttribute("internal", "yes"));
                }
            }
        }
    }

    return root.asXML();
}

From source file:com.globalsight.everest.tm.util.ttx.TtxToTmx.java

License:Apache License

/**
 * Lowercases relevant TMX attributes like &lt;tuv lang&gt;.
 *//*w ww  .  j  a va  2s  .co  m*/
private void lowercaseAttributes(Element p_tu) {
    // TUVs have been lowercased already (need `.')
    List tuvs = p_tu.selectNodes(".//tuv");

    // Rename uppercase <tuv Lang> to lowercase lang.
    for (int i = 0, max = tuvs.size(); i < max; i++) {
        Element tuv = (Element) tuvs.get(i);

        Attribute attr = tuv.attribute(Ttx.LANG);
        tuv.remove(attr);

        tuv.addAttribute("xml:lang", attr.getValue());
    }
}

From source file:com.globalsight.ling.docproc.worldserver.WsSkeletonDispose.java

License:Apache License

@Override
public String dealSkeleton(String skeleton, String localizedBy) {
    boolean localizedByUser = false;
    boolean localizedByMT = false;
    boolean localizedByLocalTM = false;

    if (localizedBy != null && localizedBy.equals(PageTemplate.byUser)) {
        localizedByUser = true;/*from   ww w. j av a  2s  .com*/
    } else if (localizedBy != null && localizedBy.equals(PageTemplate.byMT)) {
        localizedByMT = true;
    } else if (localizedBy != null && localizedBy.equals(PageTemplate.byLocalTM)) {
        localizedByLocalTM = true;
    }

    int begin = skeleton.indexOf("<" + IWS_SEGMENT_DATA);
    int end = skeleton.indexOf("</" + IWS_SEGMENT_DATA) + ("</" + IWS_SEGMENT_DATA + ">").length();

    String iwsStr = skeleton.substring(begin, end);
    iwsStr = "<segmentdata " + "xmlns:iws=\"http://www.idiominc.com/ws/asset\">" + iwsStr + "</segmentdata>";
    Document dom = getDom(iwsStr);
    Element root = dom.getRootElement();
    List iwsStatusList = root.selectNodes("//iws:status");

    for (int x = 0; x < iwsStatusList.size(); x++) {
        Element status = (Element) iwsStatusList.get(x);

        if (localizedByUser || localizedByLocalTM || localizedByMT) {
            /*
             * if (status.attribute("match-quality") != null)
             * status.remove(status.attribute("match-quality"));
             * 
             * if (status.attribute("source_content") != null)
             * status.remove(status.attribute("source_content"));
             * 
             * if (status.attribute("target_content") != null)
             * status.remove(status.attribute("target_content"));
             */
            List<Attribute> attrList = new ArrayList();
            attrList.addAll(status.attributes());

            for (int i = 0; i < attrList.size(); i++) {
                String name = attrList.get(i).getName();
                if (!name.equals(IWS_TRANSLATION_STATUS) && !name.equals(IWS_TRANSLATION_TYPE)
                        && !name.equals(IWS_SOURCE_CONTENT)) {
                    status.remove(attrList.get(i));
                }
            }
        }

        if (status.attribute(IWS_TRANSLATION_STATUS) != null) {
            if (localizedByUser) {
                status.attribute(IWS_TRANSLATION_STATUS).setValue("finished");
            } else if (localizedByLocalTM) {
                status.attribute(IWS_TRANSLATION_STATUS).setValue("pending");
            }
        } else {
            if (localizedByUser) {
                status.addAttribute(IWS_TRANSLATION_STATUS, "finished");
            } else if (localizedByLocalTM) {
                status.addAttribute(IWS_TRANSLATION_STATUS, "pending");
            }
        }

        if (status.attribute(IWS_TRANSLATION_TYPE) != null) {
            if (localizedByMT) {
                status.attribute(IWS_TRANSLATION_TYPE).setValue("machine_translation_mt");
            } else if (localizedByUser || localizedByLocalTM) {
                status.attribute(IWS_TRANSLATION_TYPE).setValue("manual_translation");
            }
        } else {
            if (localizedBy != null) {
                if (localizedByMT) {
                    status.addAttribute(IWS_TRANSLATION_TYPE, "machine_translation_mt");
                } else if (localizedByUser || localizedByLocalTM) {
                    status.addAttribute(IWS_TRANSLATION_TYPE, "manual_translation");
                }
            }
        }
    }

    iwsStr = dom.selectSingleNode("//iws:segment-metadata").asXML();
    String str = "xmlns:iws=\"http://www.idiominc.com/ws/asset\"";
    iwsStr = iwsStr.replace(str, "");
    skeleton = skeleton.substring(0, begin) + iwsStr + skeleton.substring(end);

    return skeleton;
}

From source file:com.globalsight.terminology.exporter.MtfWriter.java

License:Apache License

/**
 * Converts a GlobalSight concept group to a MultiTerm iX concept
 * group. Differences:/*from   w  w  w . j  av  a2 s. co  m*/
 *
 *  - concept level <descrip type="entryClass|status"> -->
 *    <system type="entryClass|status">
 *
 *  - <language name="English" locale="en_US" /> -->
 *    <language type="English" lang="EN" />
 *
 *  - <noteGrp><note> -->
 *    <descripGrp><descrip type="note"></descripGrp>
 *
 *  - <note> -->  (should not be produced but could be in old data)
 *    <descripGrp><descrip type="note"></descripGrp>
 *
 *  - <sourceGrp><source></sourceGrp> -->
 *    <descripGrp><descrip type="source"></descripGrp>
 *
 *  - descripGrp is not recursive
 */
private Document convertToMtf(Document p_elem) {
    List nodes;
    Node node;
    Element root = p_elem.getRootElement();
    Element elem;
    Iterator it;
    ListIterator lit;

    if (false && CATEGORY.isDebugEnabled()) {
        CATEGORY.debug("gt2mtf init: " + p_elem.asXML());
    }

    // rewrite <descrip type=entryClass> (only one on concept level)
    nodes = root.selectNodes("descrip[@type='entryClass']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();
        Element parent = elem.getParent();
        parent.remove(elem);
        parent.addElement("system").addAttribute("type", "entryClass").addText(elem.getText());
    }

    // rewrite <descrip type=status> (?? used in MTF?)
    nodes = root.selectNodes("descrip[@type='status']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();
        Element parent = elem.getParent();
        parent.remove(elem);
        parent.addElement("system").addAttribute("type", "status").addText(elem.getText());
    }

    // rewrite <noteGrp>
    while (true) {
        // refresh the node list, we're rewriting the structure
        node = root.selectSingleNode("//noteGrp");
        if (node == null) {
            break;
        }

        elem = (Element) node;

        Element parent = elem.getParent();
        parent.remove(elem);

        Element newNote = parent.addElement("descripGrp");
        Element note = null;

        // copy all child nodes but remember the <note>
        for (lit = elem.elements().listIterator(); lit.hasNext();) {
            Element child = (Element) lit.next();

            if (child.getName().equals("note")) {
                note = child;
            } else {
                lit.remove();
                newNote.add(child);
            }
        }

        // create new <descrip type="note"> with note's value
        newNote.addElement("descrip").addAttribute("type", "note").addText(note.getText());
    }

    // rewrite single <note>, if any are left in the entry
    while (true) {
        // refresh the node list, we're rewriting the structure
        node = root.selectSingleNode("//note");
        if (node == null) {
            break;
        }

        Element note = (Element) node;

        Element parent = note.getParent();
        parent.remove(note);

        Element newNote = parent.addElement("descripGrp");
        newNote.addElement("descrip").addAttribute("type", "note").addText(note.getText());
    }

    // rewrite <sourceGrp>
    while (true) {
        // refresh the node list, we're rewriting the structure
        node = root.selectSingleNode("//sourceGrp");
        if (node == null) {
            break;
        }

        elem = (Element) node;

        Element parent = elem.getParent();
        parent.remove(elem);

        Element newSource = parent.addElement("descripGrp");
        Element source = null;

        // copy all child nodes but remember the <source>
        for (lit = elem.elements().listIterator(); lit.hasNext();) {
            Element child = (Element) lit.next();

            if (child.getName().equals("source")) {
                source = child;
            } else {
                lit.remove();
                newSource.add(child);
            }
        }

        // create new <descrip type="source"> with source's value
        newSource.addElement("descrip").addAttribute("type", "source").addText(source.getText());
    }

    // rewrite <language>
    nodes = root.selectNodes("//languageGrp/language");

    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();

        Attribute nameAttr = elem.attribute("name");
        Attribute langAttr = elem.attribute("locale");

        String langName = nameAttr.getValue();
        String langLocale = langAttr.getValue();

        // locales in MTF consist of 2 letter codes (uppercase).
        langLocale = langLocale.substring(0, 2).toUpperCase();

        elem.remove(nameAttr);
        elem.remove(langAttr);

        elem.addAttribute("type", langName);
        elem.addAttribute("lang", langLocale);
    }

    if (false && CATEGORY.isDebugEnabled()) {
        CATEGORY.debug("gt2mtf done: " + p_elem.asXML());
    }

    return p_elem;
}

From source file:com.globalsight.terminology.importer.MtfReaderThread.java

License:Apache License

/**
 * Converts a MultiTerm MTF concept group to a GlobalSight concept
 * group. Differences:/*from www.j a va 2s .c  o m*/
 *
 *  - <system type="entryClass|status"> -->
 *    <descrip type="entryClass|status">
 *
 *  - <language type="English" lang="EN" /> -->
 *    <language name="English" locale="en_US" />
 *
 *  - <descripGrp><descrip type="note"> -->
 *    <noteGrp><note>
 *
 *  - <descripGrp><descrip type="source"> -->
 *    <sourceGrp><source>
 *
 *  - descripGrp is recursive, must map to noteGrps or delete.
 *
 *  - remove empty descripGrp <descrip type="Graphic"/>
 */
private Element convertMtf(Element p_elem) {
    List nodes;
    Node node;
    Element elem;
    Iterator it;
    ListIterator lit;

    // fix <system>
    nodes = p_elem.elements("system");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();
        p_elem.remove(elem);
        p_elem.addElement("descrip").addAttribute("type", elem.attributeValue("type")).addText(elem.getText());
    }

    // fix Graphic; we cannot handle them, so remove them
    nodes = p_elem.selectNodes("descripGrp[descrip/@type='Graphic']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();
        p_elem.remove(elem);
    }

    // convert <descripGrp><descrip type="note"> to noteGrp
    nodes = p_elem.selectNodes(".//descripGrp[descrip/@type='note']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();

        convertToNoteGrp(elem);
    }

    // convert <descripGrp><descrip type="source"> to sourceGrp
    nodes = p_elem.selectNodes(".//descripGrp[descrip/@type='source']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();

        convertToSourceGrp(elem);
    }

    // Convert recursive descripGrps to noteGrps if possible.
    convertRecursiveDescripGrps(p_elem, ".//conceptGrp/descripGrp");
    convertRecursiveDescripGrps(p_elem, ".//languageGrp/descripGrp");
    convertRecursiveDescripGrps(p_elem, ".//termGrp/descripGrp");

    // Remove the recursive descripGrps that are left over.
    // (In case there are doubly recursive descrips and stuff.)
    removeRecursiveDescripGrps(p_elem);

    // fix <language>
    nodes = p_elem.selectNodes("languageGrp/language");

    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();

        Attribute nameAttr = elem.attribute("type");
        Attribute langAttr = elem.attribute("lang");

        String langName = nameAttr.getValue();
        String langLocale = langAttr.getValue();

        // locales in entries consist of 2 letter codes.
        langLocale = langLocale.substring(0, 2).toLowerCase();

        elem.remove(nameAttr);
        elem.remove(langAttr);

        elem.addAttribute("name", langName);
        elem.addAttribute("locale", langLocale);
    }

    return p_elem;
}

From source file:com.globalsight.terminology.importer.MtfReaderThread.java

License:Apache License

private void convertToNoteGrp(Element p_elem) {
    Element noteGrp = p_elem.createCopy("noteGrp");

    // noteGrps contain no other fields, remove all child
    // nodes, remembering the <descrip type="note"> itself
    for (ListIterator lit = noteGrp.elements().listIterator(); lit.hasNext();) {
        Element child = (Element) lit.next();

        if (child.getName().equals("descrip")) {
            Element note = child.createCopy("note");
            note.remove(note.attribute("type"));

            lit.set(note);/* ww  w. j av a2 s  .  c  om*/
        } else {
            lit.remove();
        }
    }

    Element parent = p_elem.getParent();
    parent.content().set(parent.indexOf(p_elem), noteGrp);
}

From source file:com.globalsight.terminology.importer.MtfReaderThread.java

License:Apache License

private void convertToSourceGrp(Element p_elem) {
    Element sourceGrp = p_elem.createCopy("sourceGrp");

    // sourceGrp contains noteGrp, remove all non-noteGrp
    // children, remembering the <descrip type="source"> itself
    for (ListIterator lit = sourceGrp.elements().listIterator(); lit.hasNext();) {
        Element child = (Element) lit.next();

        if (child.getName().equals("descrip")) {
            Element source = child.createCopy("source");
            source.remove(source.attribute("type"));

            lit.set(source);/*  w  w  w  .  j  a va  2s  . c o m*/
        } else if (!child.getName().equals("noteGrp")) {
            lit.remove();
        }
    }

    Element parent = p_elem.getParent();
    parent.content().set(parent.indexOf(p_elem), sourceGrp);
}

From source file:com.haulmont.cuba.core.sys.persistence.PersistenceConfigProcessor.java

License:Apache License

public void create() {
    if (sourceFileNames == null || sourceFileNames.isEmpty())
        throw new IllegalStateException("Source file list not set");
    if (StringUtils.isBlank(outFileName))
        throw new IllegalStateException("Output file not set");

    Map<String, String> classes = new LinkedHashMap<>();
    Map<String, String> properties = new HashMap<>();

    properties.putAll(DbmsSpecificFactory.getDbmsFeatures(storeName).getJpaParameters());

    for (String fileName : sourceFileNames) {
        Document doc = getDocument(fileName);
        Element puElem = findPersistenceUnitElement(doc.getRootElement());
        if (puElem == null)
            throw new IllegalStateException(
                    "No persistence unit named 'cuba' found among multiple units inside " + fileName);
        addClasses(puElem, classes);//from w  w  w .j a v a 2 s.c  o m
        addProperties(puElem, properties);
    }

    for (String name : AppContext.getPropertyNames()) {
        if (name.startsWith("eclipselink.")) {
            properties.put(name, AppContext.getProperty(name));
        }
    }

    if (!Stores.isMain(storeName))
        properties.put(PersistenceImplSupport.PROP_NAME, storeName);

    File outFile;
    try {
        outFile = new File(outFileName).getCanonicalFile();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    outFile.getParentFile().mkdirs();

    boolean ormXmlCreated = true;
    String disableOrmGenProp = AppContext.getProperty("cuba.disableOrmXmlGeneration");
    if (!Boolean.parseBoolean(disableOrmGenProp)) {
        MappingFileCreator mappingFileCreator = new MappingFileCreator(classes.values(), properties,
                outFile.getParentFile());
        ormXmlCreated = mappingFileCreator.create();
    }

    String fileName = sourceFileNames.get(sourceFileNames.size() - 1);
    Document doc = getDocument(fileName);
    Element rootElem = doc.getRootElement();

    Element puElem = findPersistenceUnitElement(rootElem);
    if (puElem == null)
        throw new IllegalStateException(
                "No persistence unit named 'cuba' found among multiple units inside " + fileName);

    String puName = AppContext.getProperty("cuba.persistenceUnitName");
    if (!StringUtils.isEmpty(puName)) {
        if (!Stores.isMain(storeName))
            puName = puName + "_" + storeName;
        puElem.addAttribute("name", puName);
    }

    for (Element element : new ArrayList<>(Dom4j.elements(puElem, "class"))) {
        puElem.remove(element);
    }

    puElem.addElement("provider").setText("org.eclipse.persistence.jpa.PersistenceProvider");

    if (ormXmlCreated) {
        puElem.addElement("mapping-file").setText("orm.xml");
    }

    for (String className : classes.values()) {
        puElem.addElement("class").setText(className);
    }

    puElem.addElement("exclude-unlisted-classes");

    Element propertiesEl = puElem.element("properties");
    if (propertiesEl != null)
        puElem.remove(propertiesEl);

    propertiesEl = puElem.addElement("properties");
    for (Map.Entry<String, String> entry : properties.entrySet()) {
        Element element = propertiesEl.addElement("property");
        element.addAttribute("name", entry.getKey());
        element.addAttribute("value", entry.getValue());
    }

    log.info("Creating file " + outFile);
    OutputStream os = null;
    try {
        os = new FileOutputStream(outFileName);
        Dom4j.writeDocument(doc, true, os);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopGroupBox.java

License:Apache License

@Override
public boolean saveSettings(Element element) {
    if (!isSettingsEnabled()) {
        return false;
    }/*w  ww .  jav  a2s.  c  om*/

    Element groupBoxElement = element.element("groupBox");
    if (groupBoxElement != null) {
        element.remove(groupBoxElement);
    }
    groupBoxElement = element.addElement("groupBox");
    groupBoxElement.addAttribute("expanded", BooleanUtils.toStringTrueFalse(isExpanded()));
    return true;
}

From source file:com.haulmont.cuba.desktop.gui.components.SwingXTableSettings.java

License:Apache License

@Override
public boolean saveSettings(Element element) {
    element.addAttribute("horizontalScroll", String.valueOf(table.isHorizontalScrollEnabled()));

    saveFontPreferences(element);//from  w ww  .  j a  v  a 2  s.  c om

    Element columnsElem = element.element("columns");
    if (columnsElem != null) {
        element.remove(columnsElem);
    }
    columnsElem = element.addElement("columns");

    final List<TableColumn> visibleTableColumns = table.getColumns();
    final List<Table.Column> visibleColumns = new ArrayList<>();
    for (TableColumn tableColumn : visibleTableColumns) {
        visibleColumns.add((Table.Column) tableColumn.getIdentifier());
    }

    List<TableColumn> columns = table.getColumns(true);
    Collections.sort(columns, new Comparator<TableColumn>() {
        @SuppressWarnings("SuspiciousMethodCalls")
        @Override
        public int compare(TableColumn col1, TableColumn col2) {
            if (col1 instanceof TableColumnExt && !((TableColumnExt) col1).isVisible()) {
                return 1;
            }
            if (col2 instanceof TableColumnExt && !((TableColumnExt) col2).isVisible()) {
                return -1;
            }
            int i1 = visibleColumns.indexOf(col1.getIdentifier());
            int i2 = visibleColumns.indexOf(col2.getIdentifier());
            return Integer.compare(i1, i2);
        }
    });

    for (TableColumn column : columns) {
        Element colElem = columnsElem.addElement("column");
        colElem.addAttribute("id", column.getIdentifier().toString());

        int width = column.getWidth();
        colElem.addAttribute("width", String.valueOf(width));

        if (column instanceof TableColumnExt) {
            Boolean visible = ((TableColumnExt) column).isVisible();
            colElem.addAttribute("visible", visible.toString());
        }
    }

    if (table.getRowSorter() != null) {
        TableColumn sortedColumn = table.getSortedColumn();
        List<? extends RowSorter.SortKey> sortKeys = table.getRowSorter().getSortKeys();
        if (sortedColumn != null && !sortKeys.isEmpty()) {
            columnsElem.addAttribute("sortColumn", String.valueOf(sortedColumn.getIdentifier()));
            columnsElem.addAttribute("sortOrder", sortKeys.get(0).getSortOrder().toString());
        }
    }

    return true;
}