Example usage for org.dom4j Element elementIterator

List of usage examples for org.dom4j Element elementIterator

Introduction

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

Prototype

Iterator<Element> elementIterator();

Source Link

Document

Returns an iterator over all this elements child elements.

Usage

From source file:cbir.reader.XMLReader.java

License:Open Source License

/**
 * Parses image information from a given XML file and returns a list of
 * images with their descriptors (only MPEG_EHD and CEDD extracted by
 * img(rummager))./*from   ww w . ja va 2 s .  c o m*/
 * 
 * @param file
 *            The given img(rummager) XML file.
 * @return a list of images with their descriptors.
 * @throws DocumentException
 */
public List<ImageContainer> parseXMLFile(File file) throws DocumentException {

    // Read XML file
    SAXReader reader = new SAXReader();
    Document document = reader.read(file);

    // Get first Element
    Element rootElement = document.getRootElement();

    // Iterate + get image paths + descriptors

    // outer loop (Info, Data)
    for (@SuppressWarnings("rawtypes")
    Iterator iter = rootElement.elementIterator(); iter.hasNext();) {
        Element element = (Element) iter.next();

        // inner loop (Image Data)
        for (@SuppressWarnings("rawtypes")
        Iterator innerIter = element.elementIterator(); innerIter.hasNext();) {
            Element innerElement = (Element) innerIter.next();

            // data loop (Filename, EHD, RGB)
            for (@SuppressWarnings("rawtypes")
            Iterator dataIter = innerElement.elementIterator(); dataIter.hasNext();) {

                // get Filename
                Element dataElement = (Element) dataIter.next();
                String filename = new String(dataElement.getText());
                List<Descriptor> descriptors = new LinkedList<Descriptor>();
                while (dataIter.hasNext()) {
                    // get descriptors
                    dataElement = (Element) dataIter.next();
                    if (dataElement.getName().equals("EHD") || dataElement.getName().equals("CEDD"))
                        descriptors.add(readDescriptor(dataElement));
                }

                // construct Image and save in list
                ImageContainer image = new ImageContainer(filename,
                        descriptors.toArray(new Descriptor[descriptors.size()]));
                imageList.add(image);
            }
        }
    }
    return imageList;

}

From source file:ch.epfl.codimsd.qep.QEPFactory.java

License:Open Source License

/**
 * Build a hashtable containing operator opNode structures, according to what is defined
 * in the query execution plan.//  www.  java 2s. co m
 * 
 * @param document dom4j document of the QEP.
 * @return the opnode hashtable.
 * 
 * @throws QEPInitializationException
 */
