Example usage for org.jdom2 Element getChildren

List of usage examples for org.jdom2 Element getChildren

Introduction

In this page you can find the example usage for org.jdom2 Element getChildren.

Prototype

public List<Element> getChildren(final String cname) 

Source Link

Document

This returns a List of all the child elements nested directly (one level deep) within this element with the given local name and belonging to no namespace, returned as Element objects.

Usage

From source file:com.cats.version.VersionCfgParseAndSave.java

License:Apache License

public List<VersionInfo> getVersionInfo(String fullPath) {
    SAXBuilder builder = new SAXBuilder();
    List<VersionInfo> infos = new ArrayList<VersionInfo>();
    try {//from   ww  w  . j ava  2s.  c o  m
        Document doc = builder.build(new File(fullPath));
        Element root = doc.getRootElement();
        List<Element> softEles = root.getChildren("software");
        for (Element softEle : softEles) {
            String appName = softEle.getAttribute("name").getValue();
            String versionCode = softEle.getChildText("latest-version-code");
            String versionName = softEle.getChildText("latest-version");
            String versionPath = softEle.getChildText("latest-version-abspath");
            String startupName = softEle.getChildText("latest-version-startup");

            Element detailEles = softEle.getChild("latest-version-detail");
            List<Element> detailItemEles = detailEles.getChildren("item");
            List<VersionInfoDetail> details = new ArrayList<VersionInfoDetail>();
            for (Element detailItem : detailItemEles) {
                String title = detailItem.getAttributeValue("name");
                List<Element> detailEleList = detailItem.getChildren("detail");
                List<String> detailList = new ArrayList<String>();
                for (Element detailEle : detailEleList) {
                    String strDetail = detailEle.getText();
                    detailList.add(strDetail);
                }
                details.add(new VersionInfoDetail(title, detailList));
            }

            Element ignoreEles = softEle.getChild("ignore-files");
            List<String> ignoreFiles = new ArrayList<String>();
            if (ignoreEles != null) {
                List<Element> ignoreItems = ignoreEles.getChildren("item");
                for (Element ignoreItem : ignoreItems) {
                    ignoreFiles.add(ignoreItem.getText());
                }
            }

            VersionInfo versionInfo = new VersionInfo();
            versionInfo.setAppName(appName);
            versionInfo.setVersion(versionName);
            versionInfo.setStartupName(startupName);
            versionInfo.setVersionCode(Integer.parseInt(versionCode));
            versionInfo.setPath(versionPath);
            versionInfo.setDetails(details);
            versionInfo.setIgnoreFiles(ignoreFiles);
            infos.add(versionInfo);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return infos;
}

From source file:com.cisco.oss.foundation.logging.FoundationLogger.java

License:Apache License

/**
  * The sniffing Loggers are some special Loggers, whose level will be set to TRACE forcedly.
 * @param logger// ww  w.  j  ava  2s.c  o  m
  */
private static void updateSniffingLoggersLevel(Logger logger) {

    InputStream settingIS = FoundationLogger.class.getResourceAsStream("/sniffingLogger.xml");
    if (settingIS == null) {
        logger.debug("file sniffingLogger.xml not found in classpath");
    } else {
        try {
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(settingIS);
            settingIS.close();
            Element rootElement = document.getRootElement();
            List<Element> sniffingloggers = rootElement.getChildren("sniffingLogger");
            for (Element sniffinglogger : sniffingloggers) {
                String loggerName = sniffinglogger.getAttributeValue("id");
                Logger.getLogger(loggerName).setLevel(Level.TRACE);
            }
        } catch (Exception e) {
            logger.error("cannot load the sniffing logger configuration file. error is: " + e, e);
            throw new IllegalArgumentException("Problem parsing sniffingLogger.xml", e);
        }
    }

}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

License:Apache License

private static void udpateMarkerStructuredLogOverrideMap() {

    InputStream messageFormatIS = AbstractFoundationLoggingMarker.class
            .getResourceAsStream("/messageFormat.xml");
    if (messageFormatIS == null) {
        LOGGER.debug("file messageformat.xml not found in classpath");
    } else {/*from   w  ww . j a  va 2s .  c o  m*/
        try {
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(messageFormatIS);

            messageFormatIS.close();

            Element rootElement = document.getRootElement();
            List<Element> markers = rootElement.getChildren("marker");
            for (Element marker : markers) {
                AbstractFoundationLoggingMarker.markersXmlMap.put(marker.getAttributeValue("id"), marker);
            }

        } catch (Exception e) {
            LOGGER.error("cannot load the structured log override file. error is: " + e, e);
            throw new IllegalArgumentException("Problem parsing messageformat.xml", e);
        }
    }

}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

License:Apache License

private static boolean buildFromXml(Element markerElement, StringBuilder builder) {

    Element defaultAppender = markerElement.getChild("defaultAppender");

    List<Element> appenders = markerElement.getChildren("appender");
    String markerId = markerElement.getAttributeValue("id");

    if (appenders != null) {
        for (Element appender : appenders) {
            String appenderId = appender.getAttributeValue("id");
            if (appenderId == null) {
                LOGGER.error("the appender element must have an id poiting to a valid appender name");
            } else {
                buildFromAppenderElement(markerId, appenderId, appender, builder, false, appenderId);
            }//from   w  w  w .  j  av a  2s  .  c o m
        }
    }

    if (defaultAppender == null) {

        LOGGER.error("The marker element: '{}' must contain a 'defaultAppender' element", markerId);
        builder.append("return null;");

    } else {

        buildFromAppenderElement(markerId, "defaultAppender", defaultAppender, builder, true, "DEFAULT");
    }

    return true;
}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

License:Apache License

private static void buildFromAppenderElement(String markerId, String appenderId, Element appenderElement,
        StringBuilder builder, boolean isDefault, String appenderName) {

    if (!isDefault) {
        builder.append("if (\"").append(appenderName).append("\".equals(").append("appenderName)){\n");
    }// ww  w. j  a v  a2 s.co  m

    Element criteriaElement = appenderElement.getChild("criteria");

    if (criteriaElement != null) {

        List<Element> criterionList = criteriaElement.getChildren("criterion");

        if (criterionList != null) {

            for (Element criterionElement : criterionList) {

                String result = criterionElement.getAttributeValue("format");
                List<Element> fieldList = criterionElement.getChildren("field");

                if (fieldList != null) {

                    for (int i = 0; i < fieldList.size(); i++) {
                        Element fieldElement = fieldList.get(i);

                        String key = fieldElement.getAttributeValue("name");
                        String value = fieldElement.getAttributeValue("equals");

                        String getterField = "marker.get" + WordUtils.capitalize(key) + "()";

                        if (i == 0) {
                            builder.append("if (").append(getterField).append(" != null && \"").append(value)
                                    .append("\".equals(").append(getterField).append(".toString())");
                        } else {
                            builder.append(" && ").append(getterField).append(" != null && \"").append(value)
                                    .append("\".equals(").append(getterField).append(".toString())");
                        }

                    }

                    builder.append(")\n\treturn \"").append(result).append("\";\n");
                }

            }
        }
    } else {
        LOGGER.info("The marker element '{}' does not contain a 'criteria' element for appender: '{}'",
                markerId, appenderId);
    }

    String defaultFormat = appenderElement.getAttributeValue("defaultFormat");
    if (defaultFormat == null) {
        LOGGER.error("The marker element: '{}' must contain a 'defaultFormat' element", markerId);
    }
    builder.append("return \"" + defaultFormat + "\";");

    if (!isDefault) {
        builder.append("\n}\n");
    }
}

From source file:com.codeexcursion.ConversionManager.java

public List<Element> getItems() {
    List<Element> items = null;

    Element channel = rss.getChild(CHANNEL);
    if (channel == null) {
        System.out.println("Failed to retrieve channel node.");
    } else {// w  w  w. j a  v a  2  s  .com
        items = channel.getChildren("item");
    }
    return items;
}

From source file:com.codeexcursion.PathCommon.java

public void setup() {
    testFile = new File(testFilePath);
    if (!testFile.isFile()) {
        fail("Unable to open file = " + testFilePath);
    }//  w  w  w .  j  a  v  a 2s  . c o m
    document = getDocument(testFile);

    rss = document.getRootElement();

    Namespace wordpressNamespace = rss.getNamespace("wp");
    Assert.assertNotNull("Wordpress namespace is null.", wordpressNamespace);
    Assert.assertEquals("Wordpress namespace is null.", "wp", wordpressNamespace.getPrefix());

    Namespace contentNamespace = rss.getNamespace("content");
    Assert.assertNotNull("Content namespace is null.", contentNamespace);
    Assert.assertEquals("Content namespace is null.", "content", contentNamespace.getPrefix());

    List<Element> channels = rss.getChildren(ConversionManager.CHANNEL);
    Assert.assertNotNull("List of channels was null", channels);

    Element channel = channels.get(0);
    Assert.assertNotNull("Channel was null", channel);

    List<Element> listOfItems = channel.getChildren(ConversionManager.ITEM);

    Optional<Element> firstItem = listOfItems.stream().findFirst();
    Assert.assertTrue("Item element is null!", firstItem.isPresent());
    attachmentItem = new Item(firstItem.get(), wordpressNamespace, contentNamespace);
    /*
        System.out.println("xxxxxxxxxxxxxxxxx");
    //    System.out.println(firstItem.get().getChildText(ItemElementChildTagNames.POST_TYPE, Namespace.getNamespace(ItemElementChildTagNames.WORDPRESS_NAMESPACE)));
        System.out.println(firstItem.get().getName());
        System.out.println(firstItem.get().getChildText("post_id", wordpressNamespace));
    //    firstItem.get().getChildren().stream().forEach(child -> System.out.println(child.getName()));
        //System.out.println(firstItem.get().getChild("post_id", wordpressNamespace));
        System.out.println("xxxxxxxxxxxxxxxxx");
      */
    Optional<Element> postElementItem = listOfItems.stream().filter(
            item -> "246".equals(item.getChildText(ItemElementChildTagNames.DOCUMENT_ID, wordpressNamespace)))
            .findFirst();

    Assert.assertTrue("Post element item element is null!", postElementItem.isPresent());
    postItem = new Item(postElementItem.get(), wordpressNamespace, contentNamespace);
}

From source file:com.gmapp.comun.LeerPathFromXML.java

public String cargarXml(String tipoPathBuscado) {
    //System.out.println("Buscando path para \"" + tipoPathBuscado + "\" ...");
    String pathBuscado = "";
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    InputStream xmlFile = getClass().getResourceAsStream("/xml/pathFiles.xml");

    try {//from ww w  .  j a  va2s.c  o  m

        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);

        //Se obtiene la raiz 'Sistemas'
        Element rootNode = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'Sistemas'
        List list = rootNode.getChildren("Sistema");

        //Se recorre la lista de hijos de 'Sistemas'
        for (int i = 0; i < list.size(); i++) {
            //Se obtiene el elemento 'Sistema'
            Element sistema = (Element) list.get(i);

            //Se obtiene el atributo 'nombre' que esta en el tag 'Sistema'
            String nombreSistema = sistema.getAttributeValue("nombre");
            if (SysOper.contains(nombreSistema)) {
                //System.out.println("Sistema: " + nombreSistema );
                //Se obtiene la lista de hijos del tag 'Sistema~nombre '
                List lista_registros = sistema.getChildren();
                //Se recorre la lista de campos
                for (int j = 0; j < lista_registros.size(); j++) {
                    //Se obtiene el elemento 'campo'
                    Element campo = (Element) lista_registros.get(j);
                    //Se obtienen los valores que estan entre los tags '<campo></campo>'
                    //Se obtiene el valor que esta entre los tags '<nombre></nombre>'
                    String nombre = campo.getChildTextTrim("nombrePath");
                    if (nombre.equals(tipoPathBuscado)) {
                        //Se obtiene el valor que esta entre los tags '<valor></valor>'
                        pathBuscado = campo.getChildTextTrim("path");

                        //System.out.println( "\t"+nombre+"\t"+pathBuscado);
                    }
                }
            }
        }
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }

    return pathBuscado;
}

From source file:com.googlecode.mipnp.extension.rhythmbox.RhythmboxExtension.java

License:Open Source License

private List<MusicTrack> getMusicTracks() {
    List<MusicTrack> tracks = new ArrayList<MusicTrack>();
    Map<String, MusicAlbum> albums = new HashMap<String, MusicAlbum>();

    try {//from w w w.j  av a  2 s. c o  m
        Document document = builder.build(db);
        Element rootNode = document.getRootElement();
        List<Element> list = rootNode.getChildren("entry");

        for (Element entry : list) {
            if (entry.getAttribute("type").getValue().equals("song")) {
                try {
                    MusicTrack track = new MusicTrack();
                    track.setTitle(entry.getChildText("title"));
                    track.setArtist(entry.getChildText("artist"));
                    track.setGenre(entry.getChildText("genre"));
                    track.setDuration(Integer.parseInt(entry.getChildText("duration")) * 1000);
                    track.setTrackNumber(Integer.parseInt(entry.getChildText("track-number")));
                    track.setBitRate(Integer.parseInt(entry.getChildText("bitrate")));
                    track.setFile(new File(new URI(entry.getChildText("location"))));

                    String strAlbum = entry.getChildText("album");
                    MusicAlbum album = albums.get(strAlbum);
                    if (album == null) {
                        album = new MusicAlbum(strAlbum, entry.getChildText("album-artist"));
                        albums.put(strAlbum, album);
                    }
                    track.setAlbum(album);

                    tracks.add(track);
                } catch (NumberFormatException ex) {
                    System.err.println("ERROR: " + ex.getMessage());
                } catch (URISyntaxException ex) {
                    System.err.println("ERROR: " + ex.getMessage());
                }
            }
        }
    } catch (JDOMException ex) {
        System.err.println("ERROR: " + ex.getMessage());
    } catch (IOException ex) {
        System.err.println("ERROR: " + ex.getMessage());
    }
    return tracks;
}

From source file:com.init.octo.schema.XSDSchema.java

License:Open Source License

/**
 * /*from w  ww  .j  ava2  s . co  m*/
 * @param elementSpec
 * @param schemaElement
 * @param element
 */
private void addMandatoryElementToDocument(XSDElement schemaElement, String elementSpec, Element element) {
    String[] eSpec = elementSpec.split("\\.");

    if (eSpec[0].equals(element.getName()) == false) {
        log.warn("The parent element [" + element.getName() + "] does not match the element spec ["
                + elementSpec + "]");
        return;
    }

    int idx = 1;
    while (idx < eSpec.length) {

        if (isAttribute(eSpec[idx])) {
            String attname = eSpec[idx].substring(1, eSpec[idx].length());
            Attribute att = element.getAttribute(attname);

            if (att == null) {
                /** Mandatory attribute does not exist so add it.. **/
                element.setAttribute(attname, schemaElement.getDefaultAttValue(attname));
            }

            return;
        }

        StringBuffer tmp = new StringBuffer();
        for (int i = idx; i < eSpec.length; i++) {
            if (tmp.length() != 0) {
                tmp.append(".");
            }
            tmp.append(eSpec[i]);
        }

        Iterator<?> it = element.getChildren(eSpec[idx]).iterator();

        /**
         * If the document does not have the specified child element and we
         * are at the end
         **/
        /**
         * of the chain then this is a mandatory element that needs to be
         * added...
         **/
        if (it.hasNext() == false && idx == eSpec.length - 1) {

            Element newel = new Element(eSpec[idx]);

            addElementToDocument(schemaElement, element, newel);

            return;
        }

        /**
         * If the document does not have the specified child element and
         * that element is
         **/
        /** just part of the chain, then no need to carry on.. **/
        if (it.hasNext() == false) {
            return;
        }

        /**
         * If the document does have the specified child element and we are
         * at the end of the chain then every thing is ok, so just return **/
        if (idx == eSpec.length - 1) {
            return;
        } else {
            /** We have to follow every one of the elements down the tree.. **/
            while (it.hasNext()) {
                addMandatoryElementToDocument(schemaElement, tmp.toString(), (Element) it.next());
            }
            return;
        }
    }
}