Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

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

Prototype

public Document(List<? extends Content> content) 

Source Link

Document

This will create a new Document, with the supplied list of content, and a DocType declaration only if the content contains a DocType instance.

Usage

From source file:org.yawlfoundation.yawl.scheduling.FormGenerator.java

License:Open Source License

private void outFormPriv() throws Exception {
    String reschedulingKey = request.getParameter("reschedulingKey");
    source = request.getParameter("source");
    String itemid = request.getParameter("workitem");
    String handle = request.getParameter("handle");
    String participantid = request.getParameter("participantid");

    try {/*  w ww.  ja va  2s. c  o  m*/
        Participant participant = rs.getParticipant(participantid);
        userName = participant.getFullName();
    } catch (Exception e) {
        _log.error("Cannot get username for participant id: " + participantid, e);
    }

    if (!rs.isValidUserSession(handle)) {
        _log.warn("User handle is invalid: " + handle + ", redirecting to start page...");
        redirect(source.substring(0, source.lastIndexOf("/")));
    }

    wirElement = Utils.string2Element(rs.getWorkItem(itemid, handle));

    String caseId = Utils.extractCaseId(wirElement.getChildText("caseid"));
    String taskId = wirElement.getChildText("taskid");
    String taskName = taskId.substring(0, taskId.lastIndexOf("_"));

    List<Element> children = wirElement.getChild("updateddata").getChildren();
    Element task = (children.isEmpty() ? null : children.get(0));
    if (task == null) {
        children = wirElement.getChild("data").getChildren();
        task = (children.isEmpty() ? null : children.get(0));
    }

    boolean complete = request.getParameter("Complete") != null;
    boolean completeForce = request.getParameter("CompleteForce") != null
            && !request.getParameter("CompleteForce").isEmpty();
    boolean save = reschedulingKey != null || request.getParameter("Save") != null;
    boolean confirmReservations = request.getParameter("ConfirmReservations") != null;
    boolean cancel = request.getParameter("Cancel") != null;
    boolean language = request.getParameter(LANGUAGE_ATTRIBUTE_NAME) != null
            && !request.getParameter(LANGUAGE_ATTRIBUTE_NAME).isEmpty();
    isShortForm = Boolean.parseBoolean(task.getChildText("shortForm"));
    canConfirmReservations = Boolean.parseBoolean(task.getChildText("canConfirmReservations"));
    _log.debug("cancel,save,confirmReservations,complete,language,isShortForm,canConfirmReservations=" + cancel
            + "," + save + "," + confirmReservations + "," + complete + "," + language + "," + isShortForm + ","
            + canConfirmReservations);

    if (cancel) {
        redirect();
    } else if (completeForce) {
        completeWorkitem(taskName, itemid, handle);
    } else if (complete || save || language || confirmReservations) {
        Case cas = ss.loadCase(caseId);
        Document rup = cas.getRUP();
        Document rupOriginal = new Document(
                Utils.string2Element(Utils.element2String(rup.getRootElement(), false)));
        String msgDB = "customForm";
        activities = XMLUtils.getXMLObjects(rup, XMLUtils.getXPATH_Activities());

        updateRUPFromRequest(rup);

        // set times of rup if rescheduling required
        if (reschedulingRUPAfterEditInCustomForm && reschedulingKey != null && !reschedulingKey.isEmpty()) {
            String activityName = reschedulingKey.substring((XML_ACTIVITY + "_").length());
            activityName = activityName.substring(0, activityName.indexOf("_"));
            List<Element> activities = XMLUtils.getXMLObjects(rup, XMLUtils.getXPATH_Activities(activityName));
            if (!activities.isEmpty()) {
                scheduler.setTimes(rup, activities.get(0), !isShortForm, false, null);
            }
        }

        // reschedule rup at complete of short custom form
        if (isShortForm && (complete || save || confirmReservations)) {
            scheduler.findTimeSlot(rup, !isShortForm);
        }

        // full xsd validation only, if explicit datatype validation has not found any errors
        if (!XMLUtils.hasErrors(rup.getRootElement())) {
            validateXSD(rup);
        }

        if (confirmReservations) {
            String xpath = XMLUtils.getXPATH_Activities();
            List<Element> activities = XMLUtils.getXMLObjects(rup, xpath);
            for (Element activity : activities) {
                List<Element> reservations = activity.getChildren(XML_RESERVATION);
                for (Element reservation : reservations) {
                    if (RESOURCE_STATUS_REQUESTED.equals(reservation.getChildText(XML_STATUSTOBE))) {
                        reservation.getChild(XML_STATUSTOBE).setText(RESOURCE_STATUS_RESERVED);
                    }
                }
            }
        }

        try {
            ss.checkRelations(rup);
            rup = rs.saveReservations(rup, !complete && !confirmReservations, true);
        } catch (Exception e) {
            _log.error("Exception", e);
            XMLUtils.addErrorValue(rup.getRootElement(), !isShortForm, "msgRUPSaveRSError", e.getMessage());
        }

        boolean haveTosave = XMLUtils.different(rupOriginal.getRootElement(), rup.getRootElement());
        if (haveTosave && (complete || save || confirmReservations)) {
            try {
                ss.saveRupToDatabase(caseId, userName, rup, msgDB);
                haveTosave = false;
            } catch (Exception e) {
                XMLUtils.addErrorValue(rup.getRootElement(), true, "msgRUPSaveDBError", e.getMessage());
            }
        } else {
            _log.debug("Don't have to save rup");
        }

        if (complete) {
            ss.startMessageTransfers(caseId, rup);
        }

        if (complete && !XMLUtils.hasErrors(rup.getRootElement())) {
            completeWorkitem(taskName, itemid, handle);
        } else {
            activities = XMLUtils.getXMLObjects(rup, XMLUtils.getXPATH_Activities());
            buffer.append(getForm(cas, haveTosave));

            // show javascript alert to confirm the completing of work item
            if (complete) {
                bufferTop.append(" msgCompleteForce=\"").append(config.getLocalizedString("msgCompleteForce"))
                        .append("\";\r\n");
                bufferBottom.append(" completeForce();\r\n");
            }
        }
    } else { // first call
        Case cas = ss.loadCase(caseId);
        Document rup = cas.getRUP();
        Document rupOriginal = new Document(
                Utils.string2Element(Utils.element2String(rup.getRootElement(), false)));
        Set<String> addedActivityNames = new HashSet<String>();

        // extend RUP from model specification
        ss.extendRUPFromYAWLModel(rup, addedActivityNames);

        // extend RUP with variable from YAWL
        addedActivityNames.addAll(ss.getDiffActivityNames(rup.getRootElement(), task.getChild(XML_RUP)));
        if (XMLUtils.mergeElements(rup.getRootElement(), task.getChild(XML_RUP))) {
            _log.info("extend rup for case " + caseId + " from YAWL variable: "
                    + Utils.document2String(rup, false));
        }

        // extend RUP with historical data
        ss.completeRupFromHistory(rup, addedActivityNames);

        boolean haveToSave = XMLUtils.different(rupOriginal.getRootElement(), rup.getRootElement());
        validateAllElements(rup.getRootElement());
        activities = XMLUtils.getXMLObjects(rup, XMLUtils.getXPATH_Activities());
        buffer.append(getForm(cas, haveToSave));
    }
}