private static Hashtable<String, OpNode> buildOpNodeTable(Document document) throws QEPInitializationException {

    Hashtable<String, OpNode> operatorList = new Hashtable<String, OpNode>();

    /*List listMod = document.selectNodes( "//qep:Module" );
    Element modElement = (Element)listMod;
    String[] stringType = modElement.attributeValue("type").split(",");
    int numberOfIterations = Integer.parseInt(modElement.attributeValue("numberOfIterations"));
    */
    List list = document.selectNodes("//op:Operator");
    Iterator itt = list.iterator();

    while (itt.hasNext()) {

        Element opElement = (Element) itt.next();

        // Get operator ID from xml QEP
        int opID = Integer.parseInt(opElement.attributeValue("id"));

        // Build producers from xml QEP
        String[] stringProducers = opElement.attributeValue("prod").split(",");
        int[] producers = new int[stringProducers.length];

        for (int i = 0; i < stringProducers.length; i++)
            producers[i] = Integer.parseInt(stringProducers[i]);

        // Get operator type
        String type = opElement.attributeValue("type");

        // Get parallelizable information
        String parallelAtt = opElement.attributeValue("parallelizable");
        boolean parallelizable = false;
        if (parallelAtt != null) {
            if (parallelAtt.equalsIgnoreCase("true"))
                parallelizable = true;
        }

        // Get operator name from xml QEP
        Iterator opItt = opElement.elementIterator();
        Node xmlOpNode = (Node) opItt.next();
        String opName = xmlOpNode.getText();

        // Build operator parameters
        int i = 0;
        String paramString = "";
        String[] params = null;

        if (opItt.hasNext()) {

            Element parameterList = (Element) opItt.next();
            Iterator paramItt = parameterList.elementIterator();

            while (paramItt.hasNext()) {

                Node parameter = (Node) paramItt.next();
                paramString = paramString + parameter.getText() + ";";
                i++;
            }

            params = new String[i];
            params = paramString.split(";");
        }

        // Build operator timeStamp
        long idTimeStamp = System.currentTimeMillis();

        // Build OpNode object for this operator
        OpNode opNode = new OpNode(opID, opName, producers, params, idTimeStamp + "", type, parallelizable);

        // Build DataSources if necessary
        if (opNode.getType() != null) {

            if (opNode.getType().equalsIgnoreCase("Scan")) {

                // Write the number of tuples in the BlackBoard as specified in the QEP
                // This operation is not done in remote nodes as G2N has already been called
                String numberOfTuples = opElement.attributeValue(Constants.QEP_SCAN_NUMBER_TUPLES);

                // In remote QEP this parameter is null, so we dont write again the field numberOfTuples
                // used in the DiscoveryOptimizer when it calls G2N
                if (numberOfTuples != null) {

                    if (!numberOfTuples.equalsIgnoreCase("?")) {

                        BlackBoard bl = BlackBoard.getBlackBoard();
                        bl.put(Constants.QEP_SCAN_NUMBER_TUPLES, numberOfTuples);
                    }
                }

                try {
                    DataSourceManager dsManager = DataSourceManager.getDataSourceManager();
                    dsManager.createDataSources(opNode);

                } catch (Exception ex) {
                    throw new QEPInitializationException(
                            "Error creating the " + "datasource : " + ex.getMessage());
                }
            }
        }

        // Put OpNode in the QEP
        operatorList.put(opID + "", opNode);
    }

    return operatorList;
}

From source file:ch.epfl.codimsd.qep.QEPFactory.java

License:Open Source License

/**
 * Add an operator template to the QEP Document.
 * //from   w w  w .java  2 s . com
 * @param document dom4j document.
 * @param opNode opNode structure of the operator to build.
 * @param opID identifier of the operator.
 */
