List of usage examples for org.jdom2 Document getRootElement
public Element getRootElement()
Element
for this Document
From source file:ca.nrc.cadc.uws.JobReader.java
License:Open Source License
private List<Parameter> parseParametersList(Document doc) { List<Parameter> rtn = null; Element root = doc.getRootElement(); Element elementParameters = root.getChild(JobAttribute.PARAMETERS.getAttributeName(), UWS.NS); if (elementParameters != null) { rtn = new ArrayList<Parameter>(); Parameter par = null;/* www. j av a 2 s . c om*/ List<?> listElement = elementParameters.getChildren(JobAttribute.PARAMETER.getAttributeName(), UWS.NS); for (Object obj : listElement) { Element e = (Element) obj; String id = e.getAttributeValue("id"); String value = e.getText(); par = new Parameter(id, value); rtn.add(par); } } return rtn; }
From source file:ca.nrc.cadc.uws.JobReader.java
License:Open Source License
private List<Result> parseResultsList(Document doc) { List<Result> rtn = null; Element root = doc.getRootElement(); Element e = root.getChild(JobAttribute.RESULTS.getAttributeName(), UWS.NS); if (e != null) { rtn = new ArrayList<Result>(); Result rs = null;/* ww w . j ava 2s.c om*/ List<?> listE = e.getChildren(JobAttribute.RESULT.getAttributeName(), UWS.NS); for (Object obj : listE) { Element eRs = (Element) obj; String id = eRs.getAttributeValue("id"); String href = eRs.getAttributeValue("href", UWS.XLINK_NS); try { rs = new Result(id, new URI(href)); rtn.add(rs); } catch (URISyntaxException ex) { // do nothing; just do not add rs to list log.debug(ex.getMessage()); } } } return rtn; }
From source file:ca.nrc.cadc.uws.JobReader.java
License:Open Source License
private ErrorSummary parseErrorSummary(Document doc) { ErrorSummary rtn = null;/*from ww w . j ava2s . co m*/ Element root = doc.getRootElement(); Element e = root.getChild(JobAttribute.ERROR_SUMMARY.getAttributeName(), UWS.NS); if (e != null) { ErrorType errorType = null; String strType = e.getAttributeValue("type"); if (strType.equalsIgnoreCase(ErrorType.FATAL.toString())) errorType = ErrorType.FATAL; else if (strType.equalsIgnoreCase(ErrorType.TRANSIENT.toString())) errorType = ErrorType.TRANSIENT; boolean hasDetail = false; String strDetail = e.getAttributeValue("hasDetail"); if (strDetail.equalsIgnoreCase("true")) hasDetail = true; String summaryMessage = e.getChildText(JobAttribute.ERROR_SUMMARY_MESSAGE.getAttributeName(), UWS.NS); rtn = new ErrorSummary(summaryMessage, errorType, hasDetail); } return rtn; }
From source file:ca.nrc.cadc.uws.JobReader.java
License:Open Source License
private JobInfo parseJobInfo(Document doc) { JobInfo rtn = null;/*from w w w. ja v a2 s. c o m*/ Element root = doc.getRootElement(); Element e = root.getChild(JobAttribute.JOB_INFO.getAttributeName(), UWS.NS); if (e != null) { log.debug("found jobInfo element"); String content = e.getText(); List children = e.getChildren(); if (content != null) content = content.trim(); if (content.length() > 0) // it was text content { rtn = new JobInfo(content, null, null); } else if (children != null) { if (children.size() == 1) { try { Element ce = (Element) children.get(0); Document jiDoc = new Document((Element) ce.detach()); XMLOutputter outputter = new XMLOutputter(); StringWriter sw = new StringWriter(); outputter.output(jiDoc, sw); sw.close(); rtn = new JobInfo(sw.toString(), null, null); } catch (IOException ex) { throw new RuntimeException("BUG while writing element to string", ex); } } } } log.debug("parseJobInfo: " + rtn); return rtn; }
From source file:ca.nrc.cadc.uws.JobWriter.java
License:Open Source License
/** * Get an Element representing the Job jobInfo. * * @return The Job jobInfo Element./* w ww . j a v a2 s . c om*/ */ public Element getJobInfo(Job job) { Element element = null; JobInfo jobInfo = job.getJobInfo(); if (jobInfo != null) { if (jobInfo.getContent() != null && jobInfo.getValid() != null && jobInfo.getValid()) { element = new Element(JobAttribute.JOB_INFO.getAttributeName(), UWS.NS); try { // The JobInfo content can't be validated since the schema(s) aren't known // but we still need to parse and extract the root/document element Document doc = XmlUtil.buildDocument(jobInfo.getContent()); element.addContent(doc.getRootElement().detach()); } catch (Exception e) { element = null; } } } return element; }
From source file:ca.nrc.cadc.uws.sample.HelloWorld.java
License:Open Source License
public void run() { log.debug("run: " + job.getID()); try {//from w w w.j a va 2 s .c o m ExecutionPhase ep = jobUpdater.setPhase(job.getID(), ExecutionPhase.QUEUED, ExecutionPhase.EXECUTING, new Date()); if (!ExecutionPhase.EXECUTING.equals(ep)) { ep = jobUpdater.getPhase(job.getID()); log.debug(job.getID() + ": QUEUED -> EXECUTING [FAILED] -- DONE"); return; } log.info(job.getID() + ": QUEUED -> EXECUTING [OK]"); String passValue = null; String streamValue = null; String runforValue = null; boolean pass = false; boolean stream = false; long runfor = 1; // JobInfo input (XML) if (job.getJobInfo() != null) { // TODO: content type/error handling here JobInfo ji = job.getJobInfo(); if (ji.getValid() != null && ji.getValid()) { Document document = XmlUtil.buildDocument(ji.getContent()); Element root = document.getRootElement(); passValue = root.getChildText("pass"); streamValue = root.getChildText("stream"); runforValue = root.getChildText("runfor"); } } else // parameter list input { passValue = ParameterUtil.findParameterValue(PASS, job.getParameterList()); streamValue = ParameterUtil.findParameterValue(STREAM, job.getParameterList()); runforValue = ParameterUtil.findParameterValue(RUNFOR, job.getParameterList()); } if (passValue != null) try { pass = Boolean.parseBoolean(passValue); } catch (Exception ignore) { log.debug("invalid boolean value: " + PASS + "=" + passValue); } if (streamValue != null) try { stream = Boolean.parseBoolean(streamValue); } catch (Exception ignore) { log.debug("invalid boolean value: " + STREAM + "=" + streamValue); } if (runforValue != null) try { runfor = Long.parseLong(runforValue); } catch (Exception ignore) { log.debug("invalid long value: " + RUNFOR + "=" + runforValue); } // sanity check runfor *= 1000L; // convert to milliseconds if (runfor < MIN_RUNFOR) runfor = MIN_RUNFOR; else if (runfor > MAX_RUNFOR) runfor = MAX_RUNFOR; log.debug("pass: " + pass + ", stream: " + stream + ", duration: " + runfor); Thread.sleep(runfor); ExecutionPhase expected = null; ep = null; if (pass) { expected = ExecutionPhase.COMPLETED; List<Result> results = generateResults(); if (syncOutput != null) { if (stream) { syncOutput.setHeader("Content-Type", "text/plain"); PrintWriter w = new PrintWriter(syncOutput.getOutputStream()); w.println(RESULT); w.close(); ep = jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING, ExecutionPhase.COMPLETED, new Date()); } else { syncOutput.setResponseCode(303); syncOutput.setHeader("Location", results.get(0).getURI().toASCIIString()); ep = jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING, ExecutionPhase.COMPLETED, new Date()); } } else // async { ep = jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING, ExecutionPhase.COMPLETED, results, new Date()); } } else { expected = ExecutionPhase.ERROR; ErrorSummary error = generateError(); if (syncOutput != null) { if (stream) { syncOutput.setHeader("Content-Type", "text/plain"); PrintWriter w = new PrintWriter(syncOutput.getOutputStream()); w.println(ERROR); w.close(); ep = jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING, ExecutionPhase.COMPLETED, new Date()); } else { syncOutput.setResponseCode(303); syncOutput.setHeader("Location", error.getDocumentURL().toExternalForm()); ep = jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING, ExecutionPhase.ERROR, error, new Date()); } } else // async { ep = jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING, ExecutionPhase.ERROR, error, new Date()); } } if (expected.equals(ep)) log.info(job.getID() + ": EXECUTING -> " + expected.name() + " [OK]"); else log.info(job.getID() + ": EXECUTING -> " + expected.name() + " [FAILED]"); } //catch(JobNotFoundException ex) { } // either a bug or someone deleted the job after executing it //catch(JobPersistenceException ex) { } // back end persistence is failing catch (Throwable t) { log.error("unexpected failure", t); ErrorSummary error = new ErrorSummary(t.toString(), ErrorType.FATAL); if (syncOutput != null) { try { PrintWriter pw = new PrintWriter(syncOutput.getOutputStream()); pw.println(t.getMessage()); pw.close(); } catch (IOException ex) { log.error("failed to write unexpected failure message to output", ex); } } try { jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING, ExecutionPhase.ERROR, error, new Date()); } catch (Exception ex) { log.error("failed to set unexpected error state: " + ex); } } }
From source file:ca.nrc.cadc.vos.NodeReader.java
License:Open Source License
/** * Construct a Node from a Reader./*ww w .java2 s .c o m*/ * * @param reader Reader. * @return Node Node. * @throws NodeParsingException if there is an error parsing the XML. */ public Node read(Reader reader) throws NodeParsingException, IOException { if (reader == null) throw new IllegalArgumentException("reader must not be null"); // Create a JDOM Document from the XML Document document; try { // TODO: investigate creating a SAXBuilder once and re-using it // as long as we can detect concurrent access (a la java collections) document = XmlUtil.validateXml(reader, schemaMap); } catch (JDOMException jde) { String error = "XML failed schema validation: " + jde.getMessage(); throw new NodeParsingException(error, jde); } // Root element and namespace of the Document Element root = document.getRootElement(); Namespace namespace = root.getNamespace(); log.debug("node namespace uri: " + namespace.getURI()); log.debug("node namespace prefix: " + namespace.getPrefix()); /* Node base elements */ // uri attribute of the node element String uri = root.getAttributeValue("uri"); if (uri == null) { String error = "uri attribute not found in root element"; throw new NodeParsingException(error); } log.debug("node uri: " + uri); // Get the xsi:type attribute which defines the Node class String xsiType = root.getAttributeValue("type", xsiNamespace); if (xsiType == null) { String error = "xsi:type attribute not found in node element " + uri; throw new NodeParsingException(error); } // Split the type attribute into namespace and Node type String[] types = xsiType.split(":"); String type = types[1]; log.debug("node type: " + type); try { if (type.equals(ContainerNode.class.getSimpleName())) return buildContainerNode(root, namespace, uri); else if (type.equals(DataNode.class.getSimpleName())) return buildDataNode(root, namespace, uri); else if (type.equals(UnstructuredDataNode.class.getSimpleName())) return buildUnstructuredDataNode(root, namespace, uri); else if (type.equals(LinkNode.class.getSimpleName())) return buildLinkNode(root, namespace, uri); else if (type.equals(StructuredDataNode.class.getSimpleName())) return buildStructuredDataNode(root, namespace, uri); else throw new NodeParsingException("unsupported node type " + type); } catch (URISyntaxException e) { throw new NodeParsingException("invalid uri in xml: " + e.getMessage()); } }
From source file:ca.nrc.cadc.vos.TransferReader.java
License:Open Source License
private Transfer parseTransfer(Document document) throws URISyntaxException { Element root = document.getRootElement(); Direction direction = parseDirection(root); // String serviceUrl; // not in XML yet VOSURI target = new VOSURI(root.getChildText("target", VOS_NS)); // TODO: get view nodes and uri attribute View view = null;//from ww w . j ava 2s . c om Parameter param = null; List views = root.getChildren("view", VOS_NS); if (views != null && views.size() > 0) { Element v = (Element) views.get(0); view = new View(new URI(v.getAttributeValue("uri"))); List params = v.getChildren("param", VOS_NS); if (params != null) { for (Object o : params) { Element p = (Element) o; param = new Parameter(new URI(p.getAttributeValue("uri")), p.getText()); view.getParameters().add(param); } } } List<Protocol> protocols = parseProtocols(root); String keepBytesStr = root.getChildText("keepBytes", VOS_NS); if (keepBytesStr != null) { boolean keepBytes = true; keepBytes = keepBytesStr.equalsIgnoreCase("true"); return new Transfer(target, direction, view, protocols, keepBytes); } return new Transfer(target, direction, view, protocols); }
From source file:ca.nrc.cadc.vosi.avail.CheckWebService.java
License:Open Source License
void checkReturnedXml(String strXml) throws CheckException { Document doc; String xpathStr;/*from w w w . ja v a 2s . c o m*/ try { StringReader reader = new StringReader(strXml); doc = XmlUtil.buildDocument(reader, schemaMap); //get namespace and/or prefix from Document, then create xpath based on the prefix String nsp = doc.getRootElement().getNamespacePrefix(); //Namespace Prefix if (nsp != null && nsp.length() > 0) nsp = nsp + ":"; else nsp = ""; xpathStr = "/" + nsp + "availability/" + nsp + "available"; XPathBuilder<Element> builder = new XPathBuilder<Element>(xpathStr, Filters.element()); Namespace ns = Namespace.getNamespace(VOSI.NS_PREFIX, VOSI.AVAILABILITY_NS_URI); builder.setNamespace(ns); XPathExpression<Element> xpath = builder.compileWith(XPathFactory.instance()); Element eleAvail = xpath.evaluateFirst(doc); log.debug(eleAvail); String textAvail = eleAvail.getText(); // TODO: is this is actually valid? is the content not constrained by the schema? if (textAvail == null) throw new CheckException(wsURL + " output is invalid: no content in <available> element", null); if (!textAvail.equalsIgnoreCase("true")) { xpathStr = "/" + nsp + "availability/" + nsp + "note"; builder = new XPathBuilder<Element>(xpathStr, Filters.element()); builder.setNamespace(ns); xpath = builder.compileWith(XPathFactory.instance()); Element eleNotes = xpath.evaluateFirst(doc); String textNotes = eleNotes.getText(); throw new CheckException("service " + wsURL + " is not available, reported reason: " + textNotes, null); } } catch (IOException e) { // probably an incorrect setup or bug in the checks throw new RuntimeException("failed to test " + wsURL, e); } catch (JDOMException e) { throw new CheckException(wsURL + " output is invalid", e); } }
From source file:ca.nrc.cadc.vosi.Availability.java
License:Open Source License
public AvailabilityStatus fromXmlDocument(Document doc) throws ParseException { Namespace vosi = Namespace.getNamespace("vosi", VOSI.AVAILABILITY_NS_URI); Element availability = doc.getRootElement(); if (!availability.getName().equals("availability")) throw new IllegalArgumentException("missing root element 'availability'"); Element elemAvailable = availability.getChild("available", vosi); if (elemAvailable == null) throw new IllegalArgumentException("missing element 'available'"); boolean available = elemAvailable.getText().equalsIgnoreCase("true"); DateFormat df = DateUtil.getDateFormat(DateUtil.IVOA_DATE_FORMAT, DateUtil.UTC); Element elemUpSince = availability.getChild("upSince", vosi); Element elemDownAt = availability.getChild("downAt", vosi); Element elemBackAt = availability.getChild("backAt", vosi); Element elemNote = availability.getChild("note", vosi); Date upSince = null;// ww w . j a v a 2 s . co m Date downAt = null; Date backAt = null; String note = null; if (elemUpSince != null) upSince = df.parse(elemUpSince.getText()); if (elemDownAt != null) downAt = df.parse(elemDownAt.getText()); if (elemBackAt != null) backAt = df.parse(elemBackAt.getText()); if (elemNote != null) note = elemNote.getText(); return new AvailabilityStatus(available, upSince, downAt, backAt, note); }