Example usage for org.jdom2 Element getChildText

List of usage examples for org.jdom2 Element getChildText

Introduction

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

Prototype

public String getChildText(final String cname) 

Source Link

Document

Returns the textual content of the named child element, or null if there's no such child.

Usage

From source file:org.yawlfoundation.yawl.scheduling.lanes.LaneImporter.java

License:Open Source License

private void update(Element resource, String resType, String resourceId, String categoryOrRoleId) {
    if (resourceId.equals(resource.getChildText(XML_ID))) {
        return; // no resource update necessary
    }/*w w w.  j ava2s. co m*/

    if (resourceId.equals("virtual")) {
        resource.getChild(XML_ID).setText("");
        resource.getChild(resType).setText(categoryOrRoleId);
    } else {
        resource.getChild(XML_ID).setText(resourceId);
    }

    // remove reservationId to force cancellation and new creation of reservation
    // in RS, because resource changes cannot be updated in RS
    Element reservation = resource.getParentElement();
    if (reservation.getChild(XML_RESERVATIONID) != null) {
        reservation.getChild(XML_RESERVATIONID).setText("");
    } else {
        resource.addContent(new Element(XML_RESERVATIONID));
    }
}

From source file:org.yawlfoundation.yawl.scheduling.lanes.LaneProducer.java

License:Open Source License

