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, final Namespace ns) 

Source Link

Document

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

Usage

From source file:ca.nrc.cadc.caom2.xml.ObservationReader.java

License:Open Source License

/**
 * Construct an Observation from a Reader.
 *
 * @param reader/*from   w  w w. jav a2 s . c o m*/
 *            A Reader.
 * @return An Observation.
 * @throws ObservationParsingException
 *             if there is an error parsing the XML.
 */
public Observation read(Reader reader) throws ObservationParsingException, IOException {
    if (reader == null) {
        throw new IllegalArgumentException("reader must not be null");
    }

    init();

    Document document;
    try {
        document = XmlUtil.buildDocument(reader, schemaMap);
    } catch (JDOMException jde) {
        String error = "XML failed schema validation: " + jde.getMessage();
        throw new ObservationParsingException(error, jde);
    }

    // Root element and namespace of the Document
    Element root = document.getRootElement();
    Namespace namespace = root.getNamespace();
    log.debug("obs namespace uri: " + namespace.getURI());
    log.debug("obs namespace prefix: " + namespace.getPrefix());

    ReadContext rc = new ReadContext();
    if (XmlConstants.CAOM2_0_NAMESPACE.equals(namespace.getURI())) {
        rc.docVersion = 20;
    } else if (XmlConstants.CAOM2_1_NAMESPACE.equals(namespace.getURI())) {
        rc.docVersion = 21;
    } else if (XmlConstants.CAOM2_2_NAMESPACE.equals(namespace.getURI())) {
        rc.docVersion = 22;
    }

    // Simple or Composite
    Attribute type = root.getAttribute("type", xsiNamespace);
    String tval = type.getValue();

    String collection = getChildText("collection", root, namespace, false);
    String observationID = getChildText("observationID", root, namespace, false);

    // Algorithm.
    Algorithm algorithm = getAlgorithm(root, namespace, rc);

    // Create the Observation.
    Observation obs;
    String simple = namespace.getPrefix() + ":" + SimpleObservation.class.getSimpleName();
    String comp = namespace.getPrefix() + ":" + CompositeObservation.class.getSimpleName();
    if (simple.equals(tval)) {
        obs = new SimpleObservation(collection, observationID);
        obs.setAlgorithm(algorithm);
    } else if (comp.equals(tval)) {
        obs = new CompositeObservation(collection, observationID, algorithm);
    } else {
        throw new ObservationParsingException("unexpected observation type: " + tval);
    }

    // Observation children.
    String intent = getChildText("intent", root, namespace, false);
    if (intent != null) {
        obs.intent = ObservationIntentType.toValue(intent);
    }
    obs.type = getChildText("type", root, namespace, false);

    obs.metaRelease = getChildTextAsDate("metaRelease", root, namespace, false, rc.dateFormat);
    obs.sequenceNumber = getChildTextAsInteger("sequenceNumber", root, namespace, false);
    obs.proposal = getProposal(root, namespace, rc);
    obs.target = getTarget(root, namespace, rc);
    obs.targetPosition = getTargetPosition(root, namespace, rc);
    obs.requirements = getRequirements(root, namespace, rc);
    obs.telescope = getTelescope(root, namespace, rc);
    obs.instrument = getInstrument(root, namespace, rc);
    obs.environment = getEnvironment(root, namespace, rc);

    addPlanes(obs.getPlanes(), root, namespace, rc);

    if (obs instanceof CompositeObservation) {
        addMembers(((CompositeObservation) obs).getMembers(), root, namespace, rc);
    }

    assignEntityAttributes(root, obs, rc);

    return obs;
}

From source file:ca.nrc.cadc.caom2.xml.ObservationReader.java

License:Open Source License