From source file:org.yawlfoundation.yawl.scheduling.PlanningGraphCreator.java

License:Open Source License

@SuppressWarnings("unchecked")
/**//from w w  w  . j  av a2 s  .  c  o m
 * TODO@tbe: determine order of activities, store them as utilisation relations and sort
 * activities according to utilisation relations
 */
public Collection<Element> getActivityElements(String caseId)
        throws IOException, JDOMException, JaxenException {
    Element element = SchedulingService.getInstance().getSpecificationForCase(caseId);
    Document doc = new Document(element);

    Map<String, String> map = new HashMap<String, String>();
    map.put("bla", element.getNamespace().getURI());
    for (Object o : element.getAdditionalNamespaces()) {
        Namespace ns = (Namespace) o;
        map.put(ns.getPrefix(), ns.getURI());
    }

    org.jaxen.XPath xp = new JDOMXPath("//bla:expression/@query");
    xp.setNamespaceContext(new SimpleNamespaceContext(map));
    List<Attribute> list = xp.selectNodes(doc);
    List<String> activityNames = new ArrayList<String>();
    for (Attribute e : list) {
        String value = e.getValue();
        int startIndex = value.indexOf("<" + XML_ACTIVITYNAME + ">");
        int endIndex = value.indexOf("</" + XML_ACTIVITYNAME + ">");
        while (startIndex >= 0 && endIndex > startIndex) {
            if (!value.startsWith("<" + XML_EVENT_RECEIVE + ">")) {
                String activityName = value.substring(startIndex + lenActName, endIndex).trim();

                // ignore XPath expressions
                if (!activityName.contains("/") && !activityNames.contains(activityName)) {
                    activityNames.add(activityName);
                }
            }
            value = value.substring(endIndex + lenActName);
            startIndex = value.indexOf("<" + XML_ACTIVITYNAME + ">");
            endIndex = value.indexOf("</" + XML_ACTIVITYNAME + ">");
        }
    }

    //TODO@tbe: sort activities, only until order of activities can be determined from process model
    final List<String> possibleActivities = Utils
            .parseCSV(PropertyReader.getInstance().getSchedulingProperty("possibleActivitiesSorted"));
    Collections.sort(activityNames, new Comparator<String>() {
        public int compare(String a1, String a2) {
            if (possibleActivities.indexOf(a1) < 0) {
                return -1; // set missing activities at beginning
            } else if (possibleActivities.indexOf(a2) < 0) {
                return 1; // set missing activities at beginning
            } else {
                return possibleActivities.indexOf(a1) - possibleActivities.indexOf(a2);
            }
        }
    });
    logger.debug("activityNames: " + Utils.toString(activityNames));

    Collection<Element> activities = new ArrayList<Element>();
    Element preRelation = null; // relation of previous activity
    for (int i = 0; i < activityNames.size(); i++) {
        String activityName = activityNames.get(i);
        if (i > 0) {
            preRelation.getChild(XML_OTHERACTIVITYNAME).setText(activityName);
        }

        Element activity = FormGenerator.getTemplate(XML_ACTIVITY);
        activities.add(activity);
        activity.getChild(XML_ACTIVITYNAME).setText(activityName);

        if (i < activityNames.size() - 1) {
            preRelation = FormGenerator.getTemplate(XML_UTILISATIONREL);
            activity.addContent(preRelation);
        }
    }
    return activities;
}