public List<List<Map<String, Object>>> getLanes(String... dates) throws Exception {
    Date from, to;/*  w w  w .  ja  v a  2 s . co m*/
    int count = 0;

    // show intraoperative activities only
    String possibleActivitiesSorted = PropertyReader.getInstance()
            .getSchedulingProperty("possibleActivitiesSorted");
    String[] possibleActivities = Utils.parseCSV(possibleActivitiesSorted).toArray(new String[0]);

    // return dates in same order as given
    List<List<Map<String, Object>>> allLanes4AllDates = new ArrayList<List<Map<String, Object>>>();
    for (String date : dates) {
        List<Map<String, Object>> allLanes4Date = (List<Map<String, Object>>) Utils.deepCopy(lanes);
        //logger.debug("date="+date+", allLanes4Date "+Utils.toString(allLanes4Date));

        // lane goes from 00:00:00.001 bis 23:59:59.999
        long tmp = Utils.string2Date(date, Utils.DATE_PATTERN_XML).getTime();
        from = new Date(tmp - 1);
        to = new Date(tmp + 24 * 60 * 60 * 1000);
        List<Case> cases = dataMapper.getRupsByInterval(from, to, null, false);
        logger.debug("found " + cases.size() + " cases for date " + date);

        for (Case cas : cases) {
            try {
                String xpath = XMLUtils.getXPATH_Activities(possibleActivities);
                List<Element> activities = XMLUtils.getXMLObjects(cas.getRUP(), xpath);
                if (activities.isEmpty()) {
                    continue;
                }

                // get original FROM and TO date
                Date originalEarlFrom = XMLUtils.getDateValue(activities.get(0).getChild(XML_FROM), false);
                Date originalLatestTo = XMLUtils
                        .getDateValue(activities.get(activities.size() - 1).getChild(XML_TO), false);

                // set times for showable in OP plan, if no duration given, set 5 min as default
                Element earlFrom = XMLUtils.getEarliestBeginElement(cas.getRUP(), possibleActivities);
                Element latestTo = XMLUtils.getLatestEndElement(cas.getRUP(), possibleActivities);
                scheduler.setTimes(cas.getRUP(),
                        earlFrom == null ? latestTo.getParentElement() : earlFrom.getParentElement(), false,
                        false, Utils.stringXML2Duration("PT5M"));
                earlFrom = XMLUtils.getEarliestBeginElement(cas.getRUP(), possibleActivities);
                latestTo = XMLUtils.getLatestEndElement(cas.getRUP(), possibleActivities);

                Map<String, Object> processUnit = new HashMap<String, Object>();
                put(processUnit, "caseId", cas.getCaseId());
                put(processUnit, "title", cas.getCaseName());
                put(processUnit, "start",
                        Utils.date2String(XMLUtils.getDateValue(earlFrom, false), "yyyy-MM-dd HH:mm:ss"));
                put(processUnit, "end",
                        Utils.date2String(XMLUtils.getDateValue(latestTo, false), "yyyy-MM-dd HH:mm:ss"));
                put(processUnit, "hasConflicts", false); // TODO@tbe: has rup conflicts ?
                put(processUnit, "hasErrors", XMLUtils.hasErrors(cas.getRUP().getRootElement()));
                put(processUnit, "hasWarnings", XMLUtils.hasWarnings(cas.getRUP().getRootElement()));
                //put(processUnit, "canBeEdited", true); // TODO@tbe: false wenn schon gestartet oder kein YAWL-Case mehr vorhanden, noch im OP-Plan erweitern

                Map<String, Object> data = new HashMap<String, Object>();
                //put(data, "description", cas.getId() + ": " + cas.getPatientFullName() + (cas.getPatientSex()==null ? "" : " (" + cas.getPatientSex() + ")"));
                put(data, "description", "" + ": " + cas.getCaseDescription());
                put(data, "note0", "xxx");
                if (debug)
                    put(data, "note1", originalEarlFrom == null ? "???"
                            : Utils.date2String(originalEarlFrom, "HH:mm dd.MM.yyyy") + " - ");
                if (debug)
                    put(data, "note2", originalLatestTo == null ? "???"
                            : Utils.date2String(originalLatestTo, "HH:mm dd.MM.yyyy"));
                put(data, "note3", cas.getCaseId()); // YAWL-CaseId
                put(data, "note4", ""); // reserved for title
                put(data, "note5", ""); // reserved for activityNames
                put(data, "note6", ""); // reserved for activityNames
                put(data, "note7", ""); // reserved for activityNames
                put(data, "note8", ""); // reserved for activityNames
                put(data, "note9", ""); // reserved for activityNames

                put(processUnit, "data", data);

                List<Map<String, Object>> stages = new ArrayList<Map<String, Object>>();
                Long firstActFrom = null;
                int note = 0;
                for (Element activity : activities) {
                    String activityName = activity.getChildText(XML_ACTIVITYNAME);
                    Date actFrom = XMLUtils.getDateValue(activity.getChild(XML_FROM), true);
                    if (firstActFrom == null) {
                        firstActFrom = actFrom.getTime();
                    }

                    if (debug) {
                        put(data, "note" + (note + 5), activityName);
                        note++;
                    }

                    Map<String, Object> stage = new HashMap<String, Object>();
                    put(stage, "id", "stage-" + activityName);
                    put(stage, "title", config.getLocalizedString(activityName));
                    put(stage, "start", Utils.date2String(actFrom, Utils.DATETIME_PATTERN));
                    put(stage, "offset", (actFrom.getTime() - firstActFrom) / 1000 / 60);
                    put(stage, "running",
                            UTILISATION_TYPE_BEGIN.equals(activity.getChildText(XML_REQUESTTYPE)));
                    stages.add(stage);
                }

                put(processUnit, "stages", stages);

                // find matching lanes
                xpath = XMLUtils.getXPATH_ActivitiesElement(possibleActivities, XML_RESERVATION, null);
                List<Element> reservations = XMLUtils.getXMLObjects(cas.getRUP(), xpath);
                List<Map<String, Object>> lanes4Date = getMatchingLanes(reservations, allLanes4Date);
                logger.debug(lanes4Date.size() + " lanes found for caseId: " + cas.getCaseId());

                for (Map<String, Object> lane4Date : lanes4Date) {
                    List<Map<String, Object>> processUnits = (List) lane4Date.get("processUnits");
                    if (processUnits == null) {
                        processUnits = new ArrayList<Map<String, Object>>();
                    }
                    if (debug)
                        put(data, "note4", lane4Date.get("title"));
                    Map<String, Object> processUnitCopy = (Map<String, Object>) Utils.deepCopy(processUnit);
                    put(processUnitCopy, "id", "id" + processUnitCopy.get("caseId") + "-" + count++);
                    processUnits.add(processUnitCopy);
                    put(lane4Date, "processUnits", processUnits);
                }
            } catch (Throwable e) {
                logger.error("cannot show case: " + cas.getCaseId(), e);
            }
        }
        allLanes4AllDates.add(allLanes4Date);
    }
    return allLanes4AllDates;
}

From source file:org.yawlfoundation.yawl.scheduling.lanes.LaneProducer.java

License:Open Source License

/**
 * lanes finden durch prfen von rolle bzw. category 
 *///from w w w . j ava 2s.c  o  m