private static void createOperator(Document document, OpNode opNode, int opID) {

    Element root = document.getRootElement();
    Iterator ittRoot = root.elementIterator();
    Element qepElement = (Element) ittRoot.next();

    // create new operator xml template (attributes, name)
    Element newOp = qepElement.addElement("op:Operator").addAttribute("id", opID + "").addAttribute("prod",
            buildProducers(opNode));

    if (opNode.getType() != null)
        newOp.addAttribute("type", opNode.getType());

    Element newNameOp = newOp.addElement("Name");
    newNameOp.addText(opNode.getOpName());

    // create operator xml parameters
    if (opNode.getParams() != null) {
        if (opNode.getParams().length != 0) {
            Element newParameterList = newOp.addElement("ParameterList");
            for (int i = 0; i < opNode.getParams().length; i++) {
                Element newParam = newParameterList.addElement("Param");
                newParam.addText(opNode.getParams()[i]);
            }
        }
    }
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

@SuppressWarnings("unchecked")
protected List<Element> resolve(Element element, String path) throws XmlConfigException {
    final List<Element> resolved = new ArrayList<Element>();
    Attribute refAtt = element.attribute(XmlAttribute.ref.getXmlName());
    if (refAtt == null) {
        resolved.add(element);/*from w  w  w.j  a  v  a 2 s .com*/
    } else {
        resolveAttributeValue(refAtt, path);
        List<Element> refElCont = getReferredElementContent(refAtt.getValue(), path);
        for (final Element el : refElCont) {
            final Element newEl = el.createCopy();
            element.getParent().add(newEl);
            resolved.addAll(resolve(newEl, XmlUtil.getElementPath(el, true/*recurseParents*/)));
        }
        if (!element.getParent().remove(element)) {
            throw new RuntimeException("internal error: should have been removed");
        }
    }

    for (Element elem : resolved) {
        Iterator<Attribute> itA = elem.attributeIterator();
        while (itA.hasNext()) {
            Attribute att = itA.next();
            resolveAttributeValue(att, path);
        }

        //         resolve(elem.elementIterator(), path);
        Iterator<Element> itE = elem.elementIterator();
        while (itE.hasNext()) {
            Element child = itE.next();
            resolve(child, path + "/" + XmlUtil.getElementPath(child, false /*recurseParents*/));
        }
        if (elem.attribute(XmlAttribute.ref.getXmlName()) != null) {
            throw new RuntimeException("internal error: should have been resolved");
        }
    }
    return resolved;
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

@SuppressWarnings("unchecked")
public void printUsage(PrintStream stream, String usageName) throws XmlConfigException {
    Element element = XmlUtil.getChildElementByAttributeValue(getRootElement(), XmlElement.usage,
            XmlAttribute.name, usageName, true /*throwExceptionIfNull*/);
    printUsageLines(stream, element.elementIterator());
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

@SuppressWarnings("unchecked")
private void printUsageLines(PrintStream stream, Iterator<Element> usageChildIt) throws XmlConfigException {
    while (usageChildIt.hasNext()) {
        Element el = usageChildIt.next();
        if (XmlUtil.isExpectedElementName(el, XmlElement.line)) {
            Element copy = el.createCopy();
            List<Element> res = resolve(copy, XmlUtil.getElementPath(copy, true /*recurseParents*/));
            for (Element r : res) {
                stream.println(r.attributeValue(XmlAttribute.value.getXmlName()));
            }/*from   w ww . j a v  a  2  s .  c  o  m*/
        } else if (XmlUtil.isExpectedElementName(el, XmlElement.usage)) {
            Element parentCopy = el.getParent().createCopy();
            Element copy = el.createCopy();
            parentCopy.add(copy);
            List<Element> res = resolve(copy, XmlUtil.getElementPath(copy, true /*recurseParents*/));
            for (Element r : res) {
                printUsageLines(stream, r.elementIterator());
            }
        }

    }
}

From source file:ch.javasoft.xml.config.XmlPrint.java

License:BSD License

/**
 * Print the given element using the given print writer and initial 
 * indention//from w  ww . j  a  v  a 2s .c o m
 * @param elem      the xml element
 * @param indention   the initial indention
 * @param writer   the print writer to use for the output
 */
@SuppressWarnings("unchecked")
public void print(Element elem, String indention, PrintWriter writer) {
    writer.print(indention + "<" + elem.getName());

    Iterator<Attribute> itAtt = elem.attributeIterator();
    Iterator<Element> itElem = elem.elementIterator();

    if (elem.hasMixedContent() || (elem.hasContent() && !itElem.hasNext())) {
        Iterator<Node> it = elem.nodeIterator();
        while (it.hasNext()) {
            Node node = it.next();
            if (node instanceof CharacterData) {
                if (!(node instanceof Comment) && node.getText().trim().length() != 0) {
                    throw new IllegalArgumentException(
                            "text content not supported: \"" + node.getText() + "\"");
                }
            } else if (!(node instanceof Element || node instanceof Attribute)) {
                throw new IllegalArgumentException("only attributes and elements are supported");
            }
        }
    }
    while (itAtt.hasNext()) {
        Attribute att = itAtt.next();
        final String attName = att.getName();
        final String attValue = att.getValue();
        writer.print(" " + attName + "=\"" + escapeAttributeValue(attValue) + "\"");
    }
    if (!itElem.hasNext()) {
        writer.println("/>");
    } else {
        writer.println(">");
        while (itElem.hasNext()) {
            print(itElem.next(), indention + getIndention(), writer);
        }
        writer.println(indention + "</" + elem.getName() + ">");
    }
    writer.flush();
}

From source file:com.ah.be.parameter.BeParaModuleDefImpl.java

private void changeOsVersionFile() {
    String fingerprints = ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME;
    String fingerprintsChg = ImportTextFileAction.OS_VERSION_FILE_PATH
            + ImportTextFileAction.OS_VERSION_FILE_NAME_CHG;
    FileWriter fWriter = null;//from w w  w  .  j  a v  a 2  s.c o m
    try {
        if (new File(fingerprints).exists() && new File(fingerprintsChg).exists()) {
            List<String> lines = NmsUtil.readFileByLines(fingerprints);
            List<String> replaceOsName = new ArrayList<>();
            List<String> replaceOption55 = new ArrayList<>();
            String preHmVer = NmsUtil.getHiveOSVersion(NmsUtil
                    .getVersionInfo(BeAdminCentOSTools.ahBackupdir + File.separatorChar + "hivemanager.ver"));

            // parse os_dhcp_fingerprints_changes.xml
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fingerprintsChg));
            Element root = document.getRootElement();
            List<?> fingerprintElems = root.elements();
            for (Object obj : fingerprintElems) {
                Element fingerprintElem = (Element) obj;
                String osName = fingerprintElem.attributeValue("osname");
                for (Iterator<?> iterator = fingerprintElem.elementIterator(); iterator.hasNext();) {
                    Element option55Elem = (Element) iterator.next();
                    String node_option55_text = option55Elem.getText();
                    Attribute version = option55Elem.attribute("version");
                    String version_text = version.getText();
                    if (NmsUtil.compareSoftwareVersion(preHmVer, version_text) <= 0) {
                        if (!replaceOption55.contains(node_option55_text)) {
                            replaceOsName.add(osName);
                            replaceOption55.add(node_option55_text);
                        }
                    }
                }
            }

            if (replaceOption55.isEmpty()) {
                log.debug("No need to modify os_dhcp_fingerprints.txt.");
                FileUtils.deleteQuietly(new File(fingerprintsChg));
                return;
            }

            for (String option55 : replaceOption55) {
                int size = lines.size();
                boolean remove = false;
                for (int i = size - 1; i >= 0; i--) {
                    if (remove) {
                        lines.remove(i);
                        remove = false;
                    } else {
                        if (option55.equals(lines.get(i))) {
                            if (i < size - 1 && i > 0
                                    && lines.get(i - 1).startsWith(ImportTextFileAction.OS_STR)
                                    && lines.get(i + 1).equals(ImportTextFileAction.END_STR)) {
                                lines.remove(i + 1);
                                lines.remove(i);
                                remove = true;
                            } else {
                                lines.remove(i);
                            }
                        }
                    }
                }
            }

            //insert
            for (int i = 0; i < replaceOption55.size(); i++) {
                String option55 = replaceOption55.get(i);
                String osName = ImportTextFileAction.OS_STR + replaceOsName.get(i);

                if (!lines.contains(option55)) {
                    if (lines.contains(osName)) {
                        List<String> temp = lines.subList(lines.indexOf(osName), lines.size());
                        int index = lines.indexOf(osName) + temp.indexOf(ImportTextFileAction.END_STR);
                        lines.add(index, option55);

                    } else {
                        lines.add(osName);
                        lines.add(option55);
                        lines.add(ImportTextFileAction.END_STR);
                    }
                }
            }

            fWriter = new FileWriter(fingerprints, false);
            for (String line : lines) {
                if (line != null && line.startsWith(ImportTextFileAction.VERSION_STR)) {
                    String version = line.substring(line.indexOf(ImportTextFileAction.VERSION_STR)
                            + ImportTextFileAction.VERSION_STR.length());
                    BigDecimal b1 = new BigDecimal(version);
                    BigDecimal b2 = new BigDecimal("0.1");
                    float fVer = b1.add(b2).floatValue();
                    String versionStr = ImportTextFileAction.VERSION_STR + String.valueOf(fVer) + "\r\n";
                    fWriter.write(versionStr);
                } else {
                    fWriter.write(line + "\r\n");
                }
            }
            fWriter.close();

            //compress file
            String strCmd = "";
            StringBuffer strCmdBuf = new StringBuffer();
            strCmdBuf.append("tar zcvf ");
            strCmdBuf.append(
                    ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME_TAR);
            strCmdBuf.append(" -C ");
            strCmdBuf.append(ImportTextFileAction.OS_VERSION_FILE_PATH);
            strCmdBuf.append(" " + ImportTextFileAction.OS_VERSION_FILE_NAME);
            strCmd = strCmdBuf.toString();
            boolean compressResult = BeAdminCentOSTools.exeSysCmd(strCmd);
            if (!compressResult) {
                log.error("compress os_dhcp_fingerprints.txt error.");
                return;
            }

            FileUtils.deleteQuietly(new File(fingerprintsChg));
        } else {
            if (new File(fingerprintsChg).exists()) {
                FileUtils.deleteQuietly(new File(fingerprintsChg));
            }
        }
    } catch (Exception e) {
        setDebugMessage("change OsVersionFile error: ", e);
    } finally {
        if (fWriter != null) {
            try {
                fWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:com.ah.be.performance.db.TablePartitionProcessor.java

private void init() {
    try {//from  w w w.j  a  va 2 s. co  m
        File f = new File(TABLE_PARTITION_CONF_FILE);
        SAXReader reader = new SAXReader();
        Document doc = reader.read(f);
        Element root = doc.getRootElement();
        Element cata = null;

        int catalog = 1;
        for (Iterator<?> i = root.elementIterator(); i.hasNext();) {
            //for catalog
            cata = (Element) i.next();
            String enable = cata.elementText("enable");
            if (enable != null && enable.equalsIgnoreCase("false"))
                continue;
            int default_maxtime = Integer.parseInt(cata.elementTextTrim("default_maxtime"));
            int default_interval = Integer.parseInt(cata.elementTextTrim("default_interval"));
            int table_partition_number = Integer.parseInt(cata.elementTextTrim("table_partition_number"));
            int default_max_record = Integer.parseInt(cata.elementTextTrim("default_max_record"));
            int default_max_record_per_partition = Integer
                    .parseInt(cata.elementTextTrim("default_max_record_per_partition"));
            int maxtime_policy = Integer.parseInt(cata.elementTextTrim("maxtime_policy"));
            int interval_policy = Integer.parseInt(cata.elementTextTrim("interval_policy"));
            int max_record_policy = Integer.parseInt(cata.elementTextTrim("max_record_policy"));

            addTableCatalogInfo(catalog, default_maxtime, default_interval, table_partition_number,
                    default_max_record, default_max_record_per_partition, maxtime_policy, interval_policy,
                    max_record_policy);

            List<?> tableElements = cata.elements("table");
            //for table in catalog
            for (int j = 0; j < tableElements.size(); j++) {
                Element table = (Element) tableElements.get(j);
                String tableName = table.attributeValue("name");
                String schemaName = table.elementTextTrim("schemaname");
                String timeField = table.elementTextTrim("timefield");
                addTableInfo(schemaName, tableName, timeField, catalog);
            }

            catalog++;
        }
    } catch (Exception e) {
        BeLogTools.error(HmLogConst.M_PERFORMANCE_TABLEPARTITION, "Fail to init table partition configure file",
                e);
    }
}

From source file:com.ah.ui.actions.config.USBModemAction.java

private List<USBModem> readUSBConfigFile(Document document) {
    List<USBModem> usbModemLst = new ArrayList<USBModem>();

    Element root = document.getRootElement();
    if (root != null) {
        for (Iterator<?> it = root.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();
            if ("modems".equals(element.getName())) {
                for (Iterator<?> it1 = element.elementIterator(); it1.hasNext();) {
                    Element element1 = (Element) it1.next();
                    if ("modem".equals(element1.getName())) {
                        usbModemLst.add(readUSBModem(element1));
                    }//from   w w w .j  a  va  2  s. co m
                }
            }
        }
    }

    return usbModemLst;
}