Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:ca.nrc.cadc.ac.xml.UserRequestReader.java

License:Open Source License

/**
 * Construct a UserRequest from a Reader.
 *
 * @param reader Reader.//  w w  w . ja  v a 2 s . c om
 * @return UserRequest UserRequest.
 * @throws ReaderException
 * @throws java.io.IOException
 */
public UserRequest read(Reader reader) throws ReaderException, IOException {
    if (reader == null) {
        throw new IllegalArgumentException("reader must not be null");
    }

    // Create a JDOM Document from the XML
    Document document;
    try {
        document = XmlUtil.buildDocument(reader);
    } catch (JDOMException jde) {
        String error = "XML failed validation: " + jde.getMessage();
        throw new ReaderException(error, jde);
    }

    // Root element and namespace of the Document
    Element root = document.getRootElement();

    return getUserRequest(root);
}

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

License:Open Source License

public ArtifactAccess read(Reader reader) throws IOException {
    if (reader == null) {
        throw new IllegalArgumentException("reader must not be null");
    }/*from w  w  w  .j  ava 2 s.  c  o m*/

    Document document;
    try {
        document = XmlUtil.buildDocument(reader);
    } catch (JDOMException ex) {
        throw new IllegalArgumentException("invalid input document", ex);
    }

    // Root element and namespace of the Document
    Element root = document.getRootElement();
    if (!ENAMES.artifactAccess.name().equals(root.getName())) {
        throw new IllegalArgumentException(
                "invalid root element: " + root.getName() + " expected: " + ENAMES.artifactAccess);
    }

    Artifact a = getArtifact(root.getChild(ENAMES.artifact.name()));
    ArtifactAccess ret = new ArtifactAccess(a);

    ret.isPublic = getBoolean(root.getChildTextTrim(ENAMES.isPublic.name()));

    getGroupList(ret.getReadGroups(), ENAMES.readGroups.name(), root.getChildren(ENAMES.readGroups.name()));

    return ret;
}

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

License:Open Source License

/**
 * Construct an Observation from a Reader.
 *
 * @param reader//w  w w  .j av 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.dali.tables.votable.VOTableReader.java

License:Open Source License

/**
 * Read a XML VOTable from a Reader and build a VOTable object.
 *
 * @param reader Reader to read from.//from  w  ww  .ja v  a2s  .c  o m
 * @return a VOTable object.
 * @throws IOException if problem reading from the reader.
 */
public VOTable read(Reader reader) throws IOException {
    // Parse the input document.
    Document document;
    try {
        document = docBuilder.build(reader);
    } catch (JDOMException e) {
        throw new IOException("Unable to parse " + e.getMessage());
    }

    // Returned VOTable object.
    VOTable votable = new VOTable();

    // Document root element.
    Element root = document.getRootElement();

    // Namespace for the root element.
    Namespace namespace = root.getNamespace();
    log.debug("Namespace: " + namespace);

    // RESOURCE element.
    Element resource = root.getChild("RESOURCE", namespace);
    if (resource != null) {
        // Get the RESOURCE name attribute.
        Attribute resourceName = resource.getAttribute("name");
        if (resourceName != null) {
            votable.setResourceName(resourceName.getValue());
        }

        // INFO element.
        List<Element> infos = resource.getChildren("INFO", namespace);
        votable.getInfos().addAll(getInfos(infos, namespace));

        // TABLE element.
        Element table = resource.getChild("TABLE", namespace);
        if (table != null) {
            // PARAM elements.
            List<Element> params = table.getChildren("PARAM", namespace);
            votable.getParams().addAll(getParams(params, namespace));

            // FIELD elements.
            List<Element> fields = table.getChildren("FIELD", namespace);
            votable.getColumns().addAll(getFields(fields, namespace));

            // DATA element.
            Element data = table.getChild("DATA", namespace);
            if (data != null) {
                // TABLEDATA element.
                Element tableData = data.getChild("TABLEDATA", namespace);
                votable.setTableData(getTableData(tableData, namespace, votable.getColumns()));
            }
        }
    }
    return votable;
}