private List<Map<String, Object>> getMatchingLanes(List<Element> reservations,
        List<Map<String, Object>> allLanes4Date) {
    List<Map<String, Object>> lanes4Date = new ArrayList<Map<String, Object>>();
    for (Map<String, Object> lane4Date : allLanes4Date) {
        for (Element reservation : reservations) {
            try {
                String statusToBe = reservation.getChildText(XML_STATUSTOBE);
                if (!statusToBe.equals(RESOURCE_STATUS_REQUESTED)
                        && !statusToBe.equals(RESOURCE_STATUS_RESERVED)) {
                    continue;
                }

                int workload = Integer.parseInt(reservation.getChildText(XML_WORKLOAD));
                if (workload == 0) {
                    continue;
                }

                Element resource = reservation.getChild(XML_RESOURCE);
                String resourceId = resource.getChildText(XML_ID);
                String categoryId = resource.getChildText(XML_CATEGORY);
                String roleId = resource.getChildText(XML_ROLE);
                Object laneId = lane4Date.get("id");
                //logger.debug("resourceId="+resourceId+", categoryId="+categoryId+", roleId="+roleId+", laneId="+laneId);
                if (!"virtual".equals(laneId) && resourceId.equals(laneId)) { // match by Id
                    lanes4Date.add(lane4Date);
                    //logger.debug("match by Id, resourceId="+resourceId+", laneId="+lane4Date.get("id"));
                    break;
                } else if (resourceId.isEmpty() && "virtual".equals(laneId)) {
                    if (categoryId.equals(this.categoryId)) { // match by category
                        lanes4Date.add(lane4Date);
                        //logger.debug("match by category, categoryId="+categoryId);
                        break;
                    } else if (roleId.equals(this.roleId)) { // match by role
                        lanes4Date.add(lane4Date);
                        //logger.debug("match by role, roleId="+roleId);
                        break;
                    }
                }
            } catch (Exception e) {
                logger.error("cannot search for matching lane", e);
            }
        }
    }

    // if no lane found (means that no matching resource was defined in rup) then add to virtualLane 
    if (lanes4Date.isEmpty()) {
        Map<String, Object> virtualLane4Date = allLanes4Date.get(allLanes4Date.size() - 1);
        lanes4Date.add(virtualLane4Date);
    }

    return lanes4Date;
}

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

License:Open Source License

public Map<String, List<Element>> removeReservations(Document rup, String statusToBe) throws JDOMException {
    Map<String, List<Element>> res = new HashMap<String, List<Element>>();
    String where = statusToBe == null ? "" : "[" + XML_STATUSTOBE + "='" + statusToBe + "']";
    String xpath = XMLUtils.getXPATH_ActivityElement(null, XML_RESERVATION + where, null);
    List<Element> reservations = XMLUtils.getXMLObjects(rup, xpath);
    for (Element reservation : reservations) {
        Element activity = reservation.getParentElement();
        activity.removeContent(reservation);

        List<Element> l = res.get(activity.getChildText(XML_ACTIVITYNAME));
        if (l == null)
            l = new ArrayList<Element>();

        Element reservationId = reservation.getChild(XML_RESERVATIONID);
        if (reservationId == null) {
            reservation.addContent(new Element(XML_RESERVATIONID));
        } else {//  w  w w  .j a va2s.c  o m
            reservationId.setText("");
        }

        l.add(reservation);
        res.put(activity.getChildText(XML_ACTIVITYNAME), l);
    }

    return res;
}

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

License:Open Source License

public void addReservations(Document rup, Map<String, List<Element>> res) throws JDOMException {
    String xpath = XMLUtils.getXPATH_Activities();
    List<Element> activities = XMLUtils.getXMLObjects(rup, xpath);
    for (Element activity : activities) {
        List<Element> l = res.get(activity.getChildText(XML_ACTIVITYNAME));
        if (l != null) {
            for (Element reservation : l) {
                activity.addContent(reservation);
            }//from  w  w  w  .  j a  v a  2  s .c  o  m
        }
    }
}

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

License:Open Source License

/**
 * set times of activities if FROM and DURATION are given Rescheduling
 * kollidierender RUPs, welche definiert sind als: alle RUPs welche die
 * selben Ressourcen zur gleichen Zeit definieren wie der vorhergehend RUP.
 * als selbe Ressourcen werden nur nicht austauschbare Ressourcen betrachtet,
 * das sind Ressourcen mit Reservierung by Id (TODO@tbe: Reservierungen by
 * Role oder Category knnten auch kollidieren, hier aber erstmal weglassen)
 * TODO@tbe: Rescheduling von RUPs die Leerlaufzeiten haben, z.B. durch
 * frheres ende einer Aktivitt, erstmal nicht betrachten
 * //from w ww.  j  ava2  s.co m
 * @param rup
 * @param activity
 * @param withValidation
 * @param rescheduleCollidingRUPs
 * 
 */