private void assignEntityAttributes(Element e, CaomEntity ce, ReadContext rc)
        throws ObservationParsingException {
    Attribute aid = e.getAttribute("id", e.getNamespace());
    Attribute alastModified = e.getAttribute("lastModified", e.getNamespace());
    Attribute amaxLastModified = e.getAttribute("maxLastModified", e.getNamespace());
    Attribute mcs = e.getAttribute("metaChecksum", e.getNamespace());
    Attribute acc = e.getAttribute("accMetaChecksum", e.getNamespace());
    try {/*  www .j  ava  2s.c  o m*/
        UUID uuid;
        if (rc.docVersion == 20) {
            Long id = new Long(aid.getLongValue());
            uuid = new UUID(0L, id);
        } else {
            uuid = UUID.fromString(aid.getValue());
        }

        CaomUtil.assignID(ce, uuid);
        if (alastModified != null) {
            Date lastModified = rc.parseTimestamp(alastModified.getValue());
            CaomUtil.assignLastModified(ce, lastModified, "lastModified");
        }

        if (rc.docVersion >= 23) {
            if (amaxLastModified != null) {
                Date lastModified = rc.parseTimestamp(amaxLastModified.getValue());
                CaomUtil.assignLastModified(ce, lastModified, "maxLastModified");
            }
            if (mcs != null) {
                URI metaCS = new URI(mcs.getValue());
                CaomUtil.assignMetaChecksum(ce, metaCS, "metaChecksum");
            }
            if (acc != null) {
                URI accCS = new URI(acc.getValue());
                CaomUtil.assignMetaChecksum(ce, accCS, "accMetaChecksum");
            }
        }
    } catch (DataConversionException ex) {
        throw new ObservationParsingException("invalid id: " + aid.getValue());
    } catch (ParseException ex) {
        throw new ObservationParsingException("invalid lastModified: " + alastModified.getValue());
    } catch (URISyntaxException ex) {
        throw new ObservationParsingException("invalid checksum uri: " + aid.getValue());
    }
}

From source file:ca.nrc.cadc.caom2.xml.ObservationReader.java

License:Open Source License

protected Position getPosition(Element parent, Namespace namespace, ReadContext rc)
        throws ObservationParsingException {
    Element element = getChildElement("position", parent, namespace, false);
    if (element == null) {
        return null;
    }// w  w w . j av  a 2 s. c o m

    Position pos = new Position();
    Element cur = getChildElement("bounds", element, namespace, false);
    if (cur != null) {
        if (rc.docVersion < 23) {
            throw new UnsupportedOperationException(
                    "cannot convert version " + rc.docVersion + " polygon to current version");
        }
        Attribute type = cur.getAttribute("type", xsiNamespace);
        String tval = type.getValue();
        String circleType = namespace.getPrefix() + ":" + Circle.class.getSimpleName();
        String polyType = namespace.getPrefix() + ":" + Polygon.class.getSimpleName();
        if (polyType.equals(tval)) {
            List<Point> points = new ArrayList<Point>();
            Element pes = cur.getChild("points", namespace);
            for (Element pe : pes.getChildren()) { // only vertex
                double cval1 = getChildTextAsDouble("cval1", pe, namespace, true);
                double cval2 = getChildTextAsDouble("cval2", pe, namespace, true);
                points.add(new Point(cval1, cval2));
            }
            Element se = cur.getChild("samples", namespace);
            MultiPolygon poly = new MultiPolygon();
            Element ves = se.getChild("vertices", namespace);
            for (Element ve : ves.getChildren()) { // only vertex
                double cval1 = getChildTextAsDouble("cval1", ve, namespace, true);
                double cval2 = getChildTextAsDouble("cval2", ve, namespace, true);
                int sv = getChildTextAsInteger("type", ve, namespace, true);
                poly.getVertices().add(new Vertex(cval1, cval2, SegmentType.toValue(sv)));
            }
            pos.bounds = new Polygon(points, poly);
        } else if (circleType.equals(tval)) {
            Element ce = cur.getChild("center", namespace);
            double cval1 = getChildTextAsDouble("cval1", ce, namespace, true);
            double cval2 = getChildTextAsDouble("cval2", ce, namespace, true);
            Point c = new Point(cval1, cval2);
            double r = getChildTextAsDouble("radius", cur, namespace, true);
            pos.bounds = new Circle(c, r);
        } else {
            throw new UnsupportedOperationException("unsupported shape: " + tval);
        }
    }

    cur = getChildElement("dimension", element, namespace, false);
    if (cur != null) {
        // Attribute type = cur.getAttribute("type", xsiNamespace);
        // String tval = type.getValue();
        // String extype = namespace.getPrefix() + ":" +
        // Dimension2D.class.getSimpleName();
        // if ( extype.equals(tval) )
        // {
        long naxis1 = getChildTextAsLong("naxis1", cur, namespace, true);
        long naxis2 = getChildTextAsLong("naxis2", cur, namespace, true);
        pos.dimension = new Dimension2D(naxis1, naxis2);
        // }
        // else
        // throw new ObservationParsingException("unsupported dimension
        // type: " + tval);
    }

    pos.resolution = getChildTextAsDouble("resolution", element, namespace, false);
    pos.sampleSize = getChildTextAsDouble("sampleSize", element, namespace, false);
    pos.timeDependent = getChildTextAsBoolean("timeDependent", element, namespace, false);

    return pos;
}

From source file:ca.nrc.cadc.uws.JobListReader.java

License:Open Source License

private List<JobRef> parseJobList(Document doc) throws ParseException, DataConversionException {
    Element root = doc.getRootElement();
    List<Element> children = root.getChildren();
    Iterator<Element> childIterator = children.iterator();
    List<JobRef> jobs = new ArrayList<JobRef>();
    Element next = null;//  w  w w.  j  a v  a2 s  .co m
    JobRef jobRef = null;
    ExecutionPhase executionPhase = null;
    Date creationTime = null;
    Attribute nil = null;
    String runID = null;
    String ownerID = null;
    while (childIterator.hasNext()) {
        next = childIterator.next();
        String jobID = next.getAttributeValue("id");

        Element phaseElement = next.getChild(JobAttribute.EXECUTION_PHASE.getAttributeName(), UWS.NS);
        String phase = phaseElement.getValue();
        executionPhase = ExecutionPhase.valueOf(phase);

        Element creationTimeElement = next.getChild(JobAttribute.CREATION_TIME.getAttributeName(), UWS.NS);
        String time = creationTimeElement.getValue();
        creationTime = dateFormat.parse(time);

        Element runIDElement = next.getChild(JobAttribute.RUN_ID.getAttributeName(), UWS.NS);
        nil = runIDElement.getAttribute("nil", UWS.XSI_NS);
        if (nil != null && nil.getBooleanValue())
            runID = null;
        else
            runID = runIDElement.getTextTrim();

        Element ownerIDElement = next.getChild(JobAttribute.OWNER_ID.getAttributeName(), UWS.NS);
        ownerID = ownerIDElement.getTextTrim();

        jobRef = new JobRef(jobID, executionPhase, creationTime, runID, ownerID);
        jobs.add(jobRef);
    }

    return jobs;
}

From source file:ca.nrc.cadc.uws.JobReader.java

License:Open Source License

private String parseStringContent(Element e) throws DataConversionException {
    if (e == null)
        return null;
    Attribute nil = e.getAttribute("nil", UWS.XSI_NS);
    if (nil != null && nil.getBooleanValue())
        return null;
    return e.getTextTrim();
}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

private void XMLtoJavaParser() {

    // Creamos el builder basado en SAX  
    SAXBuilder builder = new SAXBuilder();

    try {/*from ww w  .jav a2  s .  co m*/

        String nombreMetodo = null;
        List<String> atributos = new ArrayList<String>();
        String tipoRetorno = null;
        String nombreArchivo = null;
        String exportValue = "";
        String codigoFuente = "";
        HashMap<String, String> tipos = new HashMap<String, String>();

        // Construimos el arbol DOM a partir del fichero xml  
        Document doc = builder.build(new FileInputStream(ruta + "VBParser\\ejemplosKDM\\archivo.kdm"));
        //Document doc = builder.build(new FileInputStream("E:\\WorkspaceParser\\VBParser\\ejemplosKDM\\archivo.kdm"));    

        Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");

        XPathExpression<Element> xpath = XPathFactory.instance().compile("//codeElement", Filters.element());

        List<Element> elements = xpath.evaluate(doc);

        for (Element emt : elements) {

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:CompilationUnit") == 0) {

                nombreArchivo = emt.getAttributeValue("name").substring(0,
                        emt.getAttributeValue("name").indexOf('.'));

            }

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:LanguageUnit") == 0) {

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    tipos.put(hijo.getAttributeValue("id", xmi), hijo.getAttributeValue("name"));

                }

            }
        }

        FileOutputStream fout;

        fout = new FileOutputStream(ruta + "VBParser\\src\\cager\\parser\\test\\" + nombreArchivo + ".java");
        //fout = new FileOutputStream("E:\\WorkspaceParser\\VBParser\\src\\cager\\parser\\test\\"+nombreArchivo+".java");           
        // get the content in bytes
        byte[] contentInBytes = null;

        contentInBytes = ("package cager.parser.test;\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        contentInBytes = ("public class " + nombreArchivo + "{\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        for (Element emt : elements) {
            // System.out.println("XPath has result: " + emt.getName()+" "+emt.getAttribute("type",xmi));
            if (emt.getAttribute("type", xmi).getValue().compareTo("code:MethodUnit") == 0) {

                nombreMetodo = emt.getAttribute("name").getValue();

                if (emt.getAttribute("export") != null)
                    exportValue = emt.getAttribute("export").getValue();

                atributos = new ArrayList<String>();

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    if (hijo.getAttribute("type", xmi) != null) {

                        if (hijo.getAttribute("type", xmi).getValue().compareTo("code:Signature") == 0) {

                            List<Element> parametros = hijo.getChildren();

                            for (Element parametro : parametros) {

                                if (parametro.getAttribute("kind") == null
                                        || parametro.getAttribute("kind").getValue().compareTo("return") != 0) {
                                    atributos.add(tipos.get(parametro.getAttribute("type").getValue()) + " "
                                            + parametro.getAttributeValue("name"));
                                } else {
                                    tipoRetorno = tipos.get(parametro.getAttribute("type").getValue());
                                }

                            }

                        }
                    } else if (hijo.getAttribute("snippet") != null) {

                        codigoFuente = hijo.getAttribute("snippet").getValue();

                    }

                }

                //System.out.println("MethodUnit!! " + emt.getName()+" "+emt.getAttribute("type",xmi)+" "+emt.getAttribute("name").getValue());
                //System.out.println(emt.getAttribute("name").getValue());

                if (tipoRetorno.compareTo("Void") == 0) {
                    tipoRetorno = "void";
                }

                contentInBytes = ("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (")
                        .getBytes();

                fout.write(contentInBytes);
                fout.flush();
                int n = 0;
                for (String parametro : atributos) {

                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        contentInBytes = (" " + parametro + ",").getBytes();
                    } else {
                        contentInBytes = (" " + parametro).getBytes();
                    }

                    fout.write(contentInBytes);
                    fout.flush();
                    n++;
                }

                contentInBytes = (" ) {\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\n/* \n " + codigoFuente + " \n */\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\t}\n\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                System.out.print("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (");
                n = 0;
                for (String parametro : atributos) {
                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        System.out.print(" " + parametro + ", ");
                    } else {
                        System.out.print(" " + parametro);
                    }
                    n++;

                }
                System.out.println(" ) {");
                System.out.println("/* \n " + codigoFuente + " \n */");
                System.out.println("\t}\n");
            }

        }

        contentInBytes = ("}\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();
        fout.close();

        XPathExpression<Attribute> xp = XPathFactory.instance().compile("//@*", Filters.attribute(xmi));
        for (Attribute a : xp.evaluate(doc)) {
            a.setName(a.getName().toLowerCase());
        }

        xpath = XPathFactory.instance().compile("//codeElement/@name='testvb.cls'", Filters.element());
        Element emt = xpath.evaluateFirst(doc);
        if (emt != null) {
            System.out.println("XPath has result: " + emt.getName());
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.archimatetool.editor.model.compatibility.Archimate2To3Converter.java

License:Open Source License

/**
 * Convert concept name types/* ww  w  . j a v a 2  s  . co m*/
 */
private void convertConceptTypeName(Element element) {
    Attribute attType = element.getAttribute("type", JDOMUtils.XSI_Namespace);

    if (attType != null) {
        String oldValue = attType.getValue();
        String newValue = ConceptNameMapping.get(oldValue);

        if (newValue != null) {
            attType.setValue(newValue);
        }

        // Or Junction has type set
        if ("archimate:OrJunction".equals(oldValue)) {
            element.setAttribute("type", "or");
        }
    }
}

From source file:com.archimatetool.editor.model.compatibility.Archimate2To3Converter.java

License:Open Source License

/**
 * Move concepts to different folders/*from  w w  w.  j a v a 2s . c  o  m*/
 */
private void moveConceptType(Element element) {
    Attribute attType = element.getAttribute("type", JDOMUtils.XSI_Namespace);

    if (attType != null) {
        String value = attType.getValue();

        // Location
        if ("archimate:Location".equals(value)) {
            Element eFolder = getModelFolder("other");
            if (eFolder != null) {
                element.detach();
                eFolder.addContent(element);
            }
        }

        // Value / Meaning
        if ("archimate:Value".equals(value) || "archimate:Meaning".equals(value)) {
            Element eFolder = getModelFolder("motivation");
            if (eFolder != null) {
                element.detach();
                eFolder.addContent(element);
            }
        }
    }
}

From source file:com.c4om.autoconf.ulysses.extra.svrlinterpreter.SVRLInterpreterProcessor.java

License:Apache License

/**
 * This method:/*from www  .j a  v a2s.  co  m*/
 * <ol>
 * <li>Takes an attribute from a source element</li>
 * <li>Detaches it</li>
 * <li>Removes its namespace</li>
 * <li>Attaches it to a destination element</li>
 * </ol>
 * @param sourceElement source element
 * @param destinationElement destination element
 * @param attrName the name of the attribute
 * @param attrNamespace the namespace of the source attribute (it will be removed at destination)
 */
private static void moveAndRemoveNSOfAttr(Element sourceElement, Element destinationElement, String attrName,
        Namespace attrNamespace) {
    Attribute mandatoryPathAttribute = sourceElement.getAttribute(attrName, attrNamespace);
    if (mandatoryPathAttribute != null) {
        mandatoryPathAttribute.detach();
        mandatoryPathAttribute.setNamespace(Namespace.NO_NAMESPACE);
        destinationElement.setAttribute(mandatoryPathAttribute);
    }
}

From source file:com.novell.ldapchai.impl.edir.NmasResponseSet.java

License:Open Source License

private static String readDisplayString(final Element questionElement, final Locale locale) {

    final Namespace XML_NAMESPACE = Namespace.getNamespace("xml", "http://www.w3.org/XML/1998/namespace");

    // someday ResoureBundle won't suck and this will be a 5 line method.

    // see if the node has any localized displays.
    final List displayChildren = questionElement.getChildren("display");

    // if no locale specified, or if no localized text is available, just use the default.
    if (locale == null || displayChildren == null || displayChildren.size() < 1) {
        return questionElement.getText();
    }//from  ww  w.j a va 2  s.c  om

    // convert the xml 'display' elements to a map of locales/strings
    final Map<Locale, String> localizedStringMap = new HashMap<Locale, String>();
    for (final Object aDisplayChildren : displayChildren) {
        final Element loopDisplay = (Element) aDisplayChildren;
        final Attribute localeAttr = loopDisplay.getAttribute("lang", XML_NAMESPACE);
        if (localeAttr != null) {
            final String localeStr = localeAttr.getValue();
            final String displayStr = loopDisplay.getText();
            final Locale localeKey = parseLocaleString(localeStr);
            localizedStringMap.put(localeKey, displayStr);
        }
    }

    final Locale matchedLocale = localeResolver(locale, localizedStringMap.keySet());

    if (matchedLocale != null) {
        return localizedStringMap.get(matchedLocale);
    }

    // none found, so just return the default string.
    return questionElement.getText();
}