Example usage for org.dom4j Document addElement

List of usage examples for org.dom4j Document addElement

Introduction

In this page you can find the example usage for org.dom4j Document addElement.

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:com.glaf.jbpm.xml.JpdlXmlReader.java

License:Apache License

public void convert(File dir) {
    if (!(dir.exists() || dir.isDirectory())) {
        return;/*ww w . j a v  a  2 s . co  m*/
    }
    String[] filelist = dir.list();
    for (int i = 0; i < filelist.length; i++) {
        String filename = dir.getAbsolutePath() + "/" + filelist[i];
        java.io.File file = new java.io.File(filename);
        if (file.isDirectory()) {
            this.convert(file);
        } else if (file.isFile() && file.getName().equals("processdefinition.xml")) {
            List<Todo> todoList = null;
            try {
                todoList = this.read(new FileInputStream(file));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
            if (todoList != null && todoList.size() > 0) {
                index = index + 100;
                Document doc = DocumentHelper.createDocument();
                doc.setXMLEncoding("GBK");
                Element root = doc.addElement("rows");
                Iterator<Todo> iter = todoList.iterator();
                while (iter.hasNext()) {
                    Todo todo = (Todo) iter.next();
                    Map<String, Object> dataMap = Tools.getDataMap(todo);
                    dataMap.remove("id");
                    dataMap.remove("locked");
                    dataMap.remove("configFlag");
                    dataMap.remove("versionNo");
                    Element row = root.addElement("row");
                    row.addAttribute("id", String.valueOf(index++));
                    Set<Entry<String, Object>> entrySet = dataMap.entrySet();
                    for (Entry<String, Object> entry : entrySet) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (value != null && !(value instanceof Map<?, ?>) && !(value instanceof Set<?>)
                                && !(value instanceof Collection<?>)) {
                            Element elem = row.addElement("property");
                            elem.addAttribute("name", key);
                            if (key.equals("link") || key.equals("listLink")) {
                                elem.addCDATA(sp + "        " + value.toString());
                            } else {
                                elem.addAttribute("value", value.toString());
                            }
                        }
                    }
                }
                filename = dir.getAbsolutePath() + "/" + "todo.xml";
                Dom4jUtils.savePrettyDoument(doc, filename, "GBK");
                doc = null;
                root = null;
            }
        }
    }
}

From source file:com.globalsight.everest.workflow.WorkflowTemplateAdapter.java

License:Apache License

/**
 * Sets the workflow template name in the xml.
 * //from  w  ww.  jav  a2s . c o m
 * @param p_document
 *            - the xml document of the workflow template.
 * @param p_templateName
 *            - The workflow template name
 */