From source file:org.yawlfoundation.yawl.scheduling.resource.ResourceServiceInterface.java

License:Open Source License

/**
 * Saves all reservation XML elements of the ResourceUtilisationPlan,
 * depending on "reservation.planningStatus" (see rup.xsd for the XML data
 * model) and removes or updates older reservations for the case and for each
 * activity. Then sets planning status and error or warning values on XML
 * elements (e.g. if a resource cannot be reserved or technical errors occur)
 * and returns the ResourceUtilisationPlan.
 * //from   w  w  w  .ja va  2s.c o m
 * @param rup
 * @param checkOnly
 * @param resourceChange
 */
public Document saveReservations(Document rup, boolean checkOnly, boolean resourceChange)
        throws ResourceGatewayException, JDOMException, IOException {
    String caseId = null;

    try {
        caseId = XMLUtils.getCaseId(rup);
        Case cas = new Case(caseId);
        cas.readCaseData(caseId);
    } catch (IOException e) {
        _log.warn("Failed to save RUP for case Id  " + caseId + ", " + e.getMessage());
        return rup;
    }

    // remove unchecked reservations, because RS cannot handle them, readd
    // them after save in RS
    Map<String, List<Element>> resUnchecked = removeReservations(rup, RESOURCE_STATUS_UNCHECKED);

    if (resourceChange) {

        // remove and readd all reservations, because resource changes cannot
        // be updated in RS
        Map<String, List<Element>> resAll = removeReservations(rup, null);
        try {
            String rupStr = Utils.element2String(rup.getRootElement(), false);
            rupStr = _calClient.saveReservations(rupStr, false, getHandle());
            rup = new Document(Utils.string2Element(rupStr));
        } catch (Exception e) {
            _log.error("cannot save empty rup", e);
        } finally {
            addReservations(rup, resAll);
        }
    }

    try {
        // remove errors from root element and reservations to avoid cancelling
        // of save in RS
        XMLUtils.removeAttribute(rup.getRootElement(), XML_ERROR);
        XMLUtils.removeAttribute(rup.getRootElement(), XML_WARNING);

        String xpath = XMLUtils.getXPATH_ActivityElement(null, XML_RESERVATION, null);
        List<Element> reservations = XMLUtils.getXMLObjects(rup, xpath);
        for (Element reservation : reservations) {
            XMLUtils.removeAttributes(reservation, XML_ERROR);
            XMLUtils.removeAttributes(reservation, XML_WARNING);
        }

        if (DEBUG_SAVE_TO_RS) {
            _log.debug("checkOnly=" + checkOnly + ", resourceChange=" + resourceChange + ", save rup in RS: "
                    + Utils.document2String(rup, true));
        }
        String rupStr = Utils.element2String(rup.getRootElement(), false);
        rupStr = _calClient.saveReservations(rupStr, checkOnly, getHandle());
        rup = new Document(Utils.string2Element(rupStr));
        if (DEBUG_SAVE_TO_RS) {
            _log.debug("saved rup from RS: " + Utils.document2String(rup, true));
        }
    } finally {
        // add formerly removed unchecked reservations
        addReservations(rup, resUnchecked);
    }
    return rup;
}