public boolean setTimes(Document rup, Element activity, boolean withValidation, boolean rescheduleCollidingRUPs,
        Duration defaultDuration) {
    String caseId = XMLUtils.getCaseId(rup);
    String activityName = activity.getChildText(XML_ACTIVITYNAME);
    boolean hasRescheduledRUPs = false;

    try {
        // 1) reschedule rup
        setTimes(rup, activity, withValidation, new ArrayList<String>(), defaultDuration);

        // rescheduling colliding rups
        if (rescheduleCollidingRUPs) {
            List<Document> allCollidingRUPs = new ArrayList<Document>();
            List<String> allCollidingRUPCaseIds = new ArrayList<String>();
            allCollidingRUPCaseIds.add(caseId);

            // 2) collect all potential colliding rups and remove their
            // reservations
            List<Document> collidingRUPs = getCollidingRups(rup, allCollidingRUPCaseIds);
            while (!collidingRUPs.isEmpty()) {
                List<Document> newCollidingRUPs = new ArrayList<Document>();
                for (Document collidingRUP : collidingRUPs) {
                    String collCaseId = null;
                    try {
                        collCaseId = XMLUtils.getCaseId(collidingRUP);
                        if (allCollidingRUPCaseIds.contains(collCaseId))
                            continue;

                        // remove all reservations in RS by saving rup without
                        // reservations
                        Map<String, List<Element>> collRes = rs.removeReservations(collidingRUP, null);
                        try {
                            logger.debug("delete reservations from collidingRUP: " + collCaseId);
                            collidingRUP = rs.saveReservations(collidingRUP, false, false);
                        } finally {
                            rs.addReservations(collidingRUP, collRes);
                        }

                        allCollidingRUPs.add(collidingRUP);
                        allCollidingRUPCaseIds.add(collCaseId);

                        newCollidingRUPs.addAll(getCollidingRups(collidingRUP, allCollidingRUPCaseIds));
                    } catch (Exception e) {
                        logger.error("cannot collect caseId: " + (collCaseId == null ? "null" : collCaseId), e);
                        XMLUtils.addErrorValue(rup.getRootElement(), withValidation, "msgRescheduleError",
                                activityName, e.getMessage());
                    }
                }
                collidingRUPs = newCollidingRUPs;
            }

            if (!allCollidingRUPs.isEmpty()) {
                // 3) save rup with new times, should not conflicting with other
                // rups
                // logger.debug("----------------wait 30s and save: "+caseId);
                // Thread.sleep(30000); // FIXME@tbe: raus
                Set<String> errors = SchedulingService.getInstance().optimizeAndSaveRup(rup, "reschedulingRUP",
                        null, false);
                logger.debug("----------------save rescheduled rup caseId: " + caseId + ", errors: "
                        + Utils.toString(errors));
            }

            // 4) sort colliding rups
            Collections.sort(allCollidingRUPs, new Comparator<Document>() {
                public int compare(Document rup1, Document rup2) {
                    Date earlFrom1 = XMLUtils.getEarliestBeginDate(rup1);
                    Date earlFrom2 = XMLUtils.getEarliestBeginDate(rup2);
                    long timeGap = earlFrom1.getTime() - earlFrom2.getTime();
                    if (timeGap > 0)
                        return 1;
                    else if (timeGap < 0)
                        return -1;
                    else
                        return 0;
                }
            });

            // 5) find new time slot for each colliding rup and save it
            for (Document collidingRUP : allCollidingRUPs) {
                String collCaseId = null;
                try {
                    collCaseId = XMLUtils.getCaseId(collidingRUP);
                    if (collCaseId.equals(caseId))
                        continue;

                    // TODO@tbe: so ist nur das suchen eines spteren timeslots
                    // mglich, es sollte auch
                    // ein frherer mglich sein, falls RUP nach vorne verschoben
                    // wurde, dazu evntl.
                    // from auf 00:00 Uhr setzen, dann findTimeSlot aufrufen
                    hasRescheduledRUPs = findTimeSlot(collidingRUP, true) || hasRescheduledRUPs;

                    SchedulingService.getInstance().optimizeAndSaveRup(collidingRUP,
                            "reschedulingCollidingRUPs", null, false);
                    logger.debug("save rescheduled colliding caseId: " + collCaseId + ", errors: "
                            + Utils.toString(XMLUtils.getErrors(collidingRUP.getRootElement())));
                    logger.info("caseId: " + collCaseId + " successfully rescheduled");
                } catch (Exception e) {
                    logger.error("cannot reschedule caseId: " + (collCaseId == null ? "null" : collCaseId), e);
                    XMLUtils.addErrorValue(rup.getRootElement(), withValidation, "msgRescheduleError",
                            activityName, e.getMessage());
                }
            }
        }
    } catch (Exception e) {
        logger.error("error during rescheduling caseId: " + (caseId == null ? "null" : caseId), e);
        XMLUtils.addErrorValue(rup.getRootElement(), withValidation, "msgRescheduleError", activityName,
                e.getMessage());
    }

    return hasRescheduledRUPs;
}

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

License:Open Source License

/**
 * set TO time of an activity depending on FROM and DURATION set FROM time of
 * previous and following activities and recurses to set their TO times also
 * /* w  w  w. ja  v  a2 s  . com*/
 * TODO@tbe: erstmal ohne Beachtung von Max und ohne Ausnutzung des
 * Gummibandes zwischen Min und Max, d.h. es wird Min als fester Wert
 * angenommen, ausserdem wird nur von einer Relation pro Aktivitt
 * ausgegangen
 * 
 * @param activity
 */
