Example usage for org.jdom2 Element getNamespace

List of usage examples for org.jdom2 Element getNamespace

Introduction

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

Prototype

public Namespace getNamespace() 

Source Link

Document

Returns the element's Namespace .

Usage

From source file:org.rometools.feed.module.mediarss.io.RSS20YahooParser.java

License:Open Source License

/**
 * Indicates if a JDom document is an RSS instance that can be parsed with the parser.
 * <p/>/*from w ww . j a  v  a  2 s  . co m*/
 * It checks for RDF ("http://www.w3.org/1999/02/22-rdf-syntax-ns#") and
 * RSS ("http://purl.org/rss/1.0/") namespaces being defined in the root element.
 *
 * @param document document to check if it can be parsed with this parser implementation.
 * @return <b>true</b> if the document is RSS1., <b>false</b> otherwise.
 */
public boolean isMyType(Document document) {
    boolean ok = false;

    Element rssRoot = document.getRootElement();
    Namespace defaultNS = rssRoot.getNamespace();
    List additionalNSs = rssRoot.getAdditionalNamespaces();

    ok = (defaultNS != null) && defaultNS.equals(getRSSNamespace());

    return ok;
}

From source file:org.rometools.feed.module.photocast.io.Parser.java

License:Open Source License

public Module parse(Element element) {
    if (element.getName().equals("channel") || element.getName().equals("feed")) {
        return new PhotocastModuleImpl();
    } else if (element.getChild("metadata", Parser.NS) == null && element.getChild("image", Parser.NS) == null)
        return null;
    PhotocastModule pm = new PhotocastModuleImpl();
    List children = element.getChildren();
    Iterator it = children.iterator();
    while (it.hasNext()) {
        Element e = (Element) it.next();
        if (!e.getNamespace().equals(Parser.NS))
            continue;
        if (e.getName().equals("photoDate")) {
            try {
                pm.setPhotoDate(Parser.PHOTO_DATE_FORMAT.parse(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse photoDate: " + e.getText() + " " + ex.toString());
            }/* www .ja v a 2 s  .  c om*/
        } else if (e.getName().equals("cropDate")) {
            try {
                pm.setCropDate(Parser.CROP_DATE_FORMAT.parse(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse cropDate: " + e.getText() + " " + ex.toString());
            }
        } else if (e.getName().equals("thumbnail")) {
            try {
                pm.setThumbnailUrl(new URL(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse thumnail: " + e.getText() + " " + ex.toString());
            }
        } else if (e.getName().equals("image")) {
            try {
                pm.setImageUrl(new URL(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse image: " + e.getText() + " " + ex.toString());
            }
        } else if (e.getName().equals("metadata")) {
            String comments = "";
            PhotoDate photoDate = null;
            if (e.getChildText("PhotoDate") != null) {
                try {
                    photoDate = new PhotoDate(Double.parseDouble(e.getChildText("PhotoDate")));
                } catch (Exception ex) {
                    LOG.warning("Unable to parse PhotoDate: " + e.getText() + " " + ex.toString());
                }
            }
            if (e.getChildText("Comments") != null) {
                comments = e.getChildText("Comments");
            }
            pm.setMetadata(new Metadata(photoDate, comments));
        }
    }
    return pm;
}

From source file:org.rometools.feed.module.sle.io.ModuleParser.java

License:Apache License

/**
 * Parses the XML node (JDOM element) extracting module information.
 * <p>//  w  w w.j  av a2s .c  om
 *
 * @param element the XML node (JDOM element) to extract module information from.
 * @return a module instance, <b>null</b> if the element did not have module information.
 */
public Module parse(Element element) {
    if (element.getChild("treatAs", NS) == null) {
        return null;
    }

    SimpleListExtension sle = new SimpleListExtensionImpl();
    sle.setTreatAs(element.getChildText("treatAs", NS));

    Element listInfo = element.getChild("listinfo", NS);
    List groups = listInfo.getChildren("group", NS);
    ArrayList values = new ArrayList();

    for (int i = 0; (groups != null) && (i < groups.size()); i++) {
        Element ge = (Element) groups.get(i);
        Namespace ns = (ge.getAttribute("ns") == null) ? element.getNamespace()
                : Namespace.getNamespace(ge.getAttributeValue("ns"));
        String elementName = ge.getAttributeValue("element");
        String label = ge.getAttributeValue("label");
        values.add(new Group(ns, elementName, label));
    }

    sle.setGroupFields((Group[]) values.toArray(new Group[values.size()]));
    values = (values.size() == 0) ? values : new ArrayList();

    List sorts = listInfo.getChildren("sort", NS);

    for (int i = 0; (sorts != null) && (i < sorts.size()); i++) {
        Element se = (Element) sorts.get(i);
        System.out.println(
                "Parse cf:sort " + se.getAttributeValue("element") + se.getAttributeValue("data-type"));
        Namespace ns = (se.getAttributeValue("ns") == null) ? element.getNamespace()
                : Namespace.getNamespace(se.getAttributeValue("ns"));
        String elementName = se.getAttributeValue("element");
        String label = se.getAttributeValue("label");
        String dataType = se.getAttributeValue("data-type");
        boolean defaultOrder = (se.getAttributeValue("default") == null) ? false
                : new Boolean(se.getAttributeValue("default")).booleanValue();
        values.add(new Sort(ns, elementName, dataType, label, defaultOrder));
    }

    sle.setSortFields((Sort[]) values.toArray(new Sort[values.size()]));
    insertValues(sle, element.getChildren());

    return sle;
}

From source file:org.savantbuild.dep.maven.POM.java

License:Open Source License

public POM(Path file) throws RuntimeException {
    SAXBuilder builder = new SAXBuilder();
    try {//from   w  ww .  j a v  a2s.c  o m
        Element pomElement = builder.build(file.toFile()).getRootElement();
        version = pomElement.getChildText("version", pomElement.getNamespace());
        if (version != null) {
            properties.put("project.version", version);
        }
        if (pomElement.getChildText("groupId", pomElement.getNamespace()) != null) {
            properties.put("project.groupId", pomElement.getChildText("groupId", pomElement.getNamespace()));
        }
        if (pomElement.getChildText("artifactId", pomElement.getNamespace()) != null) {
            properties.put("project.artifactId",
                    pomElement.getChildText("artifactId", pomElement.getNamespace()));
        }
        if (pomElement.getChildText("name", pomElement.getNamespace()) != null) {
            properties.put("project.name", pomElement.getChildText("name", pomElement.getNamespace()));
        }
        if (pomElement.getChildText("packaging", pomElement.getNamespace()) != null) {
            properties.put("project.packaging",
                    pomElement.getChildText("packaging", pomElement.getNamespace()));
        }

        // Grab the parent info
        Element parent = pomElement.getChild("parent", pomElement.getNamespace());
        if (parent != null) {
            parentGroup = parent.getChildText("groupId", pomElement.getNamespace());
            parentId = parent.getChildText("artifactId", pomElement.getNamespace());
            parentVersion = parent.getChildText("version", pomElement.getNamespace());
        }

        // Grab the properties
        Element properties = pomElement.getChild("properties", pomElement.getNamespace());
        if (properties != null) {
            properties.getChildren()
                    .forEach((element) -> this.properties.put(element.getName(), element.getTextTrim()));
        }

        // Grab the dependencies (top-level)
        Element dependencies = pomElement.getChild("dependencies", pomElement.getNamespace());
        if (dependencies != null) {
            dependencies.getChildren().forEach((element) -> this.dependencies.add(parseArtifact(element)));
        }

        // Grab the dependencyManagement info (top-level)
        Element dependencyManagement = pomElement.getChild("dependencyManagement", pomElement.getNamespace());
        if (dependencyManagement != null) {
            Element depMgntDeps = dependencyManagement.getChild("dependencies",
                    dependencyManagement.getNamespace());
            depMgntDeps.getChildren()
                    .forEach((element) -> this.dependenciesDefinitions.add(parseArtifact(element)));
        }
    } catch (JDOMException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.savantbuild.dep.maven.POM.java

License:Open Source License

private MavenArtifact parseArtifact(Element element) {
    MavenArtifact artifact = new MavenArtifact();
    artifact.group = element.getChildText("groupId", element.getNamespace());
    artifact.id = element.getChildText("artifactId", element.getNamespace());
    artifact.version = element.getChildText("version", element.getNamespace());
    artifact.type = element.getChildText("type", element.getNamespace());
    artifact.optional = toBoolean(element.getChildText("optional", element.getNamespace()));
    artifact.scope = element.getChildText("scope", element.getNamespace());
    if (artifact.scope == null) {
        artifact.scope = "compile";
    }//from   w w  w. ja  v a  2 s.co  m
    if (artifact.optional) {
        artifact.scope += "-optional";
    }

    List<Element> exclusions = element.getChildren("exclusions", element.getNamespace());
    if (exclusions.size() > 0) {
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        System.out.println(
                "This Maven artifact has a dependency [" + artifact + "] with exclusions " + exclusions);
        System.out.println("This indicates that the artifact [" + artifact
                + "] declared a bad dependency or declared an optional dependency as required.");
        System.out.println(
                "There isn't much we can do here since Savant doesn't allow exclusions because they should not occur when dependencies are listed and configured correctly.");
        System.out.println();
    }

    return artifact;
}

From source file:org.transitime.custom.nyc.BusTimeSiriAvlModule.java

License:Open Source License

/**
 * Extracts the AVL data from the XML document.
 * Uses JDOM to parse the XML because it makes the Java code much simpler.
 * @param doc/*from   w  w  w  .  j  ava  2  s. c  om*/
 * @throws NumberFormatException
 */
@Override
protected void extractAvlData(Document doc) throws NumberFormatException {
    logger.info("Extracting data from xml file");

    // Get root of doc
    Element rootNode = doc.getRootElement();

    // Get the Namespace. Found that if don't use the namespace when calling 
    // getChild() then it returns null!
    Namespace ns = rootNode.getNamespace();

    Element serviceDelivery = rootNode.getChild("ServiceDelivery", ns);
    if (serviceDelivery == null) {
        logger.error("ServiceDelivery element not found in XML data");
        return;
    }
    Element vehicleMonitoringDelivery = serviceDelivery.getChild("VehicleMonitoringDelivery", ns);
    if (vehicleMonitoringDelivery == null) {
        logger.error("VehicleMonitoringDelivery element not found in XML data");
        return;
    }

    // Handle any error message
    Element errorCondition = vehicleMonitoringDelivery.getChild("ErrorCondition", ns);
    if (errorCondition != null) {
        Element description = errorCondition.getChild("Description", ns);
        String errorStr = description.getTextNormalize();
        logger.error("While processing AVL data in BusTimeSiriAvlModule: " + errorStr);
        return;
    }

    // Handle getting vehicle location data
    List<Element> vehicles = vehicleMonitoringDelivery.getChildren("VehicleActivity", ns);
    for (Element vehicle : vehicles) {
        Element monitoredVehicleJourney = vehicle.getChild("MonitoredVehicleJourney", ns);
        if (monitoredVehicleJourney != null) {
            // Get vehicle id
            Element vehicleRef = monitoredVehicleJourney.getChild("VehicleRef", ns);
            String vehicleRefStr = vehicleRef.getTextNormalize();
            String vehicleId = vehicleRefStr.substring(vehicleRefStr.lastIndexOf('_') + 1);

            // Get the timestamp of the GPS report. 
            // Note: this probably isn't the actually GPS timestamp but instead
            // when the GPS report was "recorded", but it is the best we have.
            Element recordedAtTime = monitoredVehicleJourney.getChild("RecordedAtTime", ns);
            String timestampStr = recordedAtTime.getTextNormalize();
            // The timestamp in the XML has the TimeZone specified as "-04:00" instead of
            // what SimpleDateFormat can handle, which is "0400". Therefore need to remove
            // that one semicolon.
            String fixedStr = timestampStr.substring(0, timestampStr.lastIndexOf(':')) + "00";
            long gpsEpochTime = 0;
            try {
                gpsEpochTime = dateFormatter.parse(fixedStr).getTime();
            } catch (ParseException e) {
                logger.error("Could not parse <RecordedAtTime> of \"" + timestampStr + "\"");
            }

            // Get lat & lon
            Element vehicleLocation = monitoredVehicleJourney.getChild("VehicleLocation", ns);
            Element latitude = vehicleLocation.getChild("Latitude", ns);
            float lat = Float.parseFloat(latitude.getTextNormalize());
            Element longitude = vehicleLocation.getChild("Longitude", ns);
            float lon = Float.parseFloat(longitude.getTextNormalize());

            // Block assignment. This one is hard to figure out. While there is a <BlockRef>
            // element it appears that it is not the right one. Instead need to use
            // <FramedVehicleJourneyRef><DatedVehicleJourneyRef> and then just use
            // the last two chunks of something like "MTA NYCT_GH_C3-Weekday-SDon-118800_BX44A_115".
            // And at NextBus we definitely saw lots of problems where the block assignment
            // info wasn't accurate.
            Element framedVehicleJourneyRef = monitoredVehicleJourney.getChild("FramedVehicleJourneyRef", ns);
            Element datedVehicleJourneyRef = framedVehicleJourneyRef.getChild("DatedVehicleJourneyRef", ns);
            String fullBlockName = datedVehicleJourneyRef.getTextNormalize();
            String blockName2 = fullBlockName.substring(fullBlockName.lastIndexOf('-') + 1);
            String block = blockName2.substring(blockName2.indexOf('_') + 1);

            // Heading
            float heading = Float.NaN;
            Element bearingElement = monitoredVehicleJourney.getChild("Bearing", ns);
            if (bearingElement != null) {
                float bearing = Float.parseFloat(bearingElement.getTextNormalize());

                // For bearing: 0 is East, increments counter-clockwise. 
                // But GPS heading: 0 is North, increments clockwise. So 
                // need to convert.
                heading = 90.0f - bearing;
                if (heading < 0.0f)
                    heading += 360.0f;
            }

            // Speed is not available
            float speed = Float.NaN;

            logger.debug("vehicle={} time={} lat={} lon={} spd={} head={} blk={}", vehicleId,
                    Time.timeStr(gpsEpochTime), lat, lon, speed, heading, block);

            // Create the AVL object and send it to the JMS topic
            AvlReport avlReport = new AvlReport(vehicleId, gpsEpochTime, lat, lon, speed, heading, "SIRI");
            avlReport.setAssignment(block, AssignmentType.BLOCK_ID);

            processAvlReport(avlReport);
        }
    }

}

From source file:org.xcri.util.lax.Lax.java

License:Open Source License

/**
 * Get specified child elements as generously as possible
 * /*  w  w  w.j  a  v  a 2s  . co  m*/
 * @param parentElement
 * @param childElementName
 * @param preferredNamespace
 * @return
 * @throws WrongNamespaceException
 * @throws ElementNameFormattingException
 */
@SuppressWarnings("unchecked")
private static List<Element> getAllChildren(Element parentElement, String childElementName,
        Namespace preferredNamespace) throws LaxException {

    boolean misspelled = false;
    boolean wrongNamespace = false;

    LinkedList<Element> list = new LinkedList<Element>();
    List<Element> allChildren = parentElement.getChildren();
    Iterator<Element> iter = allChildren.iterator();
    while (iter.hasNext()) {
        Element nextElement = iter.next();
        if (nextElement.getName().equals(childElementName)) {
            //
            // Add elements that use the wrong namespace, but correct it
            // here so when its exported its correct
            //
            list.add(nextElement);
            if (nextElement.getNamespace() != preferredNamespace) {
                nextElement.setNamespace(preferredNamespace);
                wrongNamespace = true;
            }
        } else if (nextElement.getName().compareToIgnoreCase(childElementName) == 0) {
            //
            // Add elements that use incorrect case, but correct it here
            // so when its exported its done correctly
            //
            nextElement.setName(childElementName);
            list.add(nextElement);
            misspelled = true;
        }
    }
    if (misspelled || wrongNamespace) {
        LaxException ex = new LaxException(list);
        ex.setMisspelled(misspelled);
        ex.setIncorrectNamespace(wrongNamespace);
        throw ex;
    }

    return list;
}

From source file:org.xflatdb.xflat.engine.CachedDocumentEngine.java

License:Apache License

@Override
protected boolean spinUp() {
    if (!this.state.compareAndSet(EngineState.Uninitialized, EngineState.SpinningUp)) {
        return false;
    }/*from   w  w w.j  a  v a 2s  . c o  m*/

    this.getTableLock();
    try {
        synchronized (syncRoot) {
            //concurrency level 4 - don't expect to need more than this.
            this.cache = new ConcurrentHashMap<>(16, 0.75f, 4);
            this.uncommittedRows = new ConcurrentHashMap<>(16, 0.75f, 4);

            if (file.exists()) {
                try {
                    Document doc = this.file.readFile();
                    List<Element> rowList = doc.getRootElement().getChildren("row", XFlatConstants.xFlatNs);

                    for (int i = rowList.size() - 1; i >= 0; i--) {
                        Element row = rowList.get(i);

                        if (row.getChildren().isEmpty()) {
                            continue;
                        }

                        String id = getId(row);

                        Row newRow = null;

                        for (Element data : row.getChildren()) {
                            //default it to zero so that we know it's committed but if we don't get an actual
                            //value for the commit then we have the lowest value.
                            long txId = 0;
                            long commitId = 0;

                            String a = data.getAttributeValue("tx", XFlatConstants.xFlatNs);
                            if (a != null && !"".equals(a)) {
                                try {
                                    txId = Long.parseLong(a, TRANSACTION_ID_RADIX);
                                } catch (NumberFormatException ex) {
                                    //just leave it as 0.
                                }
                            }
                            a = data.getAttributeValue("commit", XFlatConstants.xFlatNs);
                            if (a != null && !"".equals(a)) {
                                try {
                                    commitId = Long.parseLong(a, TRANSACTION_ID_RADIX);
                                } catch (NumberFormatException ex) {
                                    //just leave it as 0.
                                }
                            }

                            if ("delete".equals(data.getName())
                                    && XFlatConstants.xFlatNs.equals(data.getNamespace())) {
                                //it's a delete marker
                                data = null;
                            } else {
                                data = data.clone();
                            }

                            RowData rData = new RowData(txId, data, id);
                            rData.commitId = commitId;

                            if (newRow == null)
                                newRow = new Row(id, rData);
                            else
                                newRow.rowData.put(txId, rData);
                        }

                        if (newRow != null)
                            this.cache.put(id, newRow);
                    }
                } catch (JDOMException | IOException ex) {
                    throw new XFlatException("Error building document cache", ex);
                }
            }

            this.state.set(EngineState.SpunUp);
            if (operationsReady.get()) {
                this.state.set(EngineState.Running);
                synchronized (operationsReady) {
                    operationsReady.notifyAll();
                }
            }

            return true;
        }
    } finally {
        this.releaseTableLock();
    }
}

From source file:org.yawlfoundation.yawl.elements.YTask.java

License:Open Source License

private void addDefaultValuesAsRequired(Document dataDoc) {
    if (dataDoc == null)
        return;/*w w w  .  j a  v  a  2 s . c  o  m*/
    Element dataElem = dataDoc.getRootElement();
    for (YParameter param : _decompositionPrototype.getOutputParameters().values()) {
        String defaultValue = param.getDefaultValue();
        if (!StringUtil.isNullOrEmpty(defaultValue)) {
            Element paramData = dataElem.getChild(param.getPreferredName());

            // if there's an element, but no value, add the default
            if (paramData != null) {
                if (StringUtil.isNullOrEmpty(paramData.getText())) {
                    paramData.setText(defaultValue);
                }
            }

            // else if there's no element at all, add it with the default value
            else {
                Element defElem = JDOMUtil
                        .stringToElement(StringUtil.wrap(defaultValue, param.getPreferredName()));
                defElem.setNamespace(dataElem.getNamespace());
                dataElem.addContent(Math.min(dataElem.getContentSize(), param.getOrdering()), defElem.detach());
            }
        }
    }
}

From source file:org.yawlfoundation.yawl.resourcing.jsf.dynform.DynFormFieldAssembler.java

License:Open Source License

private void buildMap(String schemaStr, String dataStr) throws DynFormException {
    Element data = JDOMUtil.stringToElement(dataStr);
    Document doc = JDOMUtil.stringToDocument(schemaStr);
    Element root = doc.getRootElement(); // schema
    Namespace ns = root.getNamespace();
    Element element = root.getChild("element", ns);
    _formName = element.getAttributeValue("name"); // name of case/task
    _fieldList = createFieldList(element, data, ns, -1);
}