From source file:org.yawlfoundation.yawl.scheduling.SchedulingService.java

License:Open Source License

public Case loadCase(String caseId) throws SQLException {
    Case caseToLoad;//from   ww w  .  j ava  2  s . com

    List<Case> cases = _dataMapper.getRupByCaseId(caseId);
    if (cases.isEmpty()) {
        Element rupElement = new Element(XML_RUP);
        Document doc = new Document(rupElement);

        // add caseId to the RUP
        Element caseIdElem = XMLUtils.getElement(doc, XML_RUP + "/" + XML_CASEID);
        if (caseIdElem == null) {
            caseIdElem = new Element(XML_CASEID);
            doc.getRootElement().addContent(caseIdElem);
        }
        caseIdElem.setText(caseId);

        caseToLoad = new Case(caseId, null, null, doc);
        _log.info("Created empty RUP for case Id " + caseId + ", " + caseToLoad.getRupAsString());
    } else {
        caseToLoad = cases.get(0);
        _log.info("Loaded RUP for case Id " + caseId + " from database: " + caseToLoad.getRupAsString());
    }

    return caseToLoad;
}

From source file:org.yawlfoundation.yawl.util.SaxonUtil.java

License:Open Source License

/**
 * Evaluates an XQuery against a data document
 * @param query the XQuery to evaluate//  ww w .  j a  v a  2 s . c o  m
 * @param dataElem a JDOM Element containing the data tree
 * @return a List containing the Element(s) resulting from the evaluation
 * @throws SaxonApiException if there's a problem with the XQuery or Element
 */
public static List<Content> evaluateListQuery(String query, Element dataElem) throws SaxonApiException {

    // put the element in a jdom document
    Document dataDoc = new Document(dataElem.clone());
    String result = evaluateQuery(query, dataDoc);

    // use the string result to create a doc to get it expressed as an element list
    Document resultDoc = JDOMUtil.stringToDocument(StringUtil.wrap(result, "root"));
    return resultDoc.getRootElement().cloneContent();
}