private void setTimes(Document rup, Element activity, boolean withValidation,
        List<String> activityNamesProcessed, Duration defaultDuration) {
    String activityName = activity.getChildText(XML_ACTIVITYNAME);
    Element durationElem = activity.getChild(XML_DURATION);
    Duration duration = XMLUtils.getDurationValue(durationElem, withValidation);
    Element from = activity.getChild(XML_FROM);
    Date fromDate = XMLUtils.getDateValue(from, withValidation);
    Element to = activity.getChild(XML_TO);
    Date toDate = XMLUtils.getDateValue(to, withValidation); // can be null
    String requestType = activity.getChildText(XML_REQUESTTYPE);

    if (requestType.equals("EOU")) { // calculate duration
        toDate = XMLUtils.getDateValue(to, withValidation);
        XMLUtils.setDurationValue(durationElem, toDate.getTime() - fromDate.getTime());
    } else if (fromDate == null) {
        if (toDate != null) {
            fromDate = new Date(toDate.getTime());
            if (duration != null) {
                duration.negate().addTo(fromDate);
                XMLUtils.setDateValue(from, fromDate);
            }
        } else if (defaultDuration != null) {
            defaultDuration.negate().addTo(fromDate);
            XMLUtils.setDateValue(from, fromDate);
        }
    } else {
        toDate = new Date(fromDate.getTime());
        if (duration != null) {
            duration.addTo(toDate); // TODO@tbe: if very very long duration, to is
                                    // one hour to high
            XMLUtils.setDateValue(to, toDate);
        } else if (defaultDuration != null) {
            defaultDuration.addTo(toDate);
            XMLUtils.setDateValue(to, toDate);
        }
    }

    activityNamesProcessed.add(activityName);
    logger.debug(activityName + ", set from: " + from.getText() + ", to: " + to.getText() + ", duration: "
            + durationElem.getText());

    // set times of following activities
    String xpath = XMLUtils.getXPATH_ActivityElement(activityName, XML_UTILISATIONREL, null);
    List relations = XMLUtils.getXMLObjects(rup, xpath);
    for (Object o : relations) {
        Element relation = (Element) o;
        String otherActivityName = relation.getChildText(XML_OTHERACTIVITYNAME);
        if (activityNamesProcessed.contains(otherActivityName)) {
            continue; // activity has been processed already
        }

        Duration min = XMLUtils.getDurationValue(relation.getChild(XML_MIN), withValidation);
        List otherActivities = XMLUtils.getXMLObjects(rup, XMLUtils.getXPATH_Activities(otherActivityName));
        for (Object obj : otherActivities) {
            Element otherActivity = (Element) obj;
            Date thisDate;
            if (relation.getChildText(XML_THISUTILISATIONTYPE).equals(UTILISATION_TYPE_BEGIN)) {
                thisDate = fromDate;
            } else if (duration != null) {
                thisDate = toDate;
            } else {
                continue;
            }
            min.addTo(thisDate); // add time gap between activities

            if (relation.getChildText(XML_OTHERUTILISATIONTYPE).equals(UTILISATION_TYPE_END)) {
                Duration otherDuration = XMLUtils.getDurationValue(otherActivity.getChild(XML_DURATION),
                        withValidation);
                (otherDuration == null ? defaultDuration : otherDuration).negate().addTo(thisDate);
            }
            XMLUtils.setDateValue(otherActivity.getChild(XML_FROM), thisDate);

            setTimes(rup, otherActivity, withValidation, activityNamesProcessed, defaultDuration);
        }
    }

    // set time of previous activities if this activity is not started
    if (!requestType.equals("POU")) {
        return;
    }
    xpath = XMLUtils.getXPATH_ActivityElement(null, XML_UTILISATIONREL, null);
    xpath += "[" + XML_OTHERACTIVITYNAME + "/text()='" + activityName + "']";
    relations = XMLUtils.getXMLObjects(rup, xpath);
    for (Object o : relations) {
        Element relation = (Element) o;
        Element otherActivity = relation.getParentElement();
        if (activityNamesProcessed.contains(otherActivity.getChildText(XML_ACTIVITYNAME))) {
            continue; // activity has been processed already
        }

        Duration min = XMLUtils.getDurationValue(relation.getChild(XML_MIN), withValidation);
        Date otherDate;
        if (relation.getChildText(XML_OTHERUTILISATIONTYPE).equals(UTILISATION_TYPE_BEGIN)) {
            fromDate = XMLUtils.getDateValue(from, withValidation);
            otherDate = fromDate;
        } else if (duration != null) {
            toDate = XMLUtils.getDateValue(to, withValidation);
            otherDate = toDate;
        } else {
            continue;
        }
        min.negate().addTo(otherDate);

        if (relation.getChildText(XML_THISUTILISATIONTYPE).equals(UTILISATION_TYPE_END)) {
            Duration otherDuration = XMLUtils.getDurationValue(otherActivity.getChild(XML_DURATION),
                    withValidation);
            (otherDuration == null ? defaultDuration : otherDuration).negate().addTo(otherDate);
        }
        XMLUtils.setDateValue(otherActivity.getChild(XML_FROM), otherDate);

        setTimes(rup, otherActivity, withValidation, activityNamesProcessed, defaultDuration);
    }
}

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