From source file:ca.nrc.cadc.dali.tables.votable.VOTableWriter.java

License:Open Source License

/**
 * Write the VOTable to the specified Writer, only writing maxrec rows.
 * If the VOTable contains more than maxrec rows, appends an INFO element with
 * name="QUERY_STATUS" value="OVERFLOW" to the VOTable.
 *
 * @param votable VOTable object to write.
 * @param writer Writer to write to.//from ww  w  .j a  v  a 2 s.  c  om
 * @param maxRec maximum number of rows to write.
 * @throws IOException if problem writing to the writer.
 */
public void write(VOTable votable, Writer writer, Long maxrec) throws IOException {
    log.debug("write, maxrec=" + maxrec);

    // VOTable document and root element.
    Document document = createDocument();
    Element root = document.getRootElement();
    Namespace namespace = root.getNamespace();

    // Create the RESOURCE element and add to the VOTABLE element.
    Element resource = new Element("RESOURCE", namespace);
    if (votable.getResourceName() != null) {
        resource.setAttribute("name", votable.getResourceName());
    }
    root.addContent(resource);

    // Create the INFO element and add to the RESOURCE element.
    for (Info in : votable.getInfos()) {
        Element info = new Element("INFO", namespace);
        info.setAttribute("name", in.getName());
        info.setAttribute("value", in.getValue());
        resource.addContent(info);
    }

    // Create the TABLE element and add to the RESOURCE element.
    Element table = new Element("TABLE", namespace);
    resource.addContent(table);

    // Add the metadata elements.
    for (TableParam param : votable.getParams()) {
        table.addContent(new ParamElement(param, namespace));
    }
    for (TableField field : votable.getColumns()) {
        table.addContent(new FieldElement(field, namespace));
    }

    // Create the DATA and TABLEDATA elements.
    Element data = new Element("DATA", namespace);
    table.addContent(data);

    // Add content.
    try {
        Iterator<List<Object>> it = votable.getTableData().iterator();

        TabledataContentConverter elementConverter = new TabledataContentConverter(namespace);
        TabledataMaxIterations maxIterations = new TabledataMaxIterations(maxrec, resource, namespace);

        IterableContent<Element, List<Object>> tabledata = new IterableContent<Element, List<Object>>(
                "TABLEDATA", namespace, it, elementConverter, maxIterations);

        data.addContent(tabledata);
    } catch (Throwable t) {
        log.debug("failure while iterating", t);
        Element info = new Element("INFO", namespace);
        info.setAttribute("name", "QUERY_STATUS");
        info.setAttribute("value", "ERROR");
        info.setText(t.toString());
        resource.addContent(info);
    }

    // Write out the VOTABLE.
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(org.jdom2.output.Format.getPrettyFormat());
    outputter.output(document, writer);
}

From source file:ca.nrc.cadc.dali.tables.votable.VOTableWriter.java

License:Open Source License

/**
 * Write the Throwable to a VOTable, creating an INFO element with
 * name="QUERY_STATUS" value="ERROR" and setting the stacktrace as
 * the INFO text./*  ww  w.j a  v  a 2  s .c om*/
 *
 * @param thrown Throwable to write.
 * @param output OutputStream to write to.
 * @throws IOException if problem writing to the stream.
 */
public void write(Throwable thrown, OutputStream output) throws IOException {
    Document document = createDocument();
    Element root = document.getRootElement();
    Namespace namespace = root.getNamespace();

    // Create the RESOURCE element and add to the VOTABLE element.
    Element resource = new Element("RESOURCE", namespace);
    resource.setAttribute("type", "results");
    root.addContent(resource);

    // Create the INFO element and add to the RESOURCE element.
    Element info = new Element("INFO", namespace);
    info.setAttribute("name", "QUERY_STATUS");
    info.setAttribute("value", "ERROR");
    info.setText(getThrownExceptions(thrown));
    resource.addContent(info);

    // Write out the VOTABLE.
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(org.jdom2.output.Format.getPrettyFormat());
    outputter.output(document, output);
}

From source file:ca.nrc.cadc.reg.CapabilitiesReader.java

License:Open Source License