From source file:org.yawlfoundation.yawl.util.YPredicateParser.java

License:Open Source License

/**
 * Evaluates an XQuery//from  w w w .  ja v a  2s  .  c o  m
 * @param s the query expression
 * @param data XML'd data that may be referenced by the expression. May be null if
 * the expression doesn't reference any data
 * @return the result of the evaluation, or "__evaluation_error__" if there's a
 * problem evaluating the expression
 */
protected String evaluateXQuery(String s, Element data) {
    return evaluateXQuery(s, new Document(data.clone()));

}

From source file:org.yawlfoundation.yawl.worklet.exception.HandlerRunner.java

License:Open Source License

/**
* writes the node id's for the nodes returned from the rdr search
* and the data for the current workitem, to a file for later
* input into the 'add rule' process, if required
*//*from   w w  w . j  a v  a  2 s  .c o m*/
public void saveSearchResults() {

    // create the required components for the output file
    Document doc = new Document(new Element("searchResult"));
    Element eLastNode = new Element("lastNode");
    Element eSatisfied = new Element("satisfied");
    Element eTested = new Element("tested");
    Element eId = new Element("id");
    Element eSpecid = new Element("specid");
    Element eSpecVersion = new Element("specversion");
    Element eSpecURI = new Element("specuri");
    Element eTaskid = new Element("taskid");
    Element eCaseid = new Element("caseid");
    Element eCaseData = new Element("casedata");
    Element eReason = new Element("extype");
    Element eWorklets = new Element("worklets");

    try {
        // transfer the workitem's data items to the file
        for (Element e : getDatalist().getChildren()) {
            eCaseData.addContent(e.clone());
        }

        // set values for case identifiers
        eSpecid.setText(_parentMonitor.getSpecID().getIdentifier());
        eSpecVersion.setText(_parentMonitor.getSpecID().getVersionAsString());
        eSpecURI.setText(_parentMonitor.getSpecID().getUri());
        eCaseid.setText(_parentMonitor.getCaseID());

        if (_wir != null) {
            // set values for the workitem identifiers (item-level exception)
            eId.setText(_wir.getID());
            eTaskid.setText(Library.getTaskNameFromId(_wir.getTaskID()));
        }

        // add the worklet names and case ids
        for (String wName : _runners.getAllWorkletNames()) {
            Element eWorkletName = new Element("workletName");
            Element eRunningCaseId = new Element("runningcaseid");
            Element eWorklet = new Element("worklet");
            eWorkletName.setText(wName);
            eRunningCaseId.setText(_runners.getCaseID(wName));
            eWorklet.addContent(eWorkletName);
            eWorklet.addContent(eRunningCaseId);
            eWorklets.addContent(eWorklet);
        }

        eReason.setText(String.valueOf(_reasonType));

        // add the nodeids to the relevent elements
        eSatisfied.setText(_searchPair.getLastTrueNode().getNodeIdAsString());
        eTested.setText(_searchPair.getLastEvaluatedNode().getNodeIdAsString());
        eLastNode.addContent(eSatisfied);
        eLastNode.addContent(eTested);

        // add the elements to the document
        Element root = doc.getRootElement();
        root.addContent(eId);
        root.addContent(eSpecid);
        root.addContent(eSpecVersion);
        root.addContent(eSpecURI);
        root.addContent(eTaskid);
        root.addContent(eCaseid);
        root.addContent(eWorklets);
        root.addContent(eReason);
        root.addContent(eLastNode);
        root.addContent(eCaseData);

        // create the output file
        saveDocument(createFileName(), doc);
    } catch (IllegalAddException iae) {
        _log.error("Exception when adding content", iae);
    }
}

From source file:org.yawlfoundation.yawl.worklet.support.ConditionEvaluator.java

License:Open Source License

/**
 *  PARSING METHODS/*from  ww  w  . j  a  v  a 2 s . c  o  m*/
 */

private String evaluateXQuery(String expr, Element data) throws RdrConditionException {
    try {
        if (expr.startsWith("{"))
            expr = deQuote(expr); // remove braces
        String query = String.format("boolean(%s)", expr);
        return SaxonUtil.evaluateQuery(query, new Document(data.clone()));
    } catch (SaxonApiException sae) {
        throw new RdrConditionException("Invalid XPath expression (" + expr + ").");
    }
}

From source file:org.yawlfoundation.yawl.worklet.support.WorkletRecord.java

License:Open Source License

/**
 * writes the node id's for the nodes returned from the rdr search
 * and the data for the current workitem, to a file for later
 * input into the 'add rule' process, if required
 *//* w w w  .j a v  a 2  s . com*/
public void saveSearchResults() {

    // create the required components for the output file
    Document doc = new Document(new Element("searchResult"));
    Element eLastNode = new Element("lastNode");
    Element eSatisfied = new Element("satisfied");
    Element eTested = new Element("tested");
    Element eId = new Element("id");
    Element eSpecid = new Element("specid");
    Element eSpecVersion = new Element("specversion");
    Element eSpecURI = new Element("specuri");
    Element eTaskid = new Element("taskid");
    Element eCaseid = new Element("caseid");
    Element eCaseData = new Element("casedata");
    Element eReason = new Element("extype");
    Element eWorklets = new Element("worklets");

    try {
        // transfer the workitem's data items to the file
        for (Element dataItem : _datalist.getChildren()) {
            eCaseData.addContent(dataItem.clone());
        }

        //set values for the workitem identifiers
        eId.setText(_wir.getID());
        eSpecid.setText(_wir.getSpecIdentifier());
        eSpecVersion.setText(_wir.getSpecVersion());
        eSpecURI.setText(_wir.getSpecURI());
        eTaskid.setText(_wir.getTaskName());
        eCaseid.setText(_wir.getCaseID());
        eReason.setText(String.valueOf(_reasonType));

        // add the worklet names and case ids
        for (String wName : _runners.getAllWorkletNames()) {
            Element eWorkletName = new Element("workletName");
            Element eRunningCaseId = new Element("runningcaseid");
            Element eWorklet = new Element("worklet");
            eWorkletName.setText(wName);
            eRunningCaseId.setText(_runners.getCaseID(wName));
            eWorklet.addContent(eWorkletName);
            eWorklet.addContent(eRunningCaseId);
            eWorklets.addContent(eWorklet);
        }

        // add the nodeids to the relevent elements
        eSatisfied.setText(_searchPair.getLastTrueNode().getNodeIdAsString());
        eTested.setText(_searchPair.getLastEvaluatedNode().getNodeIdAsString());
        eLastNode.addContent(eSatisfied);
        eLastNode.addContent(eTested);

        // add the elements to the document
        Element root = doc.getRootElement();
        root.addContent(eId);
        root.addContent(eSpecid);
        root.addContent(eSpecVersion);
        root.addContent(eSpecURI);
        root.addContent(eTaskid);
        root.addContent(eCaseid);
        root.addContent(eWorklets);
        root.addContent(eReason);
        root.addContent(eLastNode);
        root.addContent(eCaseData);

        // create the output file
        saveDocument(createFileName(), doc);
    } catch (IllegalAddException iae) {
        WorkletRecord._log.error("Exception when adding content", iae);
    }
}

From source file:par5e.ModuleXML.java

public ModuleXML() {
    Comment comment = new Comment("Generated by PAR5E - Fantasy Grounds Module Parser - Zeus Copyright 2014");

    root = new Element("root");
    root.setAttribute("version", "3.0");
    doc = new Document(root);
    doc.addContent(0, comment);//w ww  .  jav  a  2 s .c  o m

    //doc.setRootElement(root);
}