private void setTemplateName(Document p_document, String p_templateName) {
    p_document.addElement(WorkflowConstants.PROCESS_DEFINITION).addAttribute(WorkflowConstants.ATTR_NAME,
            p_templateName);
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase02PreProcess.java

License:Apache License

/**
 * Convert csv/txt file to xml file/*  ww w  .  j ava  2s.  c  o  m*/
 * 
 * @param format
 * @param originFile
 * @return
 */
private String convertToXML(String format, File originFile) {
    String fileName = originFile.getName();
    // Save the converted file to temp directory
    String xmlFilePath = jobInfo.getTempFile() + File.separator
            + fileName.substring(0, fileName.lastIndexOf(".")) + ".xml";
    File xmlFile = new File(xmlFilePath);
    FileReader fr = null;
    FileInputStream fis = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    XMLWriter output = null;
    try {
        String encoding = FileUtil.guessEncoding(originFile);

        Document document = DocumentHelper.createDocument();
        Element aElement = document.addElement("root");
        aElement.addAttribute("BomInfo", encoding == null ? "" : encoding);

        if (encoding == null) {
            fr = new FileReader(originFile);
            br = new BufferedReader(fr);
        } else {
            fis = new FileInputStream(originFile);
            isr = new InputStreamReader(fis, encoding);
            br = new BufferedReader(isr);
        }

        String str;
        if ("csv".equals(format)) {
            while ((str = br.readLine()) != null) {
                String[] values = str.split("\",\"");
                values[0] = values[0].substring(1);
                values[10] = values[10].substring(0, values[10].length() - 1);
                writeRow(aElement, values);
            }
        } else {
            while ((str = br.readLine()) != null) {
                str = str + "*";
                String[] values = str.split("\\|");
                values[10] = values[10].substring(0, values[10].lastIndexOf("*"));
                writeRow(aElement, values);
            }
        }

        output = new XMLWriter(new FileOutputStream(xmlFile));
        output.write(document);
    } catch (Exception e) {
        String message = "Failed to convert to XML, File Name: " + originFile.getName();
        LogUtil.fail(message, e);
        return null;
    } finally {
        try {
            if (output != null) {
                output.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (fr != null) {
                fr.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return xmlFile.getPath();
}

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

License:Apache License

/**
 * <p>/*from  w  w  w. java  2 s. c om*/
 * Converts a list of column values into an Entry.
 * </p>
 *
 * <p>
 * Algorithmic note: columns are managed in a priority queue. We retrieve
 * the first column and try to map it to the entry. If we can't because the
 * column depends on a later column (associatedColumn field), we add it to
 * the end of the queue. Rinse and repeat until the queue is empty.
 * </p>
 */
private Document buildEntry(String[] p_columns) throws TermbaseException, Exception {
    com.globalsight.terminology.importer.ImportOptions options = (com.globalsight.terminology.importer.ImportOptions) m_options;

    Document result = m_factory.createDocument();
    Element root = result.addElement("conceptGrp");

    // Array that holds the elements as we construct them.
    Element[] nodes = new Element[p_columns.length];
    Element node;

    // An entry must have at least one term to be stored; check this.
    int termCount = 0;

    int index;
    String value;

    // Make copy of column descriptions so we can reorder.
    ArrayList queue = new ArrayList(options.getColumns());

    while (!queue.isEmpty()) {
        ColumnDescriptor col = (ColumnDescriptor) queue.remove(0);

        index = col.m_position;

        // added for ArrayIndexOutOfBoundsException
        if (index >= p_columns.length || index < 0)
            value = "";
        else
            value = p_columns[index];

        if (col.m_type.equals("term")) {
            // build the node and add it to the array so later
            // nodes associated with it can find it (prevent
            // endless loop)
            node = buildTermGrp(value);
            nodes[index] = node;

            // only add termGrp to entry if term is non-empty
            if (value.length() > 0) {
                ++termCount;
                addTermGrp(root, node, col.m_termLanguage);
            } else {
                continue;
            }
        } else if (col.m_type.equals("skip")) {
            continue;
        } else if (col.m_type.equals("source")) {
            int i = Integer.parseInt(col.m_associatedColumn);
            Element otherNode = nodes[i];

            if (otherNode == null) {
                if (!isSkippedColumn(i)) {
                    // The column to which this column belongs has
                    // not been processed yet, but it will be
                    // processed eventually. Put this column at
                    // the end of the queue to be processed later.
                    queue.add(col);
                }

                continue;
            }

            // Now we know which column to associate this column with.
            String type = col.m_type.substring("term".length());

            node = buildSourceGrp(value);
            nodes[index] = node;

            addSourceGrp(otherNode, node);
        }
        // All concept-related attributes
        else if (col.m_type.startsWith("concept")) {
            String type = col.m_type.substring("concept".length());

            node = buildDescripGrp(value, type);
            nodes[index] = node;

            addConceptDescripGrp(root, node);
        }
        // All term-related attributes
        else if (col.m_type.startsWith("term")) {
            int i = Integer.parseInt(col.m_associatedColumn);
            Element termNode = nodes[i];

            if (termNode == null) {
                if (!isSkippedColumn(i)) {
                    // Term column to which this column belongs
                    // has not been processed yet, but it will be
                    // processed eventually. Put this column at
                    // the end of the list to be processed later.
                    queue.add(col);
                }

                continue;
            }

            // Now we know which column to associate this column with.
            String type = col.m_type.substring("term".length());

            node = buildDescripGrp(value, type);
            nodes[index] = node;

            addTermDescripGrp(termNode, node);
        } else {
            throw new Exception("invalid column descriptor " + col.m_type);
        }
    }

    if (termCount == 0) {
        throw new Exception("no terms found, ignoring entry");
    }

    return result;
}

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

License:Apache License

/**
 * <p>Converts a list of column values into an Entry.</p>
 *
 * <p>Algorithmic note: columns are managed in a priority queue.
 * We retrieve the first column and try to map it to the entry.
 * If we can't because the column depends on a later column
 * (associatedColumn field), we add it to the end of the queue.
 * Rinse and repeat until the queue is empty.</p>
 *///from  w w  w.  j  a  v  a  2s.  c  om
private Document buildEntry(Cell[] p_cells, List p_colDescriptors) throws TermbaseException, Exception {
    Document result = m_factory.createDocument();
    Element root = result.addElement("conceptGrp");
    ArrayList columnDes = new ArrayList(p_colDescriptors);

    // Array that holds the elements as we construct them.
    Element[] nodes = new Element[p_cells.length];
    Element node;

    // An entry must have at least one term to be stored; check this.
    int termCount = 0;

    int index;
    String value;

    for (int i = 0; i < columnDes.size(); i++) {
        ColumnDescriptor col = (ColumnDescriptor) columnDes.get(i);

        index = col.m_position;
        if (index >= p_cells.length) {
            continue;
        }

        value = p_cells[index].getContents().trim();

        if (col.m_type.equals("term")) {
            // build the node and add it to the array so later
            // nodes associated with it can find it (prevent
            // endless loop)
            node = buildTermGrp(value);
            nodes[index] = node;

            // only add termGrp to entry if term is non-empty
            if (value.length() > 0) {
                ++termCount;
                addTermGrp(root, node, col.m_termLanguage);
            } else {
                continue;
            }
        } else if (col.m_type.equals("skip")) {
            continue;
        } else if (col.m_type.equals("source")) {
            int ac = Integer.parseInt(col.m_associatedColumn);
            if (ac < 0) {
                continue;
            }

            Element otherNode = nodes[ac];
            if (otherNode == null) {
                if (!isSkippedColumn(ac)) {
                    // The column to which this column belongs has
                    // not been processed yet, but it will be
                    // processed eventually.  Put this column at
                    // the end of the queue to be processed later.
                    columnDes.add(col);
                }

                continue;
            }

            // Now we know which column to associate this column with.
            //String type = col.m_type.substring("term".length());

            node = buildSourceGrp(value);
            nodes[index] = node;

            addSourceGrp(otherNode, node);
        }
        // All concept-related attributes
        else if (col.m_type.startsWith("concept")) {
            String type = col.m_type.substring("concept".length());

            node = buildDescripGrp(value, type);
            nodes[index] = node;

            addConceptDescripGrp(root, node);
        }
        // All term-related attributes
        else if (col.m_type.startsWith("term")) {
            int ac = Integer.parseInt(col.m_associatedColumn);
            if (ac < 0) {
                continue;
            }

            Element termNode = nodes[ac];
            if (termNode == null) {
                if (!isSkippedColumn(ac)) {
                    // Term column to which this column belongs
                    // has not been processed yet, but it will be
                    // processed eventually. Put this column at
                    // the end of the list to be processed later.
                    columnDes.add(col);
                }

                continue;
            }

            // Now we know which column to associate this column with.
            String type = col.m_type.substring("term".length());

            node = buildDescripGrp(value, type);
            nodes[index] = node;

            addTermDescripGrp(termNode, node);
        } else {
            throw new Exception("invalid column descriptor " + col.m_type);
        }
    }

    if (termCount == 0) {
        throw new Exception("no terms found, ignoring entry");
    }

    return result;
}

From source file:com.gote.pojo.Tournament.java

License:Apache License

/**
 * Transform Tournament in a formatted XML
 * /*ww  w.j ava  2  s . c o  m*/
 * @return XML to write as a String
 */
public String toXML() {
    // Create document
    Document doc = DocumentHelper.createDocument();

    // Create tournament element
    Element root = doc.addElement(TournamentGOTEUtil.TAG_TOURNAMENT);
    // Add attributes
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_NAME, getTitle());
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_SERVER, getServerType());
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_DATESTART, getStartDate().toString());
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_DATEEND, getEndDate().toString());

    // Add rules
    getTournamentRules().toXML(root);

    // Add players
    Element players = root.addElement(TournamentGOTEUtil.TAG_PLAYERS);
    for (Player player : getParticipantsList()) {
        player.toXML(players);
    }
    // Add rounds
    Element rounds = root.addElement(TournamentGOTEUtil.TAG_ROUNDS);
    for (Round round : getRounds()) {
        round.toXML(rounds);
    }

    StringWriter out = new StringWriter(1024);
    XMLWriter writer;
    try {
        writer = new XMLWriter(OutputFormat.createPrettyPrint());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
    writer.setWriter(out);
    try {
        writer.write(doc);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Return the friendly XML
    return out.toString();
}

From source file:com.gst.mix.service.XBRLBuilder.java

License:Apache License

public String build(final Map<MixTaxonomyData, BigDecimal> map, final Date startDate, final Date endDate,
        final String currency) {
    this.instantScenarioCounter = 1;
    this.durationScenarioCounter = 1;
    this.contextMap = new HashMap<>();
    final Document doc = DocumentHelper.createDocument();
    this.root = doc.addElement("xbrl");

    this.root.addElement("schemaRef").addNamespace("link",
            "http://www.themix.org/sites/default/files/Taxonomy2010/dct/dc-all_2010-08-31.xsd");

    this.startDate = startDate;
    this.endDate = endDate;

    for (final Entry<MixTaxonomyData, BigDecimal> entry : map.entrySet()) {
        final MixTaxonomyData taxonomy = entry.getKey();
        final BigDecimal value = entry.getValue();
        addTaxonomy(this.root, taxonomy, value);

    }//ww  w . ja  v a 2  s  . co  m

    addContexts();
    addCurrencyUnit(currency);
    addNumberUnit();

    doc.setXMLEncoding("UTF-8");

    return doc.asXML();
}

From source file:com.haulmont.cuba.core.entity.ScheduledTask.java

License:Apache License

public void updateMethodParameters(List<MethodParameterInfo> params) {
    Document doc = DocumentHelper.createDocument();
    Element paramsEl = doc.addElement("params");
    for (MethodParameterInfo param : params) {
        Element paramEl = paramsEl.addElement("param");
        paramEl.addAttribute("type", param.getType().getName());
        paramEl.addAttribute("name", param.getName());
        paramEl.setText(param.getValue() != null ? param.getValue().toString() : "");
    }//  ww  w.ja va2s . c o m
    setMethodParamsXml(Dom4j.writeDocument(doc, true));
}

From source file:com.haulmont.cuba.gui.components.filter.FilterParserImpl.java

License:Apache License

/**
 * Converts filter conditions tree to filter xml
 * @param conditions conditions tree/*from w w  w .j  av  a  2 s .c om*/
 * @param valueProperty Describes what parameter value will be serialized to xml: current value or default one
 * @return filter xml
 */
@Override
@Nullable
public String getXml(ConditionsTree conditions, Param.ValueProperty valueProperty) {
    String xml = null;
    if (conditions != null && !conditions.getRootNodes().isEmpty()) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("filter");
        Element element = root.addElement("and");
        for (Node<AbstractCondition> node : conditions.getRootNodes()) {
            recursiveToXml(node, element, valueProperty);
        }
        xml = Dom4j.writeDocument(document, true);
    }
    log.trace("toXML: " + xml);
    return xml;
}

From source file:com.haulmont.cuba.gui.presentations.PresentationsImpl.java

License:Apache License

@Override
public Element getSettings(Presentation p) {
    p = getPresentation(p.getId());/*from   ww w .j  a v  a2s  . c  om*/
    if (p != null) {
        Document doc;
        if (!StringUtils.isEmpty(p.getXml())) {
            doc = Dom4j.readDocument(p.getXml());
        } else {
            doc = DocumentHelper.createDocument();
            doc.setRootElement(doc.addElement("presentation"));
        }
        return doc.getRootElement();
    } else {
        return null;
    }
}