License:Open Source License

/**
 * find time slot for rup/*from  www .  ja va2  s  .  co  m*/
 * 
 * @param rup
 */
public boolean findTimeSlot(Document rup, boolean withValidation) {
    String caseId = XMLUtils.getCaseId(rup);
    logger.debug("reschedule caseId " + caseId);
    boolean isRescheduledRUP = false;

    try {
        // Map with activities and their list of possible offsets for adding to
        // FROM
        Map<String, List<List<Long>>> actOffsets = new HashMap<String, List<List<Long>>>();
        Date latestTO = null;

        // get availabilities for all resources of rup between from and to
        String xpath = XMLUtils.getXPATH_Activities();
        List<Element> activities = XMLUtils.getXMLObjects(rup, xpath);
        for (Element activity : activities) {
            String activityName = activity.getChildText(XML_ACTIVITYNAME);
            // logger.debug("activity name: " + activityName);
            // logger.debug("activity: " + Utils.object2String(activity));
            List<Element> reservations = activity.getChildren(XML_RESERVATION);
            if (reservations.isEmpty()) {
                continue;
            }

            actOffsets.put(activityName, new ArrayList<List<Long>>());
            Date from = XMLUtils.getDateValue(activity.getChild(XML_FROM), withValidation);
            Date to = XMLUtils.getDateValue(activity.getChild(XML_TO), withValidation);

            // compute latest date to check for free timeslots
            // between earliest FROM date (of first activity) and
            // maxTimeslotPeriod hours later
            if (latestTO == null) {
                Calendar cal = Calendar.getInstance();
                /*
                 * latestTO = Utils.string2Date(Utils.date2String(to,
                 * Utils.DATE_PATTERN_XML), Utils.DATE_PATTERN_XML);
                 * cal.setTime(latestTO); cal.roll(Calendar.DAY_OF_MONTH, 1);
                 * latestTO = cal.getTime();
                 */
                Integer maxTimeslotPeriod = PropertyReader.getInstance()
                        .getIntProperty(PropertyReader.SCHEDULING, "maxTimeslotPeriod");
                cal.setTime(from);
                cal.add(Calendar.HOUR_OF_DAY, maxTimeslotPeriod);
                // cal.roll(Calendar.HOUR_OF_DAY, maxTimeslotPeriod);
                latestTO = cal.getTime();
                // logger.debug("latestTO set to " + Utils.date2String(latestTO,
                // Utils.DATETIME_PATTERN));
            }

            long duration = to.getTime() - from.getTime();
            for (Element reservation : reservations) {
                Element resource = null;
                try {
                    resource = reservation.getChild(XML_RESOURCE);
                    int workload = XMLUtils.getIntegerValue(reservation.getChild(XML_WORKLOAD), withValidation);
                    List<Element> timeslots = rs.getAvailabilities(resource, from, latestTO);
                    for (int i = 0; i < timeslots.size(); i++) {
                        Element timeslot = timeslots.get(i);
                        Date tsFrom = XMLUtils.getDateValue(timeslot.getChild("start"), withValidation);
                        Date tsTo = XMLUtils.getDateValue(timeslot.getChild("end"), withValidation);
                        long tsDuration = tsTo.getTime() - tsFrom.getTime();
                        long offsetMin = tsFrom.getTime() - from.getTime();
                        long offsetMax = tsTo.getTime() - to.getTime();
                        int tsAvailability = XMLUtils.getIntegerValue(timeslot.getChild("availability"),
                                withValidation);
                        int tsAvailabilityDiff = tsAvailability - workload;

                        // try to pass activity into timeslot, if possible, add min
                        // and max offset
                        if (tsAvailabilityDiff >= 0 && duration <= tsDuration && offsetMin >= 0
                                && offsetMax >= 0) {
                            List<Long> offset = new ArrayList<Long>();
                            offset.add(offsetMin);
                            offset.add(offsetMax);
                            List<List<Long>> offsets = actOffsets.get(activityName);
                            offsets.add(offset);
                            // logger.debug("insert offset for "+activityName+", timeslot "+i+": "
                            // + Utils.toString(offset));
                            // TODO@tbe: ohne Speicherung des verbrauchten workloads
                            // (nur relevant wenn gleiche Ressource mehrfach pro
                            // Aktivitt)
                            // --> verbrauchte availabiliy (tsAvailabilityDiff) am
                            // offset speichern und beachten
                        }
                    }
                } catch (Exception e) {
                    logger.error("error get availability for resource:" + Utils.element2String(resource, true),
                            e);
                }
            }
        }
        // logger.debug("offsets: " + Utils.toString(actOffsets));

        // get average of offsets of each activity
        List<List<Long>> offsetsAvg = new ArrayList<List<Long>>();
        for (String activityName : actOffsets.keySet()) {
            List<List<Long>> offsets = actOffsets.get(activityName);
            if (offsetsAvg.isEmpty()) {
                offsetsAvg.addAll(offsets);
            } else {
                xpath = XMLUtils.getXPATH_Activities(activityName);
                Element activity = (Element) XMLUtils.getXMLObjects(rup, xpath).get(0);
                Date from = XMLUtils.getDateValue(activity.getChild(XML_FROM), withValidation);
                Date to = XMLUtils.getDateValue(activity.getChild(XML_TO), withValidation);
                long duration = to.getTime() - from.getTime();

                List<List<Long>> offsetsAvgNew = new ArrayList<List<Long>>();
                for (List<Long> offset : offsets) {
                    for (List<Long> offsetAvg : offsetsAvg) {
                        Long offsetMin = Math.max(offset.get(0), offsetAvg.get(0));
                        Long offsetMax = Math.min(offset.get(1), offsetAvg.get(1));
                        long offsetDuration = offsetMax - offsetMin;
                        if (offsetDuration >= duration) {
                            List<Long> offsetAvgNew = new ArrayList<Long>();
                            offsetAvgNew.add(offsetMin);
                            offsetAvgNew.add(offsetMax);
                            offsetsAvgNew.add(offsetAvgNew);
                        }
                    }
                }
                offsetsAvg = offsetsAvgNew;
            }
        }
        logger.debug("caseId: " + caseId + ", offsetsAvg: " + Utils.toString(offsetsAvg));

        // add min of first offset to each activity
        if (offsetsAvg.isEmpty()) {
            logger.error("no timeslot available for case: " + caseId);
            XMLUtils.addErrorValue(rup.getRootElement(), withValidation, "msgTimeslotUnavailable");
            isRescheduledRUP = true;
        } else {
            long offsetAvgMin = Long.MAX_VALUE;
            for (List<Long> offsetAvg : offsetsAvg) {
                offsetAvgMin = Math.min(offsetAvgMin, offsetAvg.get(0));
            }
            logger.info("timeslot for case: " + caseId + " found, offset=" + offsetAvgMin + " ("
                    + Utils.date2String(new Date(offsetAvgMin), Utils.TIME_PATTERN, TimeZone.getTimeZone("GMT"))
                    + " h)");
            if (offsetAvgMin > 0) {
                for (Element activity : activities) {
                    String activityName = activity.getChildText(XML_ACTIVITYNAME);

                    Element from = activity.getChild(XML_FROM);
                    Date fromDate = XMLUtils.getDateValue(from, false);
                    fromDate = new Date(fromDate.getTime() + offsetAvgMin);
                    XMLUtils.setDateValue(from, fromDate);
                    // logger.debug("set "+activityName+" from: " +
                    // Utils.date2String(fromDate, Utils.DATETIME_PATTERN));

                    Element to = activity.getChild(XML_TO);
                    Date toDate = XMLUtils.getDateValue(to, false);
                    toDate = new Date(toDate.getTime() + offsetAvgMin);
                    XMLUtils.setDateValue(to, toDate);
                    // logger.debug("set "+activityName+" to: " +
                    // Utils.date2String(toDate, Utils.DATETIME_PATTERN));
                    isRescheduledRUP = true;
                }
            }
        }
    } catch (Exception e) {
        logger.error("cannot found timeslot for case: " + caseId, e);
        XMLUtils.addErrorValue(rup.getRootElement(), withValidation, "msgTimeslotError", e.getMessage());
    }

    return isRescheduledRUP;
}

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

License:Open Source License

/**
 * completes a rup with historical data of rups with same ActivityType, but
 * only for new added activities and if data fields are empty yet
 *
 * @param rup/*from ww  w  .  j  av  a 2  s.  c  om*/
 * @param addedActivitiyNames
 * @return
 */
public void completeRupFromHistory(Document rup, Set<String> addedActivitiyNames) {
    String xpath = XMLUtils.getXPATH_Activities();
    List<Element> activities = XMLUtils.getElements(rup, xpath);
    List<List<Element>> nodes;
    boolean changed = false;

    for (Element activity : activities) {
        String activityName = activity.getChildText(XML_ACTIVITYNAME);
        if (!addedActivitiyNames.contains(activityName)) {
            continue;
        }

        String activityType = activity.getChildText(XML_ACTIVITYTYPE);

        Integer dur = XMLUtils.getDurationValueInMinutes(activity.getChild(XML_DURATION), false);
        if (dur == null || dur == 0) {
            nodes = getRupNodes(activityName, activityType, XML_DURATION, HistoricalMode.median);
            activity.getChild(XML_DURATION).setText(nodes.isEmpty() ? "" : nodes.get(0).get(0).getText());
            changed = true;
        }

        xpath = XMLUtils.getXPATH_ActivityElement(activityName, XML_RESERVATION, null);
        List<Element> reservations = XMLUtils.getElements(rup, xpath);
        if (reservations.isEmpty()) {
            nodes = getRupNodes(activityName, activityType, XML_RESERVATION, HistoricalMode.most);
            activity.addContent(nodes.isEmpty() ? new ArrayList<Element>() : nodes.get(0));
            changed = true;
        }
    }

    if (changed) {
        _log.info("update rup for case " + XMLUtils.getCaseId(rup) + " from history: "
                + Utils.document2String(rup, false));
    }
}

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

License:Open Source License

/**
 * gets field data from case in db//  ww  w.j a  va2s  .c o  m
 *
 * @param activity
 * @param nodeName
 * @return
 */
private Map<Object, Comparable> getRUPNodes(Map<Object, List<Element>> elementMap, String activity, String type,
        String nodeName) {
    Map<Object, Comparable> sortMap = new HashMap<Object, Comparable>();
    List<List<Element>> nodeLists = null;
    try {

        nodeLists = _dataMapper.getRupNodes(activity, type, nodeName);
        for (List<Element> nodeList : nodeLists) {
            String key;
            List<Element> newNodeList = new ArrayList<Element>();

            if (nodeList.isEmpty()) {
                key = "";
            } else {
                List<String> keyParts = new ArrayList<String>();

                for (Element node : nodeList) {
                    // _log.debug("node: " + Utils.toString(node));
                    if (node.getName().equals(XML_RESERVATION)) {
                        Element reservation = FormGenerator.getTemplate(XML_RESERVATION);
                        Element resource = reservation.getChild(XML_RESOURCE);

                        Element resourceNode = node.getChild(XML_RESOURCE);

                        String keyPart = resourceNode.getChildText(XML_CAPABILITY);
                        resource.getChild(XML_CAPABILITY).setText(resourceNode.getChildText(XML_CAPABILITY));

                        keyPart = resourceNode.getChildText(XML_ROLE) + keyPart;
                        resource.getChild(XML_ROLE).setText(resourceNode.getChildText(XML_ROLE));

                        keyPart = resourceNode.getChildText(XML_SUBCATEGORY) + keyPart;
                        resource.getChild(XML_SUBCATEGORY).setText(resourceNode.getChildText(XML_SUBCATEGORY));

                        keyPart = resourceNode.getChildText(XML_CATEGORY) + keyPart;
                        resource.getChild(XML_CATEGORY).setText(resourceNode.getChildText(XML_CATEGORY));

                        if (keyPart.isEmpty()) { // use Id, because it was set in custom form or Schedule
                            keyPart = resourceNode.getChildText(XML_ID);
                            resource.getChild(XML_ID).setText(resourceNode.getChildText(XML_ID));
                        } else {
                            resource.getChild(XML_ID).setText(""); // remove Id,
                            // because it was
                            // set in RS
                        }

                        keyPart = keyPart + node.getChildText(XML_WORKLOAD);
                        reservation.getChild(XML_WORKLOAD).setText(node.getChildText(XML_WORKLOAD));

                        // _log.debug("keyPart: " + keyPart);
                        keyParts.add(keyPart);

                        newNodeList.add(reservation);
                    } else {
                        Element newNode = new Element(node.getName());
                        keyParts.add(node.getText());
                        newNode.setText(node.getText());

                        newNodeList.add(newNode);
                    }
                }

                Collections.sort(keyParts);
                key = Utils.toString(keyParts);
            }

            // _log.debug("key='"+key+"' for nodeList: " +
            // Utils.toString(newNodeList));
            if (key.isEmpty()) {
                continue;
            }

            if (sortMap.containsKey(key)) {
                sortMap.put(key, (Integer) sortMap.get(key) + 1);
            } else {
                sortMap.put(key, 1);
                elementMap.put(key, newNodeList);
            }
        }
    } catch (Exception e) {
        _log.error("cannot get historical data for " + activity + "." + nodeName, e);
    }
    // _log.debug("sortMap: " + Utils.toString(sortMap) + ", elementMap: " +
    // Utils.toString(elementMap));
    return sortMap;
}