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(QName qName);

Source Link

Document

Returns an iterator over the elements contained in this element which match the given fully qualified name.

Usage

From source file:com.alkacon.opencms.feeder.CmsFeedXmlContentHandler.java

License:Open Source License

/**
 * Initializes the feed rule mappings for this content handler.<p>
 * /*from w  w  w. java  2  s  .c o m*/
 * @param root the "feedrules" element from the appinfo node of the XML content definition
 * @param contentDefinition the content definition the mappings belong to
 * 
 * @throws CmsXmlException if something goes wrong
 */
protected void initFeedRules(Element root, CmsXmlContentDefinition contentDefinition) throws CmsXmlException {

    Iterator i = root.elementIterator(APPINFO_FEEDRULE);
    while (i.hasNext()) {
        // iterate all "mapping" elements in the "mappings" node
        Element element = (Element) i.next();
        // this is a mapping node
        String xmlField = element.attributeValue(APPINFO_ATTR_ELEMENT);
        String maptoName = element.attributeValue(APPINFO_ATTR_MAPTO);
        String maxLength = element.attributeValue(ATTR_MAXLENGTH);
        String defaultValue = element.attributeValue(ATTR_DEFAULT);
        if ((xmlField != null) && (maptoName != null)) {
            // add the element mapping 
            addFeedRule(contentDefinition, xmlField, maptoName, maxLength, defaultValue);
        }
    }
}

From source file:com.amalto.workbench.utils.XmlUtil.java

License:Open Source License

public static void iterate(Element parentElement, String elementName, ElementProcess elementProcess)
        throws DocumentException {

    // iterate through child elements of element with element specific
    // element//from w w  w  .  ja v  a 2s  .c  o m
    // name
    for (Iterator i = parentElement.elementIterator(elementName); i.hasNext();) {
        Element element = (Element) i.next();
        // do something
        elementProcess.process(element);
    }

}

From source file:com.beacon.wlsagent.xml.XmlWorker.java

public Document genMonXml(Document document, BeaconStateCollector fsc) {
    Document resultDoc = null;/*from ww w  . j  av  a  2s . c  o  m*/

    if (fsc.isConnectedToAdmin()) {

        resultDoc = DocumentHelper.createDocument();

        Element root = resultDoc.addElement("MONITOR").addAttribute("Date", BeaconUtil.getStringDate());
        Element osEle = root.addElement("OSResource");

        String cpuStr = BeaconUtil.runShell("sh bin/getCPU.sh");
        String memStr = BeaconUtil.runShell("sh bin/getMEM.sh");
        if ((cpuStr == "") || (memStr == "")) {
            cpuStr = (String) BeaconUtil.runShell().get("CPU");
            memStr = (String) BeaconUtil.runShell().get("MEM");
        }
        osEle.addAttribute("CPU", cpuStr).addAttribute("MEM", memStr);

        List mbeanEleList = document.selectNodes("//MBean");

        ObjectName[] svrRt = fsc.getServerRT();

        int svrRtCount = svrRt.length;

        int f = 0;
        for (Iterator i = mbeanEleList.iterator(); i.hasNext();) {
            Element mbeanEle = (Element) i.next();
            String mbeanName = mbeanEle.attributeValue("name");
            log.debug("Currently dealing with mbean: " + mbeanName);
            Iterator k = mbeanEle.elementIterator("attribute");

            List al = new ArrayList();
            for (; k.hasNext(); f++) {
                al.add(((Element) k.next()).getText());
            }
            String mbeanAttrStrs[] = BeaconUtil.listToStrArray(al);

            for (int m = 0; m < svrRtCount; m++) {
                Map mBeanInfoMap[] = fsc.getMBeanInfoMaps(mbeanAttrStrs, mbeanName, svrRt[m]);
                String svrName = svrRt[m].getKeyProperty("Name");
                log.debug("Currently dealing with server: " + svrRt[m]);
                if (mBeanInfoMap != null) {
                    for (int g = 0; g < mBeanInfoMap.length; g++) {
                        if (mBeanInfoMap[g] != null && mbeanAttrStrs.length > 0) {
                            Element currItem = root.addElement(mbeanName);
                            currItem.addAttribute("serverName", svrName);
                            for (int j = 0; j < mbeanAttrStrs.length; j++) {
                                String curAttr = mbeanAttrStrs[j];
                                Object curAttrVal = mBeanInfoMap[g].get(curAttr);
                                if (curAttrVal != null) {
                                    currItem.addAttribute(curAttr, String.valueOf(curAttrVal));
                                } else {
                                    root.remove(currItem);
                                    j = mbeanAttrStrs.length;
                                }
                                log.debug("Attribute: " + curAttr + " Value: "
                                        + String.valueOf(mBeanInfoMap[g].get(curAttr)));
                            }

                        }
                    }
                }
            }

        }
    } else {
        resultDoc = this.genErrXml("Happened to lose connection to WebLogic Admin. maybe shutdown");
    }

    return resultDoc;
}

From source file:com.beetle.framework.persistence.access.DBConfig.java

License:Apache License

public static List<String> getAllDatasourcename() {
    Document doc = null;/*from   w  w w.ja  va  2s.  com*/
    try {
        List<String> myList = new ArrayList<String>();
        doc = XMLReader.getXmlDoc(AppProperties.getAppHome() + "DBConfig.xml");
        Element root = doc.getRootElement();
        for (Iterator<?> i = root.elementIterator("DataSources"); i.hasNext();) {
            Element e = (Element) i.next();
            @SuppressWarnings("unchecked")
            Iterator<Node> n = e.nodeIterator();
            while (n.hasNext()) {
                Node at = n.next();
                if (at.getName() != null) {
                    myList.add(at.getName());
                }
            }
        }
        return myList;
    } catch (Exception e) {
        throw new AppRuntimeException(e);
    } finally {
        if (doc != null) {
            doc.clearContent();
        }
    }
}

From source file:com.beyondb.geocoding.SkyMapAPI.java

/**
* ??????// w  w w  . j a  va  2 s.c  o  m
*???????
* @param address
* @param city
* @return
*/
public Map<String, Coordinate> getPlaces(String address, String city) {
    Map<String, Coordinate> map = null;
    try {

        URL url = new URL(requestURL);//webService?XML?
        String soapRequest = getRequestXML(
                city == null || city.isEmpty() ? ("" + address) : (city + " " + address));

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
        con.setRequestProperty("Content-Length", String.valueOf(soapRequest.length()));
        con.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
        // con.setRequestProperty("SOAPAction",_soap_action_str);

        con.setDoOutput(true);
        con.setConnectTimeout(3000);//3?,??ip???socket??????

        con.setRequestMethod("POST");
        con.setUseCaches(false);//post?

        OutputStream out = con.getOutputStream();

        out.write(soapRequest.getBytes());
        out.flush();
        out.close();
        int code = 0;

        StringBuilder content = new StringBuilder();
        code = con.getResponseCode(); //?????
        BufferedReader br;
        String line = "";
        if (code == HttpURLConnection.HTTP_OK) {

            br = new BufferedReader(new InputStreamReader(con.getInputStream()));

            while ((line = br.readLine()) != null) {
                content.append(line);

            }
            //? XML??
            //            <?xml version="1.0" encoding="UTF-8"?><wfs:FeatureCollection xmlns:topp="http://www.openplans.org/topp" xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd" service="WFS" outputFormat="gml" version="1.0">
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.394272,39.900472</gml:coordinates></gml:Point></Geometry><ogc:id>1003716709</ogc:id><ogc:name></ogc:name><ogc:tel>010-65243322</ogc:tel><ogc:addnamel>44?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>100102 100100 100000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.394504,39.9013</gml:coordinates></gml:Point></Geometry><ogc:id>1003546134</ogc:id><ogc:name></ogc:name><ogc:tel>010-65241304</ogc:tel><ogc:addnamel>37?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>100501 100500 100000 100105 100100 100000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.393824,39.900068</gml:coordinates></gml:Point></Geometry><ogc:id>1025053239</ogc:id><ogc:name>?</ogc:name><ogc:tel>010-65122265</ogc:tel><ogc:addnamel>44?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>010100 010000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.3938,39.899528</gml:coordinates></gml:Point></Geometry><ogc:id>1003552834</ogc:id><ogc:name>?</ogc:name><ogc:tel>010-65241042</ogc:tel><ogc:addnamel>44?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>010116 010100 010000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //   <gml:featureMember xmlns:iso19112="SI_Gazetteer">
            //            <iso19112:SI_Gazetteer>
            //               <Geometry>
            //                  <gml:Point srsName="-1">
            //                     <gml:coordinates>116.3938,39.899532</gml:coordinates>
            //                  </gml:Point>
            //               </Geometry>
            //               <ogc:id>1021636362</ogc:id>
            //               <ogc:name>?</ogc:name>
            //               <ogc:tel>010-65241042</ogc:tel>
            //               <ogc:addnamel>44?</ogc:addnamel>
            //               <ogc:admin>156110101</ogc:admin>
            //               <ogc:cls>010116 010100 010000</ogc:cls>
            //               <ogc:level/>
            //               <ogc:zip/>
            //            </iso19112:SI_Gazetteer>
            //   </gml:featureMember>
            //</wfs:FeatureCollection>
            Document doc = DocumentHelper.parseText(content.toString()); // XML
            Element rootElt = doc.getRootElement(); // ?FeatureCollection

            for (Iterator it = rootElt.elementIterator("featureMember"); it.hasNext();) {
                if (map == null) {
                    map = new HashMap<>();
                }
                Element featureMemberElement = (Element) it.next();
                Element gazetterEle = featureMemberElement.element("SI_Gazetteer");
                Element geoEle = gazetterEle.element("Geometry");
                Element pointEle = geoEle.element("Point");
                Element coordEle = pointEle.element("coordinates");
                String[] coordinate = coordEle.getTextTrim().split(",");
                Coordinate tmpCoordinate = new Coordinate();
                tmpCoordinate.Longitude = Double.parseDouble(coordinate[0]);
                tmpCoordinate.Latitude = Double.parseDouble(coordinate[1]);
                Element nameEle = gazetterEle.element("name");
                map.put(nameEle.getTextTrim(), tmpCoordinate);
            }

        } else {
            //?HTTP??HTTP_OK??
            InputStream is = con.getErrorStream(); //getErrorStreamXML??JDOM??
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                content.append(line);
            }
            Logger.getLogger(SkyMapAPI.class.getName()).log(Level.SEVERE, "??");
        }

    } catch (MalformedURLException e) {
        Logger.getLogger(SkyMapAPI.class.getName()).log(Level.SEVERE, null, e);
    } catch (IOException | DocumentException e) {
        Logger.getLogger(SkyMapAPI.class.getName()).log(Level.SEVERE, null, e);
    }
    return map;
}

From source file:com.beyondb.io.DBConfig.java

/**
 *??/*from  ww  w.  jav  a 2s .c  om*/
 * @param path
 * @return
 */
public static ArrayList<DataSource> readDBConfig1(String path) {
    ArrayList<DataSource> dslist = new ArrayList<>();

    try {

        SAXReader reader = new SAXReader();
        File file = new File(path);

        if (file.exists()) {
            Document doc = reader.read(file);

            Element datasource = doc.getRootElement();
            Iterator it = datasource.elementIterator(Node_database);
            while (it.hasNext()) {
                Element dbElement = (Element) it.next();
                String id = dbElement.attribute(Attribute_id).getValue();
                String username = dbElement.attribute(Attribute_username).getValue();
                String password = dbElement.attribute(Attribute_password).getValue();
                String virtualNode = dbElement.attribute(Attribute_virtualNode).getValue();
                String url = dbElement.elementText(Attribute_jdbcurl);

                DataSource ds = new BydDataSource(url, username, password);
                ds.setVirtualNode(virtualNode);
                ds.setID(id);
                dslist.add(ds);
            }

        }

    } catch (DocumentException ex) {

        Logger.getLogger(DBConfig.class.getName()).log(Level.SEVERE, "???", ex);
    }
    return dslist;
}

From source file:com.buddycloud.friendfinder.handler.MatchContactHandler.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from ww w  .j  a  v a 2s . com
public IQ handle(IQ iq) {
    Element queryElement = iq.getElement().element("query");
    Iterator<Element> itemIterator = queryElement.elementIterator("item");

    List<MatchedUser> reportedHashes = new LinkedList<MatchedUser>();

    while (itemIterator.hasNext()) {
        Element item = (Element) itemIterator.next();
        Attribute meAttr = item.attribute("me");
        Attribute hashAttr = item.attribute("item-hash");

        String hash = hashAttr.getValue();

        if (meAttr != null && meAttr.getValue().equals("true")) {
            HashUtils.reportHash(iq.getFrom().toBareJID(), hash, getDataSource());
        } else {
            String jid = HashUtils.retrieveJid(hash, getDataSource());
            if (jid != null) {
                reportedHashes.add(new MatchedUser(jid, hash));
            }
        }
    }

    return createResponse(iq, reportedHashes);
}

From source file:com.buddycloud.friendfinder.provider.Gmail.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/* w w w.  ja  va  2  s .c  om*/
public ContactProfile getProfile(String accessToken) throws Exception {
    boolean firstPage = true;
    ContactProfile contactProfile = null;
    int startIndex = 1;

    String myEmail = null;

    while (true) {
        StringBuilder urlBuilder = new StringBuilder(GOOGLE_FEED);
        urlBuilder.append("?start-index=").append(startIndex);
        urlBuilder.append("&max-results=").append(PAGE_SIZE);
        urlBuilder.append("&access_token=").append(accessToken);

        String contactsURL = urlBuilder.toString();
        Element xmlContacts = HttpUtils.consumeXML(contactsURL);

        if (firstPage) {
            myEmail = xmlContacts.element("id").getText();
            contactProfile = new ContactProfile(HashUtils.encodeSHA256(PROVIDER_NAME, myEmail));
        }

        if (xmlContacts.element("entry") == null) {
            break;
        }
        Iterator<Element> friendsElements = xmlContacts.elementIterator("entry");
        while (friendsElements.hasNext()) {
            Element element = (Element) friendsElements.next();
            Element emailEl = element.element("email");
            if (emailEl == null) {
                continue;
            }
            String friendEmail = emailEl.attributeValue("address");
            if (friendEmail.equals(myEmail)) {
                continue;
            }
            contactProfile.addFriendHash(HashUtils.encodeSHA256(PROVIDER_NAME, friendEmail));
        }

        startIndex += PAGE_SIZE;
        firstPage = false;
    }

    return contactProfile;
}

From source file:com.doculibre.constellio.izpack.PersistenceXMLUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void run(AbstractUIProcessHandler handler, String[] args) {
    if (args.length != 5) {
        System.out.println("persistence_mysqlPath defaultPersistencePath server login password");
        return;/*from  w w w. j  av a2  s.  com*/
    }

    String persistence_mysqlPath = args[0];
    String defaultPersistencePath = args[1];
    String server = args[2];
    String login = args[3];
    String password = args[4];

    Document xmlDocument;
    try {
        xmlDocument = new SAXReader().read(persistence_mysqlPath);
        Element root = xmlDocument.getRootElement();
        Iterator<Element> it = root.elementIterator("persistence-unit");
        if (!it.hasNext()) {
            System.out.println("Corrupt persistence file :" + persistence_mysqlPath);
            return;
        }
        it = it.next().elementIterator("properties");
        if (!it.hasNext()) {
            System.out.println("Corrupt persistence file :" + persistence_mysqlPath);
            return;
        }
        Element properties = it.next();
        for (it = properties.elementIterator("property"); it.hasNext();) {
            Element property = it.next();
            String id = property.attributeValue("name");
            if (id.equals(SERVER_ELEMENT_ID)) {
                Attribute att = property.attribute("value");
                att.setText(BEFORE_SERVER_NAME + server + AFTER_SERVER_NAME);
            } else {
                if (id.equals(LOGIN_ELEMENT_ID)) {
                    Attribute att = property.attribute("value");
                    att.setText(login);
                } else {
                    if (id.equals(PASSWORD_ELEMENT_ID)) {
                        Attribute att = property.attribute("value");
                        att.setText(password);
                    }
                }
            }

        }

        OutputFormat format = OutputFormat.createPrettyPrint();

        File xmlFile = new File(persistence_mysqlPath);
        XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format);

        writer2.write(xmlDocument);
        writer2.close();
        // copier au fichier de persistence par dfaut:
        xmlFile = new File(defaultPersistencePath);
        writer2 = new XMLWriter(new FileOutputStream(xmlFile), format);

        writer2.write(xmlDocument);
        writer2.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.doculibre.constellio.izpack.TomcatUtil.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void run(AbstractUIProcessHandler handler, String[] args) {
    if (args.length != 2) {
        System.out.println("serverPath port");
        return;/*from   ww  w .ja  v a2 s  . c o m*/
    }

    String serverPath = args[0];
    String port = args[1];
    if (port.equals("8080")) {
        // C'est celui par defaut => ne rien faire
        return;
    }

    Document xmlDocument;
    try {
        xmlDocument = new SAXReader().read(serverPath);
        Element root = xmlDocument.getRootElement();

        Iterator<Element> it = root.elementIterator("Service");
        if (!it.hasNext()) {
            System.out.println("Corrupt persistence file :" + serverPath);
            return;
        }
        Element connectors = it.next();
        for (it = connectors.elementIterator("Connector"); it.hasNext();) {
            Element connector = it.next();
            String id = connector.attributeValue("protocol");
            if (id.startsWith("HTTP")) {
                Attribute att = connector.attribute("port");
                att.setText(port);
                break;
            }
        }

        OutputFormat format = OutputFormat.createPrettyPrint();

        File xmlFile = new File(serverPath);
        XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format);

        writer2.write(xmlDocument);
        writer2.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}