public Capabilities read(Reader reader) {
    if (reader == null) {
        throw new IllegalArgumentException("reader must not be null");
    }//from   w w  w  . ja  v  a 2  s  .  c  o  m

    // Create a JDOM Document from the XML
    Document document;
    try {
        document = XmlUtil.buildDocument(reader, schemaMap);
    } catch (IOException ioe) {
        String msg = "Error reading XML: " + ioe.getMessage();
        throw new RuntimeException(msg, ioe);
    } catch (JDOMException jde) {
        String msg = "XML failed schema validation: " + jde.getMessage();
        throw new RuntimeException(msg, jde);
    }

    return this.buildCapabilities(document.getRootElement());
}

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;//from w w w  . j av  a2s .  c  o 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 Job parseJob(Document doc) throws ParseException, DataConversionException {
    Element root = doc.getRootElement();

    String jobID = root.getChildText(JobAttribute.JOB_ID.getAttributeName(), UWS.NS);
    if (jobID != null && jobID.trim().length() == 0)
        jobID = null;//from w  w  w .j  a  v  a2 s.  c o m
    String runID = parseStringContent(root.getChild(JobAttribute.RUN_ID.getAttributeName(), UWS.NS));
    String ownerID = parseStringContent(root.getChild(JobAttribute.OWNER_ID.getAttributeName(), UWS.NS));
    Date quote = parseDate(parseStringContent(root.getChild(JobAttribute.QUOTE.getAttributeName(), UWS.NS)));
    Date startTime = parseDate(
            parseStringContent(root.getChild(JobAttribute.START_TIME.getAttributeName(), UWS.NS)));
    Date endTime = parseDate(
            parseStringContent(root.getChild(JobAttribute.END_TIME.getAttributeName(), UWS.NS)));
    Date creationTime = parseDate(
            parseStringContent(root.getChild(JobAttribute.CREATION_TIME.getAttributeName(), UWS.NS)));
    Date destructionTime = parseDate(
            parseStringContent(root.getChild(JobAttribute.DESTRUCTION_TIME.getAttributeName(), UWS.NS)));
    Long executionDuration = new Long(
            parseStringContent(root.getChild(JobAttribute.EXECUTION_DURATION.getAttributeName(), UWS.NS)));

    ExecutionPhase executionPhase = parseExecutionPhase(doc);

    ErrorSummary errorSummary = null;
    if (executionPhase.equals(ExecutionPhase.ERROR))
        errorSummary = parseErrorSummary(doc);

    List<Result> resultsList = parseResultsList(doc);

    List<Parameter> parameterList = parseParametersList(doc);

    JobInfo jobInfo = parseJobInfo(doc);

    Job job = new Job(jobID, executionPhase, executionDuration, destructionTime, quote, startTime, endTime,
            creationTime, errorSummary, ownerID, runID, null, null, jobInfo, parameterList, resultsList);

    return job;
}

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

License:Open Source License

private ExecutionPhase parseExecutionPhase(Document doc) {
    ExecutionPhase rtn = null;//  www . j a  v  a2s  .  com
    Element root = doc.getRootElement();
    String strPhase = root.getChildText(JobAttribute.EXECUTION_PHASE.getAttributeName(), UWS.NS);
    if (strPhase.equalsIgnoreCase(ExecutionPhase.PENDING.toString()))
        rtn = ExecutionPhase.PENDING;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.QUEUED.toString()))
        rtn = ExecutionPhase.QUEUED;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.EXECUTING.toString()))
        rtn = ExecutionPhase.EXECUTING;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.COMPLETED.toString()))
        rtn = ExecutionPhase.COMPLETED;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.ERROR.toString()))
        rtn = ExecutionPhase.ERROR;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.UNKNOWN.toString()))
        rtn = ExecutionPhase.UNKNOWN;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.HELD.toString()))
        rtn = ExecutionPhase.HELD;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.SUSPENDED.toString()))
        rtn = ExecutionPhase.SUSPENDED;
    else if (strPhase.equalsIgnoreCase(ExecutionPhase.ABORTED.toString()))
        rtn = ExecutionPhase.ABORTED;

    return rtn;
}