Example usage for org.jdom2 Element getAttribute

List of usage examples for org.jdom2 Element getAttribute

Introduction

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

Prototype

public Attribute getAttribute(final String attname) 

Source Link

Document

This returns the attribute for this element with the given name and within no namespace, or null if no such attribute exists.

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  .java  2s  .co  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.cedarsoft.serialization.test.performance.XmlParserPerformance.java

License:Open Source License

public void benchJdom() {
    runBenchmark(new Runnable() {
        @Override/*from w  w w .ja  v  a 2 s. c om*/
        public void run() {
            try {
                for (int i = 0; i < SMALL; i++) {
                    Document doc = new SAXBuilder().build(new StringReader(CONTENT_SAMPLE));

                    Element fileTypeElement = doc.getRootElement();
                    Element extensionElement = fileTypeElement.getChild("extension");

                    Extension extension = new Extension(extensionElement.getAttributeValue("delimiter"),
                            extensionElement.getText(),
                            extensionElement.getAttribute("default").getBooleanValue());
                    FileType fileType = new FileType(fileTypeElement.getChildText("id"), extension,
                            fileTypeElement.getAttribute("dependent").getBooleanValue());

                    assertNotNull(fileType);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }, 4);
}

From source file:com.compomics.pladipus.core.control.updates.ProcessingBeanUpdater.java

/**
 * Adds a new class to the bean definition
 * @param fullyDefinedClassName the fully defined class name
 * @throws IllegalArgumentException//w ww . j av  a2s  . c o m
 * @throws IOException
 * @throws JDOMException
 */
public void addNewProcessingStep(String fullyDefinedClassName)
        throws IllegalArgumentException, IOException, JDOMException {
    String className = fullyDefinedClassName.substring(fullyDefinedClassName.lastIndexOf(".") + 1);

    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(beanXMLDefinitionFile);

    //check if the class is not already in there
    for (Element aBean : document.getRootElement().getChildren()) {
        if (aBean.getAttribute("class").getValue().equals(fullyDefinedClassName)) {
            throw new IllegalArgumentException(
                    "Class is already defined in the bean configuration for " + aBean.getAttributeValue("id"));
        } else if (aBean.getAttribute("id").getValue().equals(className)) {
            throw new IllegalArgumentException("Classname is already in use");
        }
    }

    Element newClassElement = new Element("bean").setAttribute("id", className)
            .setAttribute("class", fullyDefinedClassName).setAttribute("lazy-init", "true");
    document.getRootElement().addContent(newClassElement);
    XMLOutputter outputter = new XMLOutputter();
    try (StringWriter stringWriter = new StringWriter();
            FileWriter writer = new FileWriter(beanXMLDefinitionFile);) {
        outputter.output(document, stringWriter);
        String output = stringWriter.getBuffer().toString();
        //remove empty namespaces
        output = output.replace(" xmlns=\"\"", "");
        writer.append(output);
    }
}

From source file:com.forum.action.eder.TemaACT.java

private Hilo tema(int id, String url) {
    String megacadena = "";
    Hilo h = new Hilo();
    Document document = getDocument(url);
    Element root = document.getRootElement();
    Element temas = root.getChild("temas");
    List<Element> child = temas.getChildren();
    for (Element e : child) {
        try {//from   w w w . j  a v  a2s  . co m
            if (e.getAttribute("id").getIntValue() == id) {
                h.setTitulo(e.getChildText("titulo"));
                h.setDetalles(e.getChildText("detalles"));
                List<Element> e2 = e.getChildren("tags");
                for (int i = 0; i < e2.size(); i++) {
                    megacadena += e2.get(i).getValue() + ",";
                }

                h.setEtiquetas(megacadena);
                break;
            }
        } catch (DataConversionException ex) {

        }
    }
    return h;
}

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 {//  ww  w  . j a v  a 2  s .com
        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.XSDElementTypeComplex.java

License:Open Source License

/**
 * This method builds a complex type/*  w  w w.  j  a va  2 s. c  o  m*/
 *
 * @param    root - the complexType element that defines this element
 * @param    cache - a list of pre-defined XML types
 */

public boolean build(Element root, XSDCache cache, String parentName) {

    log.debug("" + indent + ": " + "Build representation of a ComplexType");

    /** get the complex types attributes **/

    id = root.getAttributeValue(XSDSchema.ID_ATT);
    name = root.getAttributeValue(XSDSchema.NAME_ATT);
    abstractAtt = root.getAttributeValue(XSDSchema.ABSTRACT_ATT);
    mixed = root.getAttributeValue(XSDSchema.MIXED_ATT);
    block = root.getAttributeValue(XSDSchema.BLOCK_ATT);
    finalAtt = root.getAttributeValue(XSDSchema.FINAL_ATT);

    log.debug("" + indent + ": ComplexType <" + name + ">");

    for (Element rootChild : root.getChildren()) {
        String elementName = rootChild.getName();

        if (elementName.equals(XSDSchema.ANNOTATION)) {
            annotation = rootChild.getTextTrim();

        } else if (elementName.equals(XSDSchema.SIMPLECONTENT)) {

        } else if (elementName.equals(XSDSchema.COMPLEXCONTENT)) {

            for (Element child : rootChild.getChildren()) {

                Attribute baseTypeAtt = child.getAttribute(XSDSchema.BASE_ATT);
                if (baseTypeAtt == null) {
                    throw new XmlSchemaException("No base attribute for element [" + elementName + "]");
                }

                XSDElementTypeComplex cachedObject = cache.getElementTypeComplex(baseTypeAtt.getValue());
                if (cachedObject != null) {
                    baseType = cachedObject;
                }

                processComplexTypeChildren(child, cache);
            }

        } else if (elementName.equals(XSDSchema.GROUP)) {
            if (elementGroup != null) {
                throw new XmlSchemaException("Cannot define a grouping element more than once");
            }
            elementGroup = new XSDElementGroup(indent);
            elementGroup.build(rootChild, cache, parentName);

        } else if (elementName.equals(XSDSchema.ALL)) {
            if (elementGroup != null) {
                throw new XmlSchemaException("Cannot define a grouping element more than once");
            }
            elementGroup = new XsdAll(indent);
            elementGroup.build(rootChild, cache, parentName);
        } else if (elementName.equals(XSDSchema.CHOICE)) {
            if (elementGroup != null) {
                throw new XmlSchemaException("Cannot define a grouping element more than once");
            }

            elementGroup = new XSDChoice(indent);
            elementGroup.build(rootChild, cache, parentName);
        } else if (elementName.equals(XSDSchema.SEQUENCE)) {

            if (elementGroup != null) {
                log.error("Cannot define a grouping element more than once");
                return (false);
            }

            elementGroup = new XSDSequence(indent);

            if (elementGroup.build(rootChild, cache, parentName) != true) {
                log.error("Error building a sequence object");
                return (false);
            }
        } else if (elementName.equals(XSDSchema.ATTRIBUTE)) {

            XSDAttribute attribute = new XSDAttribute();
            if (attribute.build(rootChild, cache, parentName) != true) {
                log.error("Error building an attribute object");
                return (false);
            }

            attributeList.add(attribute);
        } else if (elementName.equals(XSDSchema.ATTRIBUTEGROUP)) {

            XSDAttributeGroup group = new XSDAttributeGroup();

            if (group.build(rootChild, cache, parentName) != true) {
                log.error("Error building an attribute group object");
                return (false);
            }

            attributeList.addAll(group.getAllAttributes());

        } else {
            log.warn("" + indent + ": " + "Unexpected element <" + elementName + "> found and ignored");
        }

    } // end for all child elements of this <element> tag

    log.debug("" + indent + ": " + "ComplexType built");

    return (true);

}

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

License:Open Source License

/**
 * /*  w w  w  .ja va 2s .  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;
        }
    }
}

From source file:com.kixeye.scout.eureka.EurekaServiceInstanceDescriptor.java

License:Apache License

/**
 * Creates a descriptor from a parent and a raw element.
 * //from   www .  j av a  2  s  .  c o  m
 * @param parent
 * @param instanceElement
 */
protected EurekaServiceInstanceDescriptor(EurekaApplication parent, Element instanceElement) {
    this.parent = parent;

    this.app = instanceElement.getChildText("app");
    this.ipAddress = instanceElement.getChildText("ipAddr");
    this.hostname = instanceElement.getChildText("hostName");
    this.vipAddress = instanceElement.getChildText("vipAddress");

    int lastUpdatedTimestampRaw;
    try {
        lastUpdatedTimestampRaw = Integer.parseInt(instanceElement.getChildText("lastUpdatedTimestamp"));
    } catch (Exception e) {
        lastUpdatedTimestampRaw = -11;
    }

    this.lastUpdatedTimestamp = lastUpdatedTimestampRaw;

    int lastDirtyTimestampRaw;
    try {
        lastDirtyTimestampRaw = Integer.parseInt(instanceElement.getChildText("lastDirtyTimestamp"));
    } catch (Exception e) {
        lastDirtyTimestampRaw = -11;
    }

    this.lastDirtyTimestamp = lastDirtyTimestampRaw;

    Element port = instanceElement.getChild("port");

    if (port != null) {
        this.isPortEnabled = Boolean.valueOf(port.getAttributeValue("enabled", "true"));
        this.port = Integer.valueOf(port.getTextTrim());
    } else {
        this.isPortEnabled = false;
        this.port = -1;
    }

    Element securePort = instanceElement.getChild("securePort");

    if (securePort != null) {
        this.isSecurePortEnabled = Boolean.valueOf(securePort.getAttributeValue("enabled", "true"));
        this.securePort = Integer.valueOf(securePort.getTextTrim());
    } else {
        this.isSecurePortEnabled = false;
        this.securePort = -1;
    }

    Element statusElement = instanceElement.getChild("status");
    ServiceStatus status = null;

    if (statusElement != null) {
        switch (statusElement.getTextTrim()) {
        case "UP":
            status = ServiceStatus.UP;
            break;
        case "DOWN":
            status = ServiceStatus.DOWN;
            break;
        default:
            status = ServiceStatus.UNKNOWN;
        }
    }

    this.status = status;

    Element overridenStatusElement = instanceElement.getChild("overriddenstatus");
    ServiceStatus overridenStatus = null;

    if (overridenStatusElement != null) {
        switch (overridenStatusElement.getTextTrim()) {
        case "UP":
            overridenStatus = ServiceStatus.UP;
            break;
        case "DOWN":
            overridenStatus = ServiceStatus.DOWN;
            break;
        default:
            overridenStatus = ServiceStatus.UNKNOWN;
        }
    }

    this.overridenStatus = overridenStatus;

    Element metadata = instanceElement.getChild("metadata");

    if (metadata != null) {
        for (Element element : metadata.getChildren()) {
            this.metadata.put(element.getName(), element.getText());
        }
    }

    Element dataCenterInfo = instanceElement.getChild("dataCenterInfo");

    if (dataCenterInfo != null) {
        Attribute dataCenterInfoClass = instanceElement.getAttribute("class");

        if (dataCenterInfoClass != null && dataCenterInfoClass.getValue() != null) {
            switch (dataCenterInfoClass.getValue()) {
            case EurekaServiceAmazonDataCenterInfo.DATA_CENTER_INFO_CLASS:
                this.dataCenterInfo = new EurekaServiceAmazonDataCenterInfo(this, dataCenterInfo);
                break;
            default:
                this.dataCenterInfo = null;
            }
        } else {
            this.dataCenterInfo = null;
        }
    } else {
        this.dataCenterInfo = null;
    }
}

From source file:com.locutus.outils.graphes.ConvertisseurXGMLGraphe.java

License:Open Source License

/**
 * @param fl//from   w ww .  j ava 2s . co m
 * @throws GraphConversionException
 */
private DiGraph<String> produceDiGraphByGXML(File fl) throws GraphConversionException {

    DiGraph<String> dg = new DiGraph<String>();
    // Racine du document
    Element racine = document.getRootElement();

    // Itrateur des lments du premier niveau
    Iterator<Element> it = racine.getChildren().iterator();

    // Element correspondant au graphe
    Element graph = null;
    while (it.hasNext() && graph == null) {

        Element local = it.next();

        // On rcupre la section Graph
        if (local.getAttribute("name") != null && local.getAttribute("name").getValue().equals("graph")) {

            // On a trouv une section graphe
            graph = local;
        }
    }

    if (graph == null) {
        // Erreur car le fichier ne possde pas de section Graph au premier
        // niveaus
        throw new GraphConversionException("Le fichier transmis n'est pas un graphe utilisable.");
    } else {
        this.traduireGraphe(dg, graph);
        if (idNode.size() > 0) {
            makeEdgesAndAdd(dg);

        } else {
            throw new GraphConversionException("Le fichier ne contient aucun noeud.");
        }
    }

    return dg;
}

From source file:com.locutus.outils.graphes.ConvertisseurXGMLGraphe.java

License:Open Source License

/**
 * /*from   w  w w  .j  av  a  2  s.co  m*/
 * @param graph
 * @throws GraphConversionException
 */
private void traduireGraphe(DiGraph<String> dgc, Element graph) throws GraphConversionException {
    Iterator<Element> elemGraphIt = graph.getChildren().iterator();

    while (elemGraphIt.hasNext()) {

        // On va chercher dans cette catgorie les Nodes et les Edges
        Element local2 = elemGraphIt.next();

        if (local2.getAttribute("name") != null && local2.getAttribute("name").getValue().equals("node")) {

            createNodeAndAdd(dgc, local2);

        } else if (local2.getAttribute("name") != null
                && local2.getAttribute("name").getValue().equals("edge")) {

            createEdge(dgc, local2);

        }
    }
}