Example usage for java.util Vector isEmpty

List of usage examples for java.util Vector isEmpty

Introduction

In this page you can find the example usage for java.util Vector isEmpty.

Prototype

public synchronized boolean isEmpty() 

Source Link

Document

Tests if this vector has no components.

Usage

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

@SuppressWarnings("unchecked")
    protected Object buildSingleDBObjectFromXML(Element dbImport, String dbTable, String parentName, long parentId,
            int id, boolean recursion) {
        Object dbObject = new Object();
        try {//  w  ww  .j a  v  a2 s .  c  o  m
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            String primaryKey = parentInfo.getPrimaryKeyName();

            Vector collectionIds = new Vector(20);
            Vector collectionNames = new Vector(20);
            // make the agent and the element
            Object agent = parentInfo.getClassObj().newInstance();
            Map<String, Object> agentMap = new HashMap<String, Object>();
            Element dbElement = dbImport;
            Iterator i = dbElement.elementIterator();
            do {// do for each element in the record
                Element element = (Element) i.next();

                // Object value = findTypeSequential(element, dbTable, parentId, parentName );//the
                // parent is itself, just a dummy variable
                Object value = findTypeRecordSet(element, dbTable, parentId, parentName);// the
                                                                                         // parent
                                                                                         // is
                                                                                         // itself,
                                                                                         // just
                                                                                         // a
                                                                                         // dummy
                                                                                         // variable
                if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                {
                    agentMap.put(element.getName(), value);
                }
                // ignore many-to-many for now
                else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                {// RECURSE
                    if (recursion) {
                        // get assoicated ids
                        List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$
                                + primaryKey + " = \"" + id + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        // get collection info and still dont add it
                        if (!temp_collection_ids.isEmpty()) {
                            // get child dbName
                            String childDbName = getDbName(temp_collection_ids);
                            collectionNames.addElement(childDbName);
                            for (int index = 0; index < temp_collection_ids.size(); index++) {
                                collectionIds.addElement(temp_collection_ids.get(index));
                            }
                        }
                    }
                } else
                // else, dont add it
                {
                    // if it is an id, just ignore. otherwise print out error
                    if (!element.getName().equals(primaryKey)) {
                        log.debug("did not add " + element.getName() + " to the element " //$NON-NLS-1$ //$NON-NLS-2$
                                + dbTable);
                    }
                }
            } while (i.hasNext());

            // populate
            BeanUtils.populate(agent, agentMap);
            // save it then gets is id (assigned by Hibernate)
            this.session.save(agent);

            // if there was a collection, then recurse
            if (!collectionIds.isEmpty()) {
                long newParentId = new Long(session.getIdentifier(agent).toString()).longValue();

                sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId);
            }
            dbObject = agent;
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        }

        return dbObject;
    }

From source file:org.unitime.timetable.solver.studentsct.StudentSectioningDatabaseLoader.java

public Student loadStudent(org.unitime.timetable.model.Student s, Hashtable<Long, Course> courseTable,
        Hashtable<Long, Section> classTable) {
    // Check for nobatch sectioning status
    if (iCheckForNoBatchStatus && s.hasSectioningStatusOption(StudentSectioningStatus.Option.nobatch)) {
        skipStudent(s, courseTable, classTable);
        return null;
    }/*from   w ww .ja v  a 2s.  c  o m*/

    // Check student query, if present
    if (iStudentQuery != null && !iStudentQuery.match(new DbStudentMatcher(s))) {
        skipStudent(s, courseTable, classTable);
        return null;
    }

    NameFormat nameFormat = NameFormat
            .fromReference(ApplicationProperty.OnlineSchedulingStudentNameFormat.value());
    iProgress.debug("Loading student " + s.getUniqueId() + " (id=" + s.getExternalUniqueId() + ", name="
            + nameFormat.format(s) + ")");
    Student student = new Student(s.getUniqueId().longValue());
    student.setExternalId(s.getExternalUniqueId());
    student.setName(nameFormat.format(s));
    student.setStatus(s.getSectioningStatus() == null ? null : s.getSectioningStatus().getReference());
    if (iLoadStudentInfo)
        loadStudentInfo(student, s);

    TreeSet<CourseDemand> demands = new TreeSet<CourseDemand>(new Comparator<CourseDemand>() {
        public int compare(CourseDemand d1, CourseDemand d2) {
            if (d1.isAlternative() && !d2.isAlternative())
                return 1;
            if (!d1.isAlternative() && d2.isAlternative())
                return -1;
            int cmp = d1.getPriority().compareTo(d2.getPriority());
            if (cmp != 0)
                return cmp;
            return d1.getUniqueId().compareTo(d2.getUniqueId());
        }
    });
    demands.addAll(s.getCourseDemands());
    for (CourseDemand cd : demands) {
        if (cd.getFreeTime() != null) {
            TimeLocation ft = new TimeLocation(cd.getFreeTime().getDayCode(), cd.getFreeTime().getStartSlot(),
                    cd.getFreeTime().getLength(), 0, 0, -1l, "", iFreeTimePattern, 0);
            new FreeTimeRequest(cd.getUniqueId(), cd.getPriority(), cd.isAlternative(), student, ft);
        } else if (!cd.getCourseRequests().isEmpty()) {
            Vector<Course> courses = new Vector<Course>();
            HashSet<Choice> selChoices = new HashSet<Choice>();
            HashSet<Choice> wlChoices = new HashSet<Choice>();
            HashSet<Section> assignedSections = new HashSet<Section>();
            Config assignedConfig = null;
            TreeSet<org.unitime.timetable.model.CourseRequest> crs = new TreeSet<org.unitime.timetable.model.CourseRequest>(
                    new Comparator<org.unitime.timetable.model.CourseRequest>() {
                        public int compare(org.unitime.timetable.model.CourseRequest r1,
                                org.unitime.timetable.model.CourseRequest r2) {
                            return r1.getOrder().compareTo(r2.getOrder());
                        }
                    });
            crs.addAll(cd.getCourseRequests());
            for (org.unitime.timetable.model.CourseRequest cr : crs) {
                Course course = courseTable.get(cr.getCourseOffering().getUniqueId());
                if (course == null) {
                    iProgress.warn("Student " + nameFormat.format(s) + " (" + s.getExternalUniqueId()
                            + ") requests course " + cr.getCourseOffering().getCourseName()
                            + " that is not loaded.");
                    continue;
                }
                for (Iterator k = cr.getClassWaitLists().iterator(); k.hasNext();) {
                    ClassWaitList cwl = (ClassWaitList) k.next();
                    Section section = course.getOffering().getSection(cwl.getClazz().getUniqueId().longValue());
                    if (section != null) {
                        if (cwl.getType().equals(ClassWaitList.TYPE_SELECTION))
                            selChoices.add(section.getChoice());
                        else if (cwl.getType().equals(ClassWaitList.TYPE_WAITLIST))
                            wlChoices.add(section.getChoice());
                    }
                }
                if (assignedConfig == null) {
                    HashSet<Long> subparts = new HashSet<Long>();
                    for (Iterator<StudentClassEnrollment> i = cr.getClassEnrollments().iterator(); i
                            .hasNext();) {
                        StudentClassEnrollment enrl = i.next();
                        Section section = course.getOffering().getSection(enrl.getClazz().getUniqueId());
                        if (section != null) {
                            if (getModel().isMPP())
                                selChoices.add(section.getChoice());
                            assignedSections.add(section);
                            if (assignedConfig != null
                                    && assignedConfig.getId() != section.getSubpart().getConfig().getId()) {
                                iProgress.error("There is a problem assigning " + course.getName() + " to "
                                        + nameFormat.format(s) + " (" + s.getExternalUniqueId()
                                        + "): classes from different configurations.");
                            }
                            assignedConfig = section.getSubpart().getConfig();
                            if (!subparts.add(section.getSubpart().getId())) {
                                iProgress.error("There is a problem assigning " + course.getName() + " to "
                                        + nameFormat.format(s) + " (" + s.getExternalUniqueId()
                                        + "): two or more classes of the same subpart.");
                            }
                        } else {
                            iProgress.error("There is a problem assigning " + course.getName() + " to "
                                    + nameFormat.format(s) + " (" + s.getExternalUniqueId() + "): class "
                                    + enrl.getClazz().getClassLabel() + " not known.");
                        }
                    }
                }
                courses.addElement(course);
            }
            if (courses.isEmpty())
                continue;
            CourseRequest request = new CourseRequest(cd.getUniqueId(), cd.getPriority(), cd.isAlternative(),
                    student, courses, cd.isWaitlist(), cd.getTimestamp().getTime());
            request.getSelectedChoices().addAll(selChoices);
            request.getWaitlistedChoices().addAll(wlChoices);
            if (assignedConfig != null && assignedSections.size() == assignedConfig.getSubparts().size()) {
                Enrollment enrollment = new Enrollment(request, 0, assignedConfig, assignedSections,
                        getAssignment());
                request.setInitialAssignment(enrollment);
            }
            if (assignedConfig != null && assignedSections.size() != assignedConfig.getSubparts().size()) {
                iProgress.error("There is a problem assigning " + request.getName() + " to "
                        + nameFormat.format(s) + " (" + s.getExternalUniqueId() + ") wrong number of classes ("
                        + "has " + assignedSections.size() + ", expected " + assignedConfig.getSubparts().size()
                        + ").");
            }
        }
    }

    if (!s.getClassEnrollments().isEmpty() || !s.getWaitlists().isEmpty()) {
        TreeSet<Course> courses = new TreeSet<Course>(new Comparator<Course>() {
            public int compare(Course c1, Course c2) {
                return (c1.getSubjectArea() + " " + c1.getCourseNumber())
                        .compareTo(c2.getSubjectArea() + " " + c2.getCourseNumber());
            }
        });
        Map<Long, Long> timeStamp = new Hashtable<Long, Long>();
        for (StudentClassEnrollment enrl : s.getClassEnrollments()) {
            if (enrl.getCourseRequest() != null)
                continue; // already loaded
            Course course = courseTable.get(enrl.getCourseOffering().getUniqueId());
            if (course == null) {
                iProgress.warn("Student " + nameFormat.format(s) + " (" + s.getExternalUniqueId()
                        + ") requests course " + enrl.getCourseOffering().getCourseName()
                        + " that is not loaded.");
                continue;
            }
            if (enrl.getTimestamp() != null)
                timeStamp.put(enrl.getCourseOffering().getUniqueId(), enrl.getTimestamp().getTime());
            courses.add(course);
        }
        for (WaitList w : s.getWaitlists()) {
            Course course = courseTable.get(w.getCourseOffering().getUniqueId());
            if (course == null) {
                iProgress.warn("Student " + nameFormat.format(s) + " (" + s.getExternalUniqueId()
                        + ") requests course " + w.getCourseOffering().getCourseName()
                        + " that is not loaded.");
                continue;
            }
            if (w.getTimestamp() != null)
                timeStamp.put(w.getCourseOffering().getUniqueId(), w.getTimestamp().getTime());
            courses.add(course);
        }
        int priority = 0;
        courses: for (Course course : courses) {
            Vector<Course> cx = new Vector<Course>();
            cx.add(course);
            CourseRequest request = null;
            for (Request r : student.getRequests()) {
                if (r instanceof CourseRequest && getAssignment().getValue(r) == null
                        && ((CourseRequest) r).getCourses().contains(course)) {
                    request = (CourseRequest) r;
                    break;
                }
            }
            if (request == null) {
                request = new CourseRequest(course.getId(), priority++, false, student, cx, true,
                        timeStamp.get(course.getId()));
            }
            HashSet<Section> assignedSections = new HashSet<Section>();
            Config assignedConfig = null;
            HashSet<Long> subparts = new HashSet<Long>();
            for (Iterator<StudentClassEnrollment> i = s.getClassEnrollments().iterator(); i.hasNext();) {
                StudentClassEnrollment enrl = i.next();
                if (course.getId() != enrl.getCourseOffering().getUniqueId())
                    continue;
                Section section = course.getOffering().getSection(enrl.getClazz().getUniqueId());
                if (section != null) {
                    assignedSections.add(section);
                    if (assignedConfig != null
                            && assignedConfig.getId() != section.getSubpart().getConfig().getId()) {
                        iProgress.error("There is a problem assigning " + request.getName() + " to "
                                + nameFormat.format(s) + " (" + s.getExternalUniqueId()
                                + "): classes from different configurations.");
                        continue courses;
                    }
                    assignedConfig = section.getSubpart().getConfig();
                    if (!subparts.add(section.getSubpart().getId())) {
                        iProgress.error("There is a problem assigning " + request.getName() + " to "
                                + nameFormat.format(s) + " (" + s.getExternalUniqueId()
                                + "): two or more classes of the same subpart.");
                        continue courses;
                    }
                } else {
                    iProgress.error("There is a problem assigning " + request.getName() + " to "
                            + nameFormat.format(s) + " (" + s.getExternalUniqueId() + "): class "
                            + enrl.getClazz().getClassLabel() + " not known.");
                    Section x = classTable.get(enrl.getClazz().getUniqueId());
                    if (x != null) {
                        iProgress.info("  but a class with the same id is loaded, but under offering "
                                + x.getSubpart().getConfig().getOffering().getName() + " (id is "
                                + x.getSubpart().getConfig().getOffering().getId() + ", expected "
                                + course.getOffering().getId() + ")");
                    }
                    continue courses;
                }
            }
            if (assignedConfig != null && assignedSections.size() == assignedConfig.getSubparts().size()) {
                Enrollment enrollment = new Enrollment(request, 0, assignedConfig, assignedSections,
                        getAssignment());
                request.setInitialAssignment(enrollment);
            }
            if (assignedConfig != null && assignedSections.size() != assignedConfig.getSubparts().size()) {
                iProgress.error("There is a problem assigning " + request.getName() + " to "
                        + nameFormat.format(s) + " (" + s.getExternalUniqueId() + "): wrong number of classes ("
                        + "has " + assignedSections.size() + ", expected " + assignedConfig.getSubparts().size()
                        + ").");
            }
        }
    }

    return student;
}

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

@SuppressWarnings("unchecked")
    protected Object buildSingleDataBaseObjectFromXML(Element dbImport, String dbTable, String parentName,
            long parentId, int id, boolean recursion) {
        Object dbObject = new Object();
        try {//from   w  ww  .java  2 s  . co  m
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            //String lowerdbTable = lowerFirstChar(dbTable);
            String primaryKey = parentInfo.getPrimaryKeyName();

            Vector collectionIds = new Vector(20);
            Vector collectionNames = new Vector(20);
            // make the agent and the element
            Object agent = parentInfo.getClassObj().newInstance();
            Map<String, Object> agentMap = new HashMap<String, Object>();
            Element dbElement = dbImport;
            Iterator i = dbElement.elementIterator();
            do {// do for each element in the record
                Element element = (Element) i.next();

                // Object value = findTypeSequential(element, dbTable, parentId, parentName );//the
                // parent is itself, just a dummy variable
                Object value = findTypeDataBaseParent(element, dbTable, parentId, parentName);// the
                                                                                              // parent
                                                                                              // is
                                                                                              // itself,
                                                                                              // just
                                                                                              // a
                                                                                              // dummy
                                                                                              // variable
                if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                {
                    agentMap.put(element.getName(), value);
                }
                // ignore many-to-many for now
                else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                {// RECURSE
                    if (recursion) {
                        // get assoicated ids
                        List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$
                                + primaryKey + " = \"" + id + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        // get collection info and still dont add it
                        if (!temp_collection_ids.isEmpty()) {
                            // get child dbName
                            String childDbName = getDbName(temp_collection_ids);
                            collectionNames.addElement(childDbName);
                            for (int index = 0; index < temp_collection_ids.size(); index++) {
                                collectionIds.addElement(temp_collection_ids.get(index));
                            }
                        }
                    }
                } else
                // else, dont add it
                {
                    // if it is an id, just ignore. otherwise print out error
                    if (!element.getName().equals(primaryKey)) {
                        log.debug("did not add " + element.getName() + " to the element " //$NON-NLS-1$ //$NON-NLS-2$
                                + dbTable);
                    }
                }
            } while (i.hasNext());

            // populate
            BeanUtils.populate(agent, agentMap);
            // save it then gets its id (assigned by Hibernate)
            this.session.save(agent);

            // if there was a collection, then recurse
            if (!collectionIds.isEmpty()) {
                long newParentId = new Long(session.getIdentifier(agent).toString()).longValue();

                sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId);
            }
            dbObject = agent;
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        }

        return dbObject;
    }

From source file:alter.vitro.vgw.service.query.SimpleQueryHandler.java

private Vector<ReqResultOverData> findAggrAttrValue(String pQueryDefId,
        Vector<QueriedMoteAndSensors> pMotesAndTheirSensorAndFunctsVec,
        Vector<ReqFunctionOverData> reqFunctionVec, List<String> serviceDeployStatusStr,
        List<String[]> localReplacedResources) {

    ////www . ja  va2  s . c om
    // ADDED CODE -- OPTIMIZATION PENDING +++++
    //
    // --------------- SERVICE CONTINUATION PREP
    // TODO: SERVICE CONTINUATION PREP
    //service Continuation Additions:
    //String serviceDeployStatusStr = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_UNKNOWN;
    serviceDeployStatusStr.add(ResponseAggrMsg.DEPLOY_STATUS_SERVICE_UNKNOWN);
    // deploy status flags
    boolean serviceDeployAllNodesAvailable = true;
    boolean serviceDeployContinuationEmployed = false;
    boolean serviceDeployPartiallyPossible = false;
    boolean serviceDeployImpossible = false;
    // [0] is the original nodeId, [1] the replacing node id and [2] the capability
    //List<String[]> localReplacedResources = new ArrayList<String[]>();

    //
    //
    // TODO: 1.Use the motesAndTheirSensorAndFunctVec to get the requested motes and the requested capabilities.
    // TODO: 2.Check wth Continuation Service and Resource Availability Service.
    //      TODO.   2a. If all nodes are available then Deploy_Status = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_POSSIBLE.
    //              2b. If a node in the requested motes is unavailable (or future: a requested resource is unavailable)
    //                Check the equivalent nodes for matches for this capability.
    //                If a match is found, replace the node in the motesAndTheirSensorAndFunctsVec with the replacement node
    //                  and keep this replacing tracked/stored locally (as well as the cache of the continuationService)
    //                  when the results are found, replace the original mote back, but also send the extra xml that says that the values from that node for that capability are from the replacement node
    //                  TODO: Careful! a node could be replaced by more than one nodes, based on the capabilities requested! TEST THIS CASE!
    //                  TODO: Careful! a node could be replaced for one capability, but not for another!
    //                  Also set the flag serviceContinuationEmployed to true.
    //                      if at the end only this flag is set then update the Deploy_Status to  ResponseAggrMsg.DEPLOY_STATUS_SERVICE_CONTINUATION
    //               If a match is not found then remove this node from the results.
    //                  Also set the flag servicePartiallyPossible to true.
    //                  if at the end only this flag is set then update the Deploy_Status ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL
    //              If a the end both flags  serviceContinuationEmployed and servicePartiallyPossible are true
    //                  and not the serviceImpossible flag then update the Deploy_Status to ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL_CONT_COMBO
    //
    //              Finally if NO nodes are available for the service set the serviceImpossible flag to true and
    //                  update the deploy_status to  ResponseAggrMsg.DEPLOY_STATUS_SERVICE_IMPOSSIBLE
    // END: SERVICE CONTINUATION PREP
    Vector<QueriedMoteAndSensors> originalMotesAndTheirSensorAndFunctsVec = pMotesAndTheirSensorAndFunctsVec;
    Vector<QueriedMoteAndSensors> newMotesAndTheirSensorAndFunctsVec = new Vector<QueriedMoteAndSensors>();

    List<String> allInvolvedMoteIdsList = new ArrayList<String>();
    for (QueriedMoteAndSensors aMoteAndSensors : originalMotesAndTheirSensorAndFunctsVec) {
        allInvolvedMoteIdsList.add(aMoteAndSensors.getMoteid());
    }
    logger.debug("Queried motes and sensors:");
    for (QueriedMoteAndSensors aMoteAndSensors : originalMotesAndTheirSensorAndFunctsVec) {
        logger.debug("Mote Id: " + aMoteAndSensors.getMoteid());
        if (aMoteAndSensors.getQueriedSensorIdsAndFuncVec() != null
                && !aMoteAndSensors.getQueriedSensorIdsAndFuncVec().isEmpty()) {
            HashMap<String, Vector<Integer>> functionsForCapabilityOfThisMoteHM = new HashMap<String, Vector<Integer>>();
            for (ReqSensorAndFunctions sensAndFuncts : aMoteAndSensors.getQueriedSensorIdsAndFuncVec()) {
                logger.debug("     Capabilities: " + sensAndFuncts.getSensorModelid()); // TODO: we could probably acquire the friendly name too from some map
                //TODO: this isNodeResourceAvailable could be also done ideally within the ContinuationOfProvisionService within the findNextEquivalaneNode funciton (also could be synchronized)
                //logger.debug("DDDDD Size of functs:"+ Integer.toString(sensAndFuncts.getFunctionsOverSensorModelVec().size()));
                //{
                //    int smid = sensAndFuncts.getSensorModelIdInt();
                //    //logger.debug("For mote "+fullMoteId +" and sensor "+Integer.toString(smid) + " function vector size is "+reqFunctionVec.size());
                //    for (Integer inFunctVec : sensAndFuncts.getFunctionsOverSensorModelVec()) {
                //        logger.debug("Fid: " + inFunctVec);
                //    }
                // }

                functionsForCapabilityOfThisMoteHM.put(sensAndFuncts.getSensorModelid(),
                        sensAndFuncts.getFunctionsOverSensorModelVec());
                if (!ResourceAvailabilityService.getInstance().isNodeResourceAvailable(pQueryDefId,
                        aMoteAndSensors.getMoteid(), sensAndFuncts.getSensorModelid())) {
                    logger.debug("Node id: " + aMoteAndSensors.getMoteid() + " unavailable for: "
                            + sensAndFuncts.getSensorModelid());
                    String[] replacementInfo = ContinuationOfProvisionService.getInstance()
                            .findNextEquivalentNode(pQueryDefId, allInvolvedMoteIdsList,
                                    aMoteAndSensors.getMoteid(), sensAndFuncts.getSensorModelid());
                    if (replacementInfo == null) {
                        //
                        logger.debug("Could not find replacement node for " + sensAndFuncts.getSensorModelid()
                                + " vsn id: " + pQueryDefId);
                        serviceDeployPartiallyPossible = true;
                    } else {
                        logger.debug("Found replacement node " + replacementInfo[1] + " for node "
                                + replacementInfo[0] + " for " + replacementInfo[2] + " vsn id: "
                                + pQueryDefId);
                        serviceDeployContinuationEmployed = true;
                        // to prevent duplicates (though there really should not be such case)
                        addToLocalReplacementInfoList(localReplacedResources, replacementInfo);

                    }

                } //end if: node capability is not available
                else { //capability is available
                       // add self as a replacement (locally)
                       // a node could be available for some capabilities but not for others
                    String[] replacementInfo = { aMoteAndSensors.getMoteid(), aMoteAndSensors.getMoteid(),
                            sensAndFuncts.getSensorModelid() };
                    logger.debug("Adding self to local cache");
                    addToLocalReplacementInfoList(localReplacedResources, replacementInfo);
                }
            } //end for loop for this node's capability

            //loop through the localReplacedResources for this node and update the newMotesAndTheirSensorAndFunctsVec
            List<String> consideredReplacementNodes = new ArrayList<String>();
            for (String[] entryLocal : localReplacedResources) {
                //logger.debug("Checking  localReplacedResources for: " + entryLocal[0]);
                if (entryLocal[0].compareToIgnoreCase(aMoteAndSensors.getMoteid()) == 0) {
                    String idOfOneReplacingNode = entryLocal[1];
                    if (!consideredReplacementNodes.contains(idOfOneReplacingNode)) {
                        //logger.debug("INNER Checking  localReplacedResources for: " + idOfOneReplacingNode);
                        consideredReplacementNodes.add(idOfOneReplacingNode);

                        Vector<ReqSensorAndFunctions> replacementNodeSensorAndFuncts = new Vector<ReqSensorAndFunctions>();
                        QueriedMoteAndSensors replacementMoteAndSensors = new QueriedMoteAndSensors(
                                idOfOneReplacingNode, replacementNodeSensorAndFuncts);
                        // inner loop again to find all capabilities that this node (idOfOneReplacingNode) is a replacement for
                        for (String[] entryLocalInner : localReplacedResources) {
                            if (entryLocalInner[0].compareToIgnoreCase(aMoteAndSensors.getMoteid()) == 0
                                    && entryLocalInner[1].compareToIgnoreCase(idOfOneReplacingNode) == 0) {
                                //logger.debug("INNER MATCh FOUND for: " +  entryLocalInner[1] + " capability: " + entryLocalInner[2] );
                                String capabilityToAdd = entryLocalInner[2];
                                int capabilityToAddInt = ReqSensorAndFunctions.invalidSensModelId;
                                try {
                                    capabilityToAddInt = Integer.valueOf(capabilityToAdd);
                                } catch (Exception ex33) {
                                    logger.error(
                                            "Could not convert capability id to int for replacement capability: "
                                                    + capabilityToAdd);
                                }
                                //logger.error("CAP TO ADD" + capabilityToAdd);
                                if (functionsForCapabilityOfThisMoteHM.containsKey(capabilityToAdd)
                                        && functionsForCapabilityOfThisMoteHM.get(capabilityToAdd) != null
                                        && !functionsForCapabilityOfThisMoteHM.get(capabilityToAdd).isEmpty()) {
                                    //logger.error("FOUND IN HASHMAP!!!");
                                    Vector<Integer> funcsOverThisCapability = functionsForCapabilityOfThisMoteHM
                                            .get(capabilityToAdd);
                                    //int smid = capabilityToAddInt;
                                    //logger.debug("DEB DEB For mote "+aMoteAndSensors.getMoteid() +" and sensor "+Integer.toString(smid) + " function vector size is "+reqFunctionVec.size());
                                    //for (Integer inFunctVec : funcsOverThisCapability) {
                                    //    logger.debug("DEB DEB Fid: " + inFunctVec);
                                    //}
                                    ReqSensorAndFunctions thisSensorAndFuncts = new ReqSensorAndFunctions(
                                            capabilityToAddInt, funcsOverThisCapability);
                                    //thisSensorAndFuncts.getSensorModelid();
                                    //thisSensorAndFuncts.getFunctionsOverSensorModelVec().size();
                                    //logger.debug("DEB DEB 333 For  sensor "+ thisSensorAndFuncts.getSensorModelid()+ " function vector size is "+ thisSensorAndFuncts.getFunctionsOverSensorModelVec().size());
                                    //for (Integer inFunctVec : funcsOverThisCapability) {
                                    //    logger.debug("DEB DEB 333 Fid: " + inFunctVec);
                                    //}
                                    replacementNodeSensorAndFuncts.addElement(thisSensorAndFuncts);
                                }
                            }
                        }
                        if (!replacementNodeSensorAndFuncts.isEmpty()) {
                            //logger.error("ADDING ELEMENT TO NEW MOTES LIST!!!" + replacementMoteAndSensors.getMoteid() + ":: " + Integer.toString(replacementMoteAndSensors.getQueriedSensorIdsAndFuncVec().size()));
                            replacementMoteAndSensors
                                    .setQueriedSensorIdsAndFuncVec(replacementNodeSensorAndFuncts);
                            newMotesAndTheirSensorAndFunctsVec.addElement(replacementMoteAndSensors);
                        }
                    }
                }
            }
            //functionsForCapabilityOfThisMoteHM.clear();
        }
    } //end for loop for this node of queried motes
    if (newMotesAndTheirSensorAndFunctsVec == null || newMotesAndTheirSensorAndFunctsVec.isEmpty()) {
        serviceDeployImpossible = true;
        logger.debug("Service Deploy is impossible for vsn id: " + pQueryDefId);
    }

    // decide status
    String statusDecidedStr = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_UNKNOWN;
    if (serviceDeployImpossible) {
        statusDecidedStr = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_IMPOSSIBLE;
    } else if (serviceDeployContinuationEmployed && serviceDeployPartiallyPossible) {
        statusDecidedStr = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL_CONT_COMBO;
    } else if (serviceDeployContinuationEmployed) {
        statusDecidedStr = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_CONTINUATION;
    } else if (serviceDeployPartiallyPossible) {
        statusDecidedStr = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL;
    } else if (serviceDeployAllNodesAvailable && !serviceDeployImpossible && !serviceDeployContinuationEmployed
            && !serviceDeployPartiallyPossible) {
        statusDecidedStr = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_POSSIBLE;
    }
    serviceDeployStatusStr.set(0, statusDecidedStr);
    logger.debug("Decided DEPLOY STATUS WAS: " + serviceDeployStatusStr.get(0));
    // We proceed here because even if service deploy is not possible, a reply will be sent with the status and empty lists (TODO consider)
    // However we also send (near the end of this method, alert messages for the deploy status if <> OK
    //
    //
    // TODO: To skip redundant queries in network
    // TODO: Count the reqFunction in reqFunction Vec (Debug print them) (also check that they are executed even if gateway level for each node-which should not happen)
    // TODO: Verify that if a function is gateway level and its removed(?) from the reqFunctionVec then it's not executed by the wsi adapter!
    //
    //
    // TODO: handle conditions for aggregate (gateway level functions).
    //
    //clone the reqFunctionsVec   . TODO. this is not cloning though, we pass references to the added elements
    Vector<ReqFunctionOverData> onlyNodeReqFunctVec = new Vector<ReqFunctionOverData>();
    Vector<ReqFunctionOverData> onlyGwLevelReqFunctVec = new Vector<ReqFunctionOverData>();
    for (int i = 0; i < reqFunctionVec.size(); i++) {
        if (ReqFunctionOverData.isValidGatewayReqFunct(reqFunctionVec.elementAt(i).getfuncName()))
            onlyGwLevelReqFunctVec.addElement(reqFunctionVec.elementAt(i));
        else {
            onlyNodeReqFunctVec.addElement(reqFunctionVec.elementAt(i));
        }
    }
    //
    // get the involved capabilities per gatewaylevel function, and then remove the function id from those sensorModels!
    //
    //  Produce a hashmap of gwLevel function name to Vector of capabilities (sensorModelId from the query/request)
    HashMap<String, Vector<String>> gwLevelFunctToCapsList = new HashMap<String, Vector<String>>(); // todo: IMPORTANT later we should group sensormodelIds per capability they belong to, but for now sensormodelid == capability!
    Iterator<ReqFunctionOverData> gwLevelFunctsIter = onlyGwLevelReqFunctVec.iterator();
    while (gwLevelFunctsIter.hasNext()) {
        Vector<String> myInvolvedCaps = new Vector<String>();
        ReqFunctionOverData tmpGwLevelFunct = gwLevelFunctsIter.next();
        // new change to new Vector of motes (19/04)
        Iterator<QueriedMoteAndSensors> onMotesSensFunctsVecIter = newMotesAndTheirSensorAndFunctsVec
                .iterator();
        while (onMotesSensFunctsVecIter.hasNext()) {
            QueriedMoteAndSensors tmpMoteAndSenAndFuncts = onMotesSensFunctsVecIter.next();
            Iterator<ReqSensorAndFunctions> sensAndFunctsIter = tmpMoteAndSenAndFuncts
                    .getQueriedSensorIdsAndFuncVec().iterator();

            while (sensAndFunctsIter.hasNext()) {
                ReqSensorAndFunctions sensAndFuncts = sensAndFunctsIter.next();
                //Vector<Integer> sensfunctsVector = sensAndFuncts.getFunctionsOverSensorModelVec();
                int initSize = sensAndFuncts.getFid().size();

                for (int k = initSize - 1; k >= 0; k--) {
                    int sensfid = sensAndFuncts.getFid().get(k).intValue();
                    if (sensfid == tmpGwLevelFunct.getfuncId()) {
                        if (!myInvolvedCaps.contains(sensAndFuncts.getSensorModelid())) {
                            myInvolvedCaps.addElement(sensAndFuncts.getSensorModelid());
                        }

                        // TODO: WHY??? (NOT NEEDED ANYMORE because we use the onlyNodeReqFunctVec to query the sensor and that filters out the functions in the adapter) ::here we should also delete the fid from the sensor model (but the simple way does not work for some reason, so it is left for future)

                        //List tmpList =  removeElementAt(sensAndFuncts.getFid(),k);
                        //sensAndFuncts.getFid().clear();
                        //sensAndFuncts.getFid().addAll(tmpList);
                        //sensAndFuncts.getFunctionsOverSensorModelVec().clear();

                    }
                }
            }
        }
        gwLevelFunctToCapsList.put(tmpGwLevelFunct.getfuncName(), myInvolvedCaps);
    }
    //
    //
    //
    Vector<ReqResultOverData> allResultsRead = new Vector<ReqResultOverData>();
    //WsiAdapterCon myDCon = WsiAdapterConFactory.createMiddleWCon("uberdust", DbConInfoFactory.createConInfo("restHttp"));
    // DONE: The translateAggrQuery should not be executed for gateway level functions (skip them here or in the adapter con class.(?)
    // new changed to the new vector of motes : 19/04
    logger.debug("Submitting query to the network");
    // ASK ONLY FOR NODE LEVEL FUNCTIONS (TODO: Essentially for now, only last value is a node level function sent from the VSP, although other node level functions are supported)
    allResultsRead = myDCon.translateAggrQuery(newMotesAndTheirSensorAndFunctsVec, onlyNodeReqFunctVec);
    logger.debug("After Submitting query to the network");
    //
    //
    // TODO: All gateway level functions reference a node level function at some point (either directly eg max or two hops eg "IF MAX "
    //
    //
    // Handle gateway level functions
    // first order of business, delete everything within them (some connectors could put latest values of all nodes, but we want to do it the more proper way)
    // then get the values of the referenced function(s)
    // aggregate the values and produce a single result. TODO: here UOMs of different sensor models could come into play. Handle this in the future!
    //
    //
    // 1. we create a new derived structure with unique fid keyed entries for required Result over data.
    Vector<ReqResultOverData> allUniqueFunctionsWithResults = new Vector<ReqResultOverData>();
    Iterator<ReqResultOverData> messyResultsIter = allResultsRead.iterator();
    // Loop over all resultOverData. They are keyed by fid, but there can be multiple of the same fid!
    // So here we merge those of same fid.
    while (messyResultsIter.hasNext()) //OUTER loop
    {
        ReqResultOverData tmpResStructFromMessyVec = messyResultsIter.next();

        //ReqResultOverData tmpResStructMatched = null;
        boolean foundTheFid = false;
        Iterator<ReqResultOverData> uniqueFuncResultsIter = allUniqueFunctionsWithResults.iterator();
        while (uniqueFuncResultsIter.hasNext()) //for the first pass of the OUTER loop the allUniqueFunctionsWithResults is empty
        {
            ReqResultOverData uniqueFunctResult = uniqueFuncResultsIter.next();
            if (uniqueFunctResult.getFidInt() == tmpResStructFromMessyVec.getFidInt()) {
                foundTheFid = true;
                uniqueFunctResult.getOut().addAll(tmpResStructFromMessyVec.getAllResultsforFunct());
                break;
            }
        }
        if (!foundTheFid) {
            allUniqueFunctionsWithResults.addElement(new ReqResultOverData(tmpResStructFromMessyVec.getFidInt(),
                    tmpResStructFromMessyVec.getAllResultsforFunct()));
        }

    }
    //
    // Repeat this process slightly altered to add the unique Gw level functions
    //
    Iterator<ReqFunctionOverData> gwfunctIter = onlyGwLevelReqFunctVec.iterator();
    while (gwfunctIter.hasNext()) //OUTER loop
    {
        ReqFunctionOverData tmpReqGwFunct = gwfunctIter.next();
        //ReqResultOverData tmpResStructMatched = null;
        boolean foundTheFid = false;
        Iterator<ReqResultOverData> uniqueFuncResultsIter = allUniqueFunctionsWithResults.iterator();
        while (uniqueFuncResultsIter.hasNext()) //for the first pass of the OUTER loop the allUniqueFunctionsWithResults is empty
        {
            ReqResultOverData uniqueFunctResult = uniqueFuncResultsIter.next();
            if (uniqueFunctResult.getFidInt() == tmpReqGwFunct.getfuncId()) {
                foundTheFid = true;
                break;
            }
        }
        if (!foundTheFid) {
            allUniqueFunctionsWithResults.addElement(
                    new ReqResultOverData(tmpReqGwFunct.getfuncId(), new Vector<ResultAggrStruct>()));
        }

    }
    // end of 1.
    //
    // 2. Go through all the gateway level functions (all of which are missing values right now).
    //    For each gateway level function, go through all the results for this function.
    //
    gwfunctIter = onlyGwLevelReqFunctVec.iterator();
    while (gwfunctIter.hasNext()) {
        ReqFunctionOverData tmpGwFunct = gwfunctIter.next();

        Iterator<ReqResultOverData> resultsIter = allUniqueFunctionsWithResults.iterator();
        // loop over all resultOverData for this specific function (matching is made in the next two lines)
        while (resultsIter.hasNext()) {
            ReqResultOverData tmpResForGWFunct = resultsIter.next();
            if (tmpResForGWFunct.getFidInt() == tmpGwFunct.getfuncId()) {

                // descriptionTokens[0] : GW LEVEL PREFIX
                // descriptionTokens[1] : FUNCTION NAME
                // descriptionTokens[2] : REFERENCED FUNCTION ID
                String[] descriptionTokens = tmpGwFunct.getfuncName()
                        .split(ReqFunctionOverData.GW_LEVEL_SEPARATOR);
                //
                // 3. Handle min, max and avg gateway level functions. (IF THEN FUNCTIONS ARE HANDLED AS ANOTHER CASE - THEY ARE ONE HOP HIGHER)
                //    MIN, MAX, and AVG are all one hop (reference) away from a node level function (last value)
                if (descriptionTokens != null && descriptionTokens.length > 2
                        && (descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.maxFunc)
                                || descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.minFunc)
                                || descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.avgFunc))) {
                    logger.debug("Clearing up values for gw funct name: " + tmpGwFunct.getfuncName());
                    // cleanup of output list  (it should however be already empty now that we rightfully only poll the WSI for node level functions)
                    tmpResForGWFunct.getOut().clear();
                    tmpResForGWFunct.getAllResultsforFunct().clear();

                    //after cleanup of output list
                    logger.debug("Filling up values for gw funct name: " + tmpGwFunct.getfuncName());
                    if (descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.maxFunc)) {
                        // MAX FUNCTION   =======================================
                        int aggregatedValues = 0;

                        int refFunct = ReqFunctionOverData.unknownFuncId;
                        try {
                            refFunct = Integer.valueOf(descriptionTokens[2]);
                        } catch (Exception exfrtm) {
                            logger.error("Reference function id was set as unknown!");
                        }
                        HashMap<String, Long> capToTsFromMinLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToTsToMaxLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToMaxValueLong = new HashMap<String, Long>();
                        //
                        Iterator<ReqResultOverData> resultsIter002 = allUniqueFunctionsWithResults.iterator();
                        // INNER LOOP THROUGH FUNCTIONS with results, searching for the referenced NODE level function
                        while (resultsIter002.hasNext()) {
                            ReqResultOverData tmpRes = resultsIter002.next();
                            if (tmpRes.getFidInt() == refFunct) {
                                // for every GENERIC capability requested( the generic capability is coded as hashcode() )
                                for (String currCapSidStr : gwLevelFunctToCapsList
                                        .get(tmpGwFunct.getfuncName())) {
                                    if (!capToMaxValueLong.containsKey(currCapSidStr)) {
                                        capToMaxValueLong.put(currCapSidStr, Long.valueOf(Long.MIN_VALUE));
                                        capToTsFromMinLong.put(currCapSidStr, Long.valueOf(Long.MAX_VALUE));
                                        capToTsToMaxLong.put(currCapSidStr, Long.valueOf(Long.MIN_VALUE));
                                    }

                                    Iterator<OutType> tmpOutItemIter = tmpRes.getOut().iterator();
                                    while (tmpOutItemIter.hasNext()) {
                                        ResultAggrStruct tmpOutItem = new ResultAggrStruct(
                                                tmpOutItemIter.next());
                                        if (currCapSidStr.trim().equalsIgnoreCase(tmpOutItem.getSid().trim())) {
                                            try {
                                                long longValToCompare = Long.parseLong(tmpOutItem.getVal());
                                                if (longValToCompare > capToMaxValueLong.get(currCapSidStr)
                                                        .longValue()) {
                                                    capToMaxValueLong.put(currCapSidStr,
                                                            Long.valueOf(longValToCompare));
                                                }
                                                if (capToTsFromMinLong.get(currCapSidStr)
                                                        .longValue() > tmpOutItem.getTis().getFromTimestamp()
                                                                .getTime()) {
                                                    capToTsFromMinLong.put(currCapSidStr, Long.valueOf(
                                                            tmpOutItem.getTis().getFromTimestamp().getTime()));
                                                }
                                                if (capToTsToMaxLong.get(currCapSidStr).longValue() < tmpOutItem
                                                        .getTis().getToTimestamp().getTime()) {
                                                    capToTsToMaxLong.put(currCapSidStr, Long.valueOf(
                                                            tmpOutItem.getTis().getToTimestamp().getTime()));
                                                }
                                                aggregatedValues += 1;

                                            } catch (Exception e) {
                                                logger.error("Invalid format to aggregate");
                                            }
                                        }
                                    }
                                    ResultAggrStruct thisAggrResult = new ResultAggrStruct(
                                            ResultAggrStruct.MidSpecialForAggregateMultipleValues,
                                            Integer.valueOf(currCapSidStr),
                                            Long.toString(capToMaxValueLong.get(currCapSidStr)),
                                            aggregatedValues,
                                            new TimeIntervalStructure(
                                                    new Timestamp(capToTsFromMinLong.get(currCapSidStr)),
                                                    new Timestamp(capToTsToMaxLong.get(currCapSidStr))));
                                    tmpResForGWFunct.getOut().add(thisAggrResult);
                                }
                            }
                        }
                    } else if (descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.minFunc)) {
                        // MIN FUNCTION   =======================================
                        int aggregatedValues = 0;

                        int refFunct = ReqFunctionOverData.unknownFuncId;
                        try {
                            refFunct = Integer.valueOf(descriptionTokens[2]);
                        } catch (Exception exfrtm) {
                            logger.error("Reference function id was set as unknown!");
                        }
                        HashMap<String, Long> capToTsFromMinLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToTsToMaxLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToMinValueLong = new HashMap<String, Long>();
                        //
                        Iterator<ReqResultOverData> resultsIter002 = allUniqueFunctionsWithResults.iterator();
                        while (resultsIter002.hasNext()) {

                            ReqResultOverData tmpRes = resultsIter002.next();
                            if (tmpRes.getFidInt() == refFunct) {
                                // for every GENERIC capability requested( the genereic capability is coded as hashcode() )
                                for (String currCapSidStr : gwLevelFunctToCapsList
                                        .get(tmpGwFunct.getfuncName())) {
                                    if (!capToMinValueLong.containsKey(currCapSidStr)) {
                                        capToMinValueLong.put(currCapSidStr, Long.valueOf(Long.MAX_VALUE));
                                        capToTsFromMinLong.put(currCapSidStr, Long.valueOf(Long.MAX_VALUE));
                                        capToTsToMaxLong.put(currCapSidStr, Long.valueOf(Long.MIN_VALUE));
                                    }

                                    Iterator<OutType> tmpOutItemIter = tmpRes.getOut().iterator();
                                    while (tmpOutItemIter.hasNext()) {
                                        ResultAggrStruct tmpOutItem = new ResultAggrStruct(
                                                tmpOutItemIter.next());
                                        if (currCapSidStr.trim().equalsIgnoreCase(tmpOutItem.getSid().trim())) {
                                            try {
                                                long longValToCompare = Long.parseLong(tmpOutItem.getVal());
                                                if (longValToCompare < capToMinValueLong.get(currCapSidStr)
                                                        .longValue()) {
                                                    capToMinValueLong.put(currCapSidStr,
                                                            Long.valueOf(longValToCompare));
                                                }
                                                if (capToTsFromMinLong.get(currCapSidStr)
                                                        .longValue() > tmpOutItem.getTis().getFromTimestamp()
                                                                .getTime()) {
                                                    capToTsFromMinLong.put(currCapSidStr, Long.valueOf(
                                                            tmpOutItem.getTis().getFromTimestamp().getTime()));
                                                }
                                                if (capToTsToMaxLong.get(currCapSidStr).longValue() < tmpOutItem
                                                        .getTis().getToTimestamp().getTime()) {
                                                    capToTsToMaxLong.put(currCapSidStr, Long.valueOf(
                                                            tmpOutItem.getTis().getToTimestamp().getTime()));
                                                }
                                                aggregatedValues += 1;

                                            } catch (Exception e) {
                                                logger.error("Invalid format to aggregate");
                                            }
                                        }
                                    }
                                    ResultAggrStruct thisAggrResult = new ResultAggrStruct(
                                            ResultAggrStruct.MidSpecialForAggregateMultipleValues,
                                            Integer.valueOf(currCapSidStr),
                                            Long.toString(capToMinValueLong.get(currCapSidStr)),
                                            aggregatedValues,
                                            new TimeIntervalStructure(
                                                    new Timestamp(capToTsFromMinLong.get(currCapSidStr)),
                                                    new Timestamp(capToTsToMaxLong.get(currCapSidStr))));
                                    logger.debug("Adding a result");
                                    tmpResForGWFunct.getOut().add(thisAggrResult);
                                    logger.debug("Added a result");

                                }
                            }
                        }
                    } else if (descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.avgFunc)) {
                        // AVG FUNCTION   =======================================
                        int aggregatedValues = 0;
                        int refFunct = ReqFunctionOverData.unknownFuncId;
                        try {
                            refFunct = Integer.valueOf(descriptionTokens[2]);
                        } catch (Exception exfrtm) {
                            logger.error("Reference function id was set as unknown!");
                        }
                        HashMap<String, Long> capToTsFromMinLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToTsToMaxLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToAvgValueLong = new HashMap<String, Long>();
                        //
                        Iterator<ReqResultOverData> resultsIter002 = allUniqueFunctionsWithResults.iterator();

                        while (resultsIter002.hasNext()) {

                            ReqResultOverData tmpRes = resultsIter002.next();
                            /*System.out.println("LLLLLLLL TEST 3");
                            StringBuilder tmpRsOD = new StringBuilder();
                            tmpRsOD.append("resf fid:");
                            tmpRsOD.append(tmpRes.getFidInt());
                            tmpRsOD.append(" AND ref funct:");
                            tmpRsOD.append(refFunct);
                            System.out.println("OOOOOOOOOOOOOO TEST 3B" + tmpRsOD.toString());*/
                            if (tmpRes.getFidInt() == refFunct) {
                                // for every GENERIC capability requested( the genereic capability is coded as hashcode() )
                                for (String currCapSidStr : gwLevelFunctToCapsList
                                        .get(tmpGwFunct.getfuncName())) {
                                    if (!capToAvgValueLong.containsKey(currCapSidStr)) {
                                        capToAvgValueLong.put(currCapSidStr, Long.valueOf(0));
                                        capToTsFromMinLong.put(currCapSidStr, Long.valueOf(Long.MAX_VALUE));
                                        capToTsToMaxLong.put(currCapSidStr, Long.valueOf(Long.MIN_VALUE));
                                    }

                                    Iterator<OutType> tmpOutItemIter = tmpRes.getOut().iterator();
                                    while (tmpOutItemIter.hasNext()) {
                                        ResultAggrStruct tmpOutItem = new ResultAggrStruct(
                                                tmpOutItemIter.next());
                                        if (currCapSidStr.trim().equalsIgnoreCase(tmpOutItem.getSid().trim())) {
                                            try {
                                                long longValOfSensor = Long.parseLong(tmpOutItem.getVal());
                                                long valPrevious = capToAvgValueLong.get(currCapSidStr)
                                                        .longValue();
                                                long newVal = valPrevious + longValOfSensor;
                                                capToAvgValueLong.put(currCapSidStr, Long.valueOf(newVal));

                                                //
                                                if (capToTsFromMinLong.get(currCapSidStr)
                                                        .longValue() > tmpOutItem.getTis().getFromTimestamp()
                                                                .getTime()) {
                                                    capToTsFromMinLong.put(currCapSidStr, Long.valueOf(
                                                            tmpOutItem.getTis().getFromTimestamp().getTime()));
                                                }
                                                if (capToTsToMaxLong.get(currCapSidStr).longValue() < tmpOutItem
                                                        .getTis().getToTimestamp().getTime()) {
                                                    capToTsToMaxLong.put(currCapSidStr, Long.valueOf(
                                                            tmpOutItem.getTis().getToTimestamp().getTime()));
                                                }
                                                aggregatedValues += 1;

                                            } catch (Exception e) {
                                                logger.error("Invalid format to aggregate");
                                            }

                                        }
                                    }
                                    Double avgVal = Double
                                            .valueOf(capToAvgValueLong.get(currCapSidStr).longValue())
                                            / Double.valueOf(aggregatedValues);
                                    /*StringBuilder tmpRs = new StringBuilder();
                                    tmpRs.append("Result:");
                                    tmpRs.append(avgVal);
                                    tmpRs.append(" aggr vals:");
                                    tmpRs.append(aggregatedValues);
                                    System.out.println("OOOOOOOOOOOOOO TEST 3C" + tmpRs.toString());*/
                                    ResultAggrStruct thisAggrResult = new ResultAggrStruct(
                                            ResultAggrStruct.MidSpecialForAggregateMultipleValues,
                                            Integer.valueOf(currCapSidStr), Double.toString(avgVal),
                                            aggregatedValues,
                                            new TimeIntervalStructure(
                                                    new Timestamp(capToTsFromMinLong.get(currCapSidStr)),
                                                    new Timestamp(capToTsToMaxLong.get(currCapSidStr))));

                                    tmpResForGWFunct.getOut().add(thisAggrResult);
                                    //System.out.println("OOOOOOOOOOOOOO TEST 3D" + tmpRs.toString());
                                }
                            }
                        }

                    }
                }
            }
        }
    } // end of while loop on ONE HOP REFERENCE GW FUNCTIONs (MIN, MAX, AVG

    // Start of while loop on 2nd HOP reference GW function (need the one hops already filled in)
    // TODO: we don't handle/anticipate the case where the IF_THEN function references another IF_THEN function (even repeatedly). More flexibility could be implemented!!
    gwfunctIter = onlyGwLevelReqFunctVec.iterator(); // gets a NEW iterator
    while (gwfunctIter.hasNext()) {
        ReqFunctionOverData tmpGwFunct = gwfunctIter.next();

        Iterator<ReqResultOverData> resultsIter = allUniqueFunctionsWithResults.iterator();
        // loop over all resultOverData for this specific function (matching is made in the next two lines)
        while (resultsIter.hasNext()) {
            ReqResultOverData tmpResForGWFunct = resultsIter.next();

            if (tmpResForGWFunct.getFidInt() == tmpGwFunct.getfuncId()) {

                // descriptionTokens[0] : GW LEVEL PREFIX
                // descriptionTokens[1] : FUNCTION NAME
                // descriptionTokens[2] : REFERENCED FUNCTION ID
                String[] descriptionTokens = tmpGwFunct.getfuncName()
                        .split(ReqFunctionOverData.GW_LEVEL_SEPARATOR);

                if (descriptionTokens != null && descriptionTokens.length > 2
                        && (descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.ruleRuleBinaryAndFunc)
                                || descriptionTokens[1]
                                        .equalsIgnoreCase(ReqFunctionOverData.ruleRuleIfThenFunc))) {
                    logger.debug("Clearing up values for gw funct name: " + tmpGwFunct.getfuncName());
                    // cleanup of output list  (it should however be already empty now that we rightfully only poll the WSI for node level functions)
                    tmpResForGWFunct.getOut().clear();
                    tmpResForGWFunct.getAllResultsforFunct().clear();
                    //after cleanup of output list
                    logger.debug("Filling values for funct name: " + tmpGwFunct.getfuncName());
                    if (descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.ruleRuleBinaryAndFunc)) {

                        //TODO: handle a binary rule (condition1 and condition2)
                    } else if (descriptionTokens[1].equalsIgnoreCase(ReqFunctionOverData.ruleRuleIfThenFunc)) {

                        logger.debug("Filling values for funct name: " + tmpGwFunct.getfuncName());
                        //handle a binary rule (condition1 then do 3)
                        // 1: check if the referenced function has results that meet the conditions in its threshold
                        int consideredValues = 0;
                        int refFunct = ReqFunctionOverData.unknownFuncId;
                        try {
                            refFunct = Integer.valueOf(descriptionTokens[2]);
                        } catch (Exception exfrtm) {
                            logger.error("Reference function id was set as unknown!");
                        }
                        HashMap<String, Long> capToTsFromMinLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToTsToMaxLong = new HashMap<String, Long>();
                        HashMap<String, Long> capToConditionValueLong = new HashMap<String, Long>();
                        //
                        Iterator<ReqResultOverData> resultsIter002 = allUniqueFunctionsWithResults.iterator();
                        while (resultsIter002.hasNext()) {
                            ReqResultOverData tmpRes = resultsIter002.next();
                            if (tmpRes.getFidInt() == refFunct) {
                                // for every GENERIC capability requested( the genereic capability is coded as hashcode() )
                                for (String currCapSidStr : gwLevelFunctToCapsList
                                        .get(tmpGwFunct.getfuncName())) {
                                    if (!capToConditionValueLong.containsKey(currCapSidStr)) {
                                        capToTsFromMinLong.put(currCapSidStr, Long.valueOf(Long.MAX_VALUE));
                                        capToTsToMaxLong.put(currCapSidStr, Long.valueOf(Long.MIN_VALUE));
                                        capToConditionValueLong.put(currCapSidStr, Long.valueOf(0));
                                    }

                                    Iterator<OutType> tmpOutItemIter = tmpRes.getOut().iterator();
                                    while (tmpOutItemIter.hasNext()) {
                                        ResultAggrStruct tmpOutItem = new ResultAggrStruct(
                                                tmpOutItemIter.next());

                                        if (currCapSidStr.trim().equalsIgnoreCase(tmpOutItem.getSid().trim())) {
                                            try {
                                                // TODO: Actually here we need to find in the original ReqFunctVec (that contains the full function definitions, not just the function id)
                                                //      the thresholds set. Before we search for the thresholds in the referenced function but now (better) we get them from this function (If_then)

                                                boolean foundTheCurrentFunctionInTheOriginalReqFunctionVec = false;
                                                long longValOfSensor = Long.parseLong(tmpOutItem.getVal());
                                                ReqFunctionOverData currentFunctionInCondition = null;
                                                for (int kx1 = 0; kx1 < reqFunctionVec.size(); kx1++) {
                                                    if (reqFunctionVec.elementAt(kx1)
                                                            .getfuncId() == tmpResForGWFunct.getFidInt()) {
                                                        currentFunctionInCondition = reqFunctionVec
                                                                .elementAt(kx1);
                                                        foundTheCurrentFunctionInTheOriginalReqFunctionVec = true;
                                                        break;
                                                    }
                                                }
                                                // but also find the reference function in the condition to include details in the notification
                                                boolean foundTheReferencedFunctionInTheOriginalReqFunctionVec = false;
                                                ReqFunctionOverData referencedFunctionInCondition = null;
                                                for (int kx1 = 0; kx1 < reqFunctionVec.size(); kx1++) {
                                                    if (reqFunctionVec.elementAt(kx1)
                                                            .getfuncId() == tmpResForGWFunct.getFidInt()) {
                                                        referencedFunctionInCondition = reqFunctionVec
                                                                .elementAt(kx1);
                                                        foundTheReferencedFunctionInTheOriginalReqFunctionVec = true;
                                                        break;
                                                    }
                                                }
                                                if (foundTheCurrentFunctionInTheOriginalReqFunctionVec) // the referred function here must have a threshold field because it's an evaluation of a condition
                                                {
                                                    if (currentFunctionInCondition != null
                                                            && currentFunctionInCondition
                                                                    .getThresholdField() != null
                                                            && !currentFunctionInCondition.getThresholdField()
                                                                    .isEmpty()) {
                                                        logger.debug(
                                                                "-------- INTO EVALUATING CONDITION NOW! ");
                                                        ThresholdStructure requiredThresholds = new ThresholdStructure(
                                                                currentFunctionInCondition.getThresholdField());
                                                        if (requiredThresholds.getLowerBound() != null
                                                                && !requiredThresholds.getLowerBound()
                                                                        .isEmpty()) {
                                                            logger.debug("Condition low parameter: "
                                                                    + requiredThresholds.getLowerBound()
                                                                            .trim());
                                                            //    TODO: handle other conditions for services (lower than, equals, between)
                                                            long lowbound = Long.parseLong(
                                                                    requiredThresholds.getLowerBound());
                                                            if (longValOfSensor >= lowbound) {
                                                                logger.debug("Sensor: " + tmpOutItem.getMid()
                                                                        + ". Condition is met: "
                                                                        + Long.toString(longValOfSensor)
                                                                        + " >= " + requiredThresholds
                                                                                .getLowerBound().trim());
                                                                consideredValues = 1;
                                                                ResultAggrStruct thisAggrResult = new ResultAggrStruct(
                                                                        tmpOutItem.getMid(),
                                                                        Integer.valueOf(currCapSidStr),
                                                                        Long.toString(longValOfSensor),
                                                                        consideredValues,
                                                                        new TimeIntervalStructure(new Timestamp(
                                                                                Long.valueOf(tmpOutItem.getTis()
                                                                                        .getFromTimestamp()
                                                                                        .getTime())),
                                                                                new Timestamp(Long.valueOf(
                                                                                        tmpOutItem.getTis()
                                                                                                .getToTimestamp()
                                                                                                .getTime()))));
                                                                tmpResForGWFunct.getOut().add(thisAggrResult);
                                                                // DONE: Send an alert notification
                                                                NotificationsFromVSNs newNotify = new NotificationsFromVSNs();
                                                                newNotify.setQueryDefId(pQueryDefId);
                                                                newNotify.setVgwID(myPeerId);
                                                                // get continuation info. Careful, we have not yet replaced the replacemntIDs with the original nodes in the measurements here (it's done later)
                                                                // but we have to set the MoteId to the Original Id and the replacementId to the replacement node
                                                                String[] replaceItem = getLocalReplacemntInfoListItem(
                                                                        localReplacedResources,
                                                                        tmpOutItem.getMid(),
                                                                        tmpOutItem.getSid());
                                                                if (replaceItem != null
                                                                        && replaceItem[0] != null
                                                                        && !replaceItem[0].isEmpty()
                                                                        && replaceItem[0].compareToIgnoreCase(
                                                                                replaceItem[1]) != 0) {
                                                                    newNotify.setMoteID(replaceItem[0]);
                                                                    newNotify.setReplacmntID(
                                                                            tmpOutItem.getMid());
                                                                } else {
                                                                    newNotify.setMoteID(tmpOutItem.getMid());
                                                                    newNotify.setReplacmntID("");
                                                                }
                                                                newNotify.setValue(longValOfSensor);
                                                                if (tmpOutItem.getTis() != null && tmpOutItem
                                                                        .getTis().isTimestampFromDefined())
                                                                    newNotify.setValueTimestamp(
                                                                            Long.toString(tmpOutItem.getTis()
                                                                                    .getFromTimestamp()
                                                                                    .getTime()));
                                                                newNotify.setBoundValue(lowbound);
                                                                newNotify.setRefFunctName(
                                                                        referencedFunctionInCondition
                                                                                .getfuncName());
                                                                newNotify.setRefFunctTriggerSign("gt"); //default for lower bound conditions
                                                                newNotify.setCapabilityCode(
                                                                        tmpOutItem.getSid().trim());
                                                                newNotify.setTimestamp(Long
                                                                        .toString(System.currentTimeMillis()));
                                                                newNotify.setType(
                                                                        NotificationsFromVSNs.CRITICAL_TYPE);
                                                                newNotify.setLevel(
                                                                        NotificationsFromVSNs.GATEWAY_LEVEL);
                                                                newNotify.setRefFunctId(
                                                                        referencedFunctionInCondition
                                                                                .getfuncId());
                                                                newNotify.setMessage(
                                                                        "Condition was met for node id: "
                                                                                + newNotify.getMoteID()
                                                                                + " value: " + longValOfSensor
                                                                                + " capability code:__"
                                                                                + tmpOutItem.getSid().trim());
                                                                // Send the response to the requesting end user
                                                                //System.out.println("Sending Notification!");
                                                                String notifMsgToSend = NotificationsFromVSNs
                                                                        .getAlertDelimitedString(newNotify);
                                                                this.sendResponse(notifMsgToSend);

                                                            } else {
                                                                logger.debug("Sensor: " + tmpOutItem.getMid()
                                                                        + " with value: "
                                                                        + Long.toString(longValOfSensor)
                                                                        + " does not meet Condition!");
                                                            }
                                                        }
                                                    }

                                                }

                                            } catch (Exception e) {
                                                logger.error("Invalid format to aggregate");
                                            }

                                        }
                                    }
                                    //
                                    //
                                }
                            }
                        }
                    }
                }

            }
        }

    }
    // Add trailing section for service deployability and replacements list
    // Careful! for the replacements list, skip the entries where the node replaces itself
    // DONE: RECONSTRUCT the Vector<ReqResultOverData> allUniqueFunctionsWithResults for the original nodes!
    //
    //
    logger.debug("BEFORE RECONSTRUCTION");
    if (allUniqueFunctionsWithResults != null) {
        logger.debug("IN RECONSTRUCTION");
        for (ReqResultOverData aResultOverData : allUniqueFunctionsWithResults) {
            String functionId = aResultOverData.getFid();
            // replacing is needed only for node level functions and possibly for if then functions referring to last values of sensors (not for aggregate GW level or if_then over aggregates)
            // &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&+++++++++++++++++++++++++++++++++++==
            /*
            boolean isGwLevel = false;
            Iterator<ReqFunctionOverData> gwfunctIterLocal =  onlyGwLevelReqFunctVec.iterator();
            while(gwfunctIterLocal.hasNext())     //OUTER loop
            {
            ReqFunctionOverData tmpReqGwFunct = gwfunctIterLocal.next();
            if(Integer.toString(tmpReqGwFunct.getfuncId()).equalsIgnoreCase(functionId)){
                isGwLevel = true;
                break;
            }
                    
            }
            if(!isGwLevel) {
            */
            logger.debug("FID:: " + functionId);
            if (aResultOverData.getAllResultsforFunct() != null) {
                if (aResultOverData.getAllResultsforFunct().isEmpty()) {
                    logger.debug("has no results!!");
                } else {
                    logger.debug("found results!!");
                }

                Vector<ResultAggrStruct> newReconstructedResultVec = null;
                boolean foundAtLeastOneResultForSpecificMoteId = false;
                for (ResultAggrStruct thisResult : aResultOverData.getAllResultsforFunct()) {
                    if (thisResult.getMid()
                            .compareToIgnoreCase(ResultAggrStruct.MidSpecialForAggregateMultipleValues) != 0) {
                        if (!foundAtLeastOneResultForSpecificMoteId) {
                            foundAtLeastOneResultForSpecificMoteId = true;
                            newReconstructedResultVec = new Vector<ResultAggrStruct>();
                        }
                        String[] replaceItem = getLocalReplacemntInfoListItem(localReplacedResources,
                                thisResult.getMid(), thisResult.getSid());
                        if (replaceItem != null && replaceItem[0] != null && !replaceItem[0].isEmpty()) {
                            logger.debug("Back to replacing node :" + thisResult.getMid()
                                    + " with original node: " + replaceItem[0]);
                            thisResult.setMid(replaceItem[0]);
                            newReconstructedResultVec.addElement(thisResult);
                        }
                    }
                }
                if (foundAtLeastOneResultForSpecificMoteId) {
                    aResultOverData.setAllResultsforFunct(newReconstructedResultVec);
                }
            }
            /* } */
        }
    }

    //

    // DEBUG:
    logger.debug("The gateway has collected results and is ready to send them!");
    //return allResultsRead;    // Support for various data types is added by the DataTypeAdapter class
    //    ********************** COAP MESSAGES BACK TO GATEWAY *******************************
    //   ALSO SEND ANY SECURITY MESSAGES
    //   TODO: we could clean the cache after sending these messages (?)
    if (!VitroGatewayService.getVitroGatewayService().isWsiTrustCoapMessagingSupport()) {
        logger.debug("No SUPPORT FOR SENDING TRUST SECURITY INFO back to VSP!");
    }
    if (!VitroGatewayService.getVitroGatewayService().isTrustRoutingCoapMessagingActive()) {
        logger.debug("No ACTIVATION FOR SENDING TRUST SECURITY INFO back to VSP!");
    }

    if (VitroGatewayService.getVitroGatewayService().isWsiTrustCoapMessagingSupport()
            && VitroGatewayService.getVitroGatewayService().isTrustRoutingCoapMessagingActive()) {
        logger.debug("Attempting to send TRUST SECURITY INFO back to VSP!");
        HashMap<String, InfoOnTrustRouting> cacheTrustCoapCopy = new HashMap<String, InfoOnTrustRouting>(
                TrustRoutingQueryService.getInstance().getCachedDirectoryOfTrustRoutingInfo());
        String aRefCapCode = "";
        int aRefFunctId = 1;// last value is always in the request
        if (originalMotesAndTheirSensorAndFunctsVec != null) {
            try {
                aRefCapCode = originalMotesAndTheirSensorAndFunctsVec.firstElement()
                        .getQueriedSensorIdsAndFuncVec().get(0).getSensorModelid();
            } catch (Exception e339) {
                logger.error("Could not acquire sample capability id for security TRUST alert ");
            }
            try {
                aRefFunctId = originalMotesAndTheirSensorAndFunctsVec.firstElement()
                        .getQueriedSensorIdsAndFuncVec().get(0).getFunctionsOverSensorModelVec().firstElement();
            } catch (Exception e339) {
                logger.error("Could not acquire sample function id for security TRUST alert ");
            }
        }
        if (cacheTrustCoapCopy != null) {

            for (String sourceNodeId : cacheTrustCoapCopy.keySet()) {
                InfoOnTrustRouting tmpInfoOnTrust = cacheTrustCoapCopy.get(sourceNodeId);
                HashMap<String, Integer> tmpParentIdToPFiHM = tmpInfoOnTrust.getParentIdsToPFI();
                for (String parentNodeId : tmpParentIdToPFiHM.keySet()) {
                    // TODO: Send a SECURITY notification
                    NotificationsFromVSNs newNotify = new NotificationsFromVSNs();
                    newNotify.setQueryDefId(pQueryDefId);
                    newNotify.setVgwID(myPeerId);
                    newNotify.setMoteID(sourceNodeId);
                    newNotify.setValue(tmpParentIdToPFiHM.get(parentNodeId));
                    // TODO: Demo: change to current timestamp which is more reliable
                    newNotify.setValueTimestamp(Long.toString(System.currentTimeMillis())); // the time stamp for the PFI value
                    newNotify.setTimestamp(Long.toString(System.currentTimeMillis())); //the time stamp of the notification

                    //newNotify.setTimestamp(tmpInfoOnTrust.getTimestamp() );
                    //newNotify.setValueTimestamp(tmpInfoOnTrust.getTimestamp());
                    newNotify.setType(NotificationsFromVSNs.SECURITY_TYPE);
                    newNotify.setLevel(NotificationsFromVSNs.GATEWAY_LEVEL);
                    // we need sample valid funct ids and capability codes related to this VSN , to associate it at the VSP level with a partial service!
                    newNotify.setRefFunctId(aRefFunctId);
                    newNotify.setCapabilityCode(aRefCapCode);
                    // the message field is here used to store the parent ID.
                    newNotify.setMessage(parentNodeId);
                    // Send the response to the requesting end user
                    //System.out.println("Sending Notification!");
                    String notifMsgToSend = NotificationsFromVSNs.getAlertDelimitedString(newNotify);
                    try {
                        this.sendResponse(notifMsgToSend);
                        logger.debug("Sent one TRUST SECURITY INFO back to VSP!");
                    } catch (Exception securSendExc) {
                        logger.error("Could not send Security Type notification", securSendExc);
                    }
                }
            }
        }
        //
        /*
        logger.debug("Sending a dummy message security for TRUST-DEBUG");
        {   //---------------------------------------------------------------------
        // TODO: Send a SECURITY notification
        NotificationsFromVSNs newNotify = new NotificationsFromVSNs();
        newNotify.setQueryDefId(pQueryDefId);
        newNotify.setVgwID(myPeerId);
        newNotify.setMoteID("urn:wisebed:ctitestbed:0xca2");
        newNotify.setValue(400);
        newNotify.setValueTimestamp(Long.toString(new Date().getTime()));
        newNotify.setTimestamp(Long.toString(new Date().getTime()));
        newNotify.setType(NotificationsFromVSNs.SECURITY_TYPE);
        newNotify.setLevel(NotificationsFromVSNs.GATEWAY_LEVEL);
                
        newNotify.setRefFunctId(aRefFunctId);
        newNotify.setCapabilityCode(aRefCapCode);
        // the message field is here used to store the parent ID.
        newNotify.setMessage("urn:wisebed:ctitestbed:0xCC");
        // Send the response to the requesting end user
        //System.out.println("Sending Notification!");
        String notifMsgToSend = NotificationsFromVSNs.getAlertDelimitedString(newNotify);
        try{
            this.sendResponse(notifMsgToSend);
            logger.debug("Sent one TRUST SECURITY INFO back to VSP!");
        }catch(Exception securSendExc){
            logger.error("Could not send Security Type notification" , securSendExc);
        }
                
        //---------------------------------------------------------------------
        }
        */

    } //end of if we have to send the security Coap Routing Trust Messages

    // %%%%%%%%%% DIRECTLY INFORM THE GATEWAY OF PROBLEMATIC DEPLOY STATUS:
    if (serviceDeployImpossible || serviceDeployContinuationEmployed || serviceDeployPartiallyPossible) {
        String aRefMote = "";
        String aRefCapCode = "";
        int aRefFunctId = 1;// last value is always in the request
        if (originalMotesAndTheirSensorAndFunctsVec != null) {
            try {
                aRefMote = originalMotesAndTheirSensorAndFunctsVec.firstElement().getMoteid();
            } catch (Exception e339) {
                logger.error("Could not acquire sample ref node it for DEPLOY ABILITY STATUS alert ");
            }

            try {
                aRefCapCode = originalMotesAndTheirSensorAndFunctsVec.firstElement()
                        .getQueriedSensorIdsAndFuncVec().get(0).getSensorModelid();
            } catch (Exception e339) {
                logger.error("Could not acquire sample capability for DEPLOY ABILITY STATUS alert ");
            }
            try {
                aRefFunctId = originalMotesAndTheirSensorAndFunctsVec.firstElement()
                        .getQueriedSensorIdsAndFuncVec().get(0).getFunctionsOverSensorModelVec().firstElement();
            } catch (Exception e339) {
                logger.error("Could not acquire sample function id for DEPLOY ABILITY STATUS alert ");
            }
        }
        String strMessage = "";
        long deployValue = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_POSSIBLE_INT;
        if (serviceDeployImpossible) {
            strMessage = "The requested VSN cannot be supported by this island: " + myPeerId;
            // case ResponseAggrMsg.DEPLOY_STATUS_SERVICE_IMPOSSIBLE;
            deployValue = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_IMPOSSIBLE_INT;
        } else if (serviceDeployContinuationEmployed && serviceDeployPartiallyPossible) {
            // case ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL_CONT_COMBO;
            strMessage = "The requested VSN is partially supported using service continuation on this island: "
                    + myPeerId;

            deployValue = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL_CONT_COMBO_INT;
        } else if (serviceDeployContinuationEmployed) {
            // case ResponseAggrMsg.DEPLOY_STATUS_SERVICE_CONTINUATION;
            strMessage = "The requested VSN is supported using service continuation on this island: "
                    + myPeerId;
            deployValue = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_CONTINUATION_INT;
        } else if (serviceDeployPartiallyPossible) {
            // case ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL;
            strMessage = "The requested VSN is partially supported on this island: " + myPeerId;
            deployValue = ResponseAggrMsg.DEPLOY_STATUS_SERVICE_PARTIAL_INT;
        }
        // SEND THE NOTIFICATION::
        // TODO: Send a DEPLOY_STATUS_TYPE notification
        NotificationsFromVSNs newNotify = new NotificationsFromVSNs();
        newNotify.setQueryDefId(pQueryDefId);
        newNotify.setVgwID(myPeerId);
        newNotify.setMoteID(aRefMote);
        newNotify.setValue(deployValue);
        // TODO: Demo: change to current timestamp which is more reliable
        newNotify.setValueTimestamp(Long.toString(System.currentTimeMillis())); // the time stamp for the PFI value
        newNotify.setTimestamp(Long.toString(System.currentTimeMillis())); //the time stamp of the notification

        //newNotify.setTimestamp(tmpInfoOnTrust.getTimestamp() );
        //newNotify.setValueTimestamp(tmpInfoOnTrust.getTimestamp());
        newNotify.setType(NotificationsFromVSNs.DEPLOY_STATUS_TYPE);
        newNotify.setLevel(NotificationsFromVSNs.GATEWAY_LEVEL);
        // we need sample valid funct ids and capability codes related to this VSN , to associate it at the VSP level with a partial service!
        newNotify.setRefFunctId(aRefFunctId);
        newNotify.setCapabilityCode(aRefCapCode);
        // the message field is here used to store the parent ID.
        newNotify.setMessage(strMessage);
        // Send the response to the requesting end user
        //System.out.println("Sending Notification!");
        String notifMsgToSend = NotificationsFromVSNs.getAlertDelimitedString(newNotify);
        try {
            this.sendResponse(notifMsgToSend);
            logger.debug("Sent one DEPLOY STATUS info back to VSP!");
        } catch (Exception securSendExc) {
            logger.error("Could not send DEPLOY STATUS notification", securSendExc);
        }
    }
    return allUniqueFunctionsWithResults;
}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * LOCK Method.//from w ww .ja  v a  2s.  c om
 */
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(SakaidavStatus.SC_LOCKED);
        return;
    }

    LockInfo lock = new LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = req.getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }

    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
            }

        } else {
            // Bad request
            resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
            }

        } else {
            // Bad request
            resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                resp.setStatus(SakaidavStatus.SC_BAD_REQUEST);
            }

            // contribute feeds us an owner that looks
            // like <A:href>...</A:href>. Since we'll put it
            // back with a different namespace prefix, we
            // don't want to save it that way.

            lock.owner = lock.owner.replaceAll("<(/?)[^>]+:([hH][rR][eE][fF])>", "<$1$2>");
            // System.out.println("lock.owner: " + lock.owner);

        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(req);
    String lockToken = null;

    lock.path = path;

    // Retrieve the resources
    // DirContext resources = getResources();
    DirContextSAKAI resources = getResourcesSAKAI();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    // We don't want to allow just anyone to lock a resource.
    // It seems reasonable to allow it only for someone who
    // is allowed to modify it.
    if (prohibited(path) || !(exists ? contentHostingService.allowUpdateResource(adjustId(path))
            : contentHostingService.allowAddResource(adjustId(path)))) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN, path);
        return;
    }

    Enumeration<LockInfo> locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-"
                + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        lockToken = MD5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector<String> lockPaths = new Vector<String>();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration<String> lockPathsList = lockPaths.elements();

                resp.setStatus(SakaidavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement("D", "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement("D", "response", XMLWriter.OPENING);
                    generatedXML.writeElement("D", "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement("D", "href", XMLWriter.CLOSING);
                    generatedXML.writeElement("D", "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + SakaidavStatus.SC_LOCKED + " "
                            + SakaidavStatus.getStatusText(SakaidavStatus.SC_LOCKED));
                    generatedXML.writeElement("D", "status", XMLWriter.CLOSING);

                    generatedXML.writeElement("D", "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);

                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;

            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        resp.sendError(SakaidavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(SakaidavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }

            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }

        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            LockInfo presentLock = (LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(SakaidavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector<String> lockNulls = lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector<String>();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    lockNulls.addElement(lock.path);

                }

            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = req.getHeader("If");
        if (ifHeader == null)
            ifHeader = "";

        // Checking resource locks

        LockInfo toRenew = (LockInfo) resourceLocks.get(path);
        Enumeration<String> tokenList = null;
        if ((lock != null) && (toRenew != null) && (toRenew.tokens != null)) {
            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }
        }

        // Checking inheritable collection locks

        Enumeration<LockInfo> collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement("D", "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML, true);

    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement("D", "prop", XMLWriter.CLOSING);

    /* the RFC requires this header in response to lock creation */

    if (lockRequestType == LOCK_CREATION)
        resp.addHeader("Lock-Token", "opaquelocktoken:" + lockToken);

    resp.setStatus(exists ? SakaidavStatus.SC_OK : SakaidavStatus.SC_CREATED);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

From source file:org.kepler.objectmanager.data.text.TextComplexFormatDataReader.java

/**
 * This method will read one row from inputstream and return a data vector
 * which element is String and the value is field data. After reach the end
 * of stream, empty vector will be returned. So this method can be iterated
 * by a while loop until a empty vector hited. During the iteration, every
 * data in the stream will be pulled out.
 * //from ww w.ja  v a 2  s  . c o  m
 * @return Vector
 */
public Vector getRowDataVectorFromStream() throws Exception {
    Vector oneRowDataVector = new Vector();
    StringBuffer lineDelimiterBuffer = new StringBuffer();// to store
    // delmiter
    StringBuffer fieldValueBuffer = new StringBuffer();
    int singleCharactor = -2;
    int columnCount = 1;// this is for every character in one row
    int attributeCount = 0; // this is for every attribute
    boolean startNewAttribute = true;
    boolean isWidthFix = true;
    int width = -1;
    int widthCount = 0;
    boolean startWidthCount = false;
    int startColumnNumberFromFormat = -1;
    String fieldDelimiter = null;

    if (dataStream != null) {
        singleCharactor = dataStream.read();

        while (singleCharactor != -1) {
            char charactor = (char) singleCharactor;
            // strip header
            if (stripHeader && numberOfHeaderLines > 0 && headLineNumberCount < numberOfHeaderLines) {
                lineDelimiterBuffer.append(charactor);
                if (lineDelimiterBuffer.length() == physicalLineDelimiterLength
                        && lineDelimiterBuffer.toString().equals(physicalLineDelimiter)) {
                    // reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                    headLineNumberCount++;
                } else if (lineDelimiterBuffer.length() == physicalLineDelimiterLength) {
                    // reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                }

            } else {
                // handle data after strip header
                fieldValueBuffer.append(charactor);
                lineDelimiterBuffer.append(charactor);

                // set up format info
                if (startNewAttribute) {
                    startNewAttribute = false;
                    // find the format from array
                    TextComplexDataFormat format = formats[attributeCount];
                    if (format == null) {
                        throw new Exception("The text format is null for an attribute");
                    } else if (format instanceof TextWidthFixedDataFormat) {
                        TextWidthFixedDataFormat widthFormat = (TextWidthFixedDataFormat) format;
                        width = widthFormat.getFieldWidth();
                        startColumnNumberFromFormat = widthFormat.getFieldStartColumn();
                        isWidthFix = true;
                        startWidthCount = false;

                    } else if (format instanceof TextDelimitedDataFormat) {
                        TextDelimitedDataFormat delimitedFormat = (TextDelimitedDataFormat) format;
                        fieldDelimiter = delimitedFormat.getFieldDelimiter();
                        isWidthFix = false;
                    }
                }

                if (isWidthFix) {
                    // find start cloumn if metadata specify it
                    if (startColumnNumberFromFormat != -1 && startColumnNumberFromFormat == columnCount) {
                        fieldValueBuffer = new StringBuffer();
                        fieldValueBuffer.append(charactor);
                        startWidthCount = true;
                    } else if (startColumnNumberFromFormat == -1) {
                        startWidthCount = true;
                    }
                    // start count width
                    if (startWidthCount) {
                        widthCount++;
                    }
                    // we got the value when widthcount reach width of this
                    // format
                    if (widthCount == width) {
                        String value = fieldValueBuffer.toString();
                        log.debug("Add width fixed attribute value " + value + " to the vector");
                        oneRowDataVector.add(value.trim());
                        widthCount = 0;
                        startWidthCount = false;
                        fieldValueBuffer = new StringBuffer();
                        startNewAttribute = true;
                        attributeCount++;
                    }

                } else {
                    // for delimter data
                    if (fieldValueBuffer.toString().endsWith(fieldDelimiter)) {
                        String value = fieldValueBuffer.toString();
                        value = value.substring(0, value.length() - fieldDelimiter.length());
                        log.debug("Add delimited attribute value " + value + " to the vector");
                        oneRowDataVector.add(value.trim());
                        fieldValueBuffer = new StringBuffer();
                        startNewAttribute = true;
                        attributeCount++;
                    }
                }

                columnCount++;

                // reset columnCount to 1 when hit a physical line delimiter
                if (lineDelimiterBuffer.length() == physicalLineDelimiterLength
                        && lineDelimiterBuffer.toString().equals(physicalLineDelimiter)) {
                    // reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                    columnCount = 1;
                } else if (lineDelimiterBuffer.length() == physicalLineDelimiterLength) {
                    // reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                }

                // get a row vector break it.
                if (attributeCount == numberOfAttirbute) {
                    break;
                }
            }
            singleCharactor = dataStream.read();
        }

    }
    // if row vector is not empty and its length less than number of
    // attribute,
    // we should add "" string to make its' length equals attribute length;
    if (!oneRowDataVector.isEmpty() && oneRowDataVector.size() < numberOfAttirbute) {
        int size = oneRowDataVector.size();
        for (int i = size; i < numberOfAttirbute; i++) {
            oneRowDataVector.add(DEFAULTVALUE);
        }
    }
    return oneRowDataVector;
}

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

@SuppressWarnings("unchecked")
    protected void sequentialXMLImportRecordSet(Element dbImport, String dbTable, String parentName,
            long parentId) {
        try {/*from   w  ww  .  ja v  a  2 s.  c om*/
            String id = new String();
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            // get the records
            List records = dbImport.selectNodes("//" + dbTable); //$NON-NLS-1$
            //String lowerdbTable = lowerFirstChar(dbTable);
            DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            String primaryKey = info.getPrimaryKeyName();
            List ids = dbImport.selectNodes("//" + primaryKey); //$NON-NLS-1$

            if (records.size() < 1) {
                log.debug("Cannot import. Given database type:" + dbTable //$NON-NLS-1$
                        + " does not exsist in import file"); //$NON-NLS-1$
            } else {
                // loop for each record
                for (int k = 0; k < records.size(); k++) {
                    Vector collectionIds = new Vector(20);
                    Vector collectionNames = new Vector(20);
                    // keep this id to compare against it's collection
                    Element idElement = (Element) ids.get(k);
                    id = idElement.getStringValue();
                    // make the agent and the element
                    Object agent = parentInfo.getClassObj().newInstance();
                    Map<String, Object> agentMap = new HashMap<String, Object>();
                    Element dbElement = (Element) records.get(k);
                    Iterator i = dbElement.elementIterator();
                    do {// do for each element in the record
                        Element element = (Element) i.next();

                        Object value = findTypeRecordSet(element, dbTable, parentId, parentName);// the
                                                                                                 // parent
                                                                                                 // is
                                                                                                 // itself,
                                                                                                 // just
                                                                                                 // a
                                                                                                 // dummy
                                                                                                 // variable
                        if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {
                            agentMap.put(element.getName(), value);
                        }
                        // ignore many-to-many for now
                        else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {// RECURSE
                         // get assoicated ids
                            List temp_collection_ids = element
                                    .selectNodes("//" + dbTable + "[" + primaryKey + " = \"" + id //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                                            + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$
                            // get collection info and still dont add it
                            if (!temp_collection_ids.isEmpty()) {
                                // get child dbName
                                String childDbName = getDbName(temp_collection_ids);
                                collectionNames.addElement(childDbName);
                                for (int index = 0; index < temp_collection_ids.size(); index++) {
                                    collectionIds.addElement(temp_collection_ids.get(index));
                                }
                            }
                        } else
                        // else, dont add it
                        {
                            // if it is an id, just ignore. otherwise print out error
                            if (!element.getName().equals(primaryKey)) {
                                log.debug("did not add " + element.getName() //$NON-NLS-1$
                                        + " to the element " + dbTable); //$NON-NLS-1$
                            }
                        }
                    } while (i.hasNext());

                    // populate and save
                    BeanUtils.populate(agent, agentMap);

                    this.session.save(agent);

                    // if there was a collection, then recurse
                    if (!collectionIds.isEmpty()) {
                        long newParentId = new Long(session.getIdentifier(agent).toString()).longValue();
                        // import all children
                        sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId);
                    }
                }
            }
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        }
    }

From source file:edu.lternet.pasta.dml.database.TextComplexFormatDataReader.java

/**
 * This method will read one row from inputstream and return a data vector 
 * which element is String and the value is field data. After reach the end 
 * of stream, empty vector will be returned. So this method can be iterated 
 * by a while loop until a empty vector hited. During the iteration, every 
 * data in the stream will be pulled out.
 * /*from   w  ww . jav  a 2 s .c  o  m*/
 * @return Vector
 */
public Vector getOneRowDataVector() throws Exception {
    Vector oneRowDataVector = new Vector();
    StringBuffer lineDelimiterBuffer = new StringBuffer();// to store delmiter
    StringBuffer fieldValueBuffer = new StringBuffer();
    int singleCharactor = -2;
    int columnCount = 1;// this is for every character in one row
    int attributeCount = 0; // this is for every attribute
    boolean startNewAttribute = true;
    boolean isWidthFix = true;
    int width = -1;
    int widthCount = 0;
    boolean startWidthCount = false;
    int startColumnNumberFromFormat = -1;
    String fieldDelimiter = null;

    if (dataStream != null) {
        singleCharactor = dataStream.read();

        while (singleCharactor != -1) {
            char charactor = (char) singleCharactor;
            // strip header
            if (stripHeader && numberOfHeaderLines > 0 && headLineNumberCount < numberOfHeaderLines) {
                lineDelimiterBuffer.append(charactor);
                if (lineDelimiterBuffer.length() == physicalLineDelimiterLength
                        && lineDelimiterBuffer.toString().equals(physicalLineDelimiter)) {
                    //reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                    headLineNumberCount++;
                } else if (lineDelimiterBuffer.length() == physicalLineDelimiterLength) {
                    // reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                }

            } else {
                // handle data after strip header
                fieldValueBuffer.append(charactor);
                lineDelimiterBuffer.append(charactor);

                // set up format info
                if (startNewAttribute) {
                    startNewAttribute = false;
                    //find the format from array
                    TextComplexDataFormat format = formats[attributeCount];
                    if (format == null) {
                        throw new Exception("The text format is null for an attribute");
                    } else if (format instanceof TextWidthFixedDataFormat) {
                        TextWidthFixedDataFormat widthFormat = (TextWidthFixedDataFormat) format;
                        width = widthFormat.getFieldWidth();
                        startColumnNumberFromFormat = widthFormat.getFieldStartColumn();
                        isWidthFix = true;
                        startWidthCount = false;

                    } else if (format instanceof TextDelimitedDataFormat) {
                        TextDelimitedDataFormat delimitedFormat = (TextDelimitedDataFormat) format;
                        fieldDelimiter = delimitedFormat.getFieldDelimiter();
                        isWidthFix = false;
                    }
                }

                if (isWidthFix) {
                    // find start cloumn if metadata specify it
                    if (startColumnNumberFromFormat != -1 && startColumnNumberFromFormat == columnCount) {
                        fieldValueBuffer = new StringBuffer();
                        fieldValueBuffer.append(charactor);
                        startWidthCount = true;
                    } else if (startColumnNumberFromFormat == -1) {
                        startWidthCount = true;
                    }
                    // start count width
                    if (startWidthCount) {
                        widthCount++;
                    }
                    // we got the value when widthcount reach width of this format
                    if (widthCount == width) {
                        String value = fieldValueBuffer.toString();
                        //log.debug("Add width fixed attribute value " + value +
                        //       " to the vector");
                        oneRowDataVector.add(value.trim());
                        widthCount = 0;
                        startWidthCount = false;
                        fieldValueBuffer = new StringBuffer();
                        startNewAttribute = true;
                        attributeCount++;
                    }

                } else {
                    // for delimter data
                    if (fieldValueBuffer.toString().endsWith(fieldDelimiter)) {
                        String value = fieldValueBuffer.toString();
                        value = value.substring(0, value.length() - fieldDelimiter.length());
                        //log.debug("Add delimited attribute value " + value +
                        //        " to the vector" );
                        oneRowDataVector.add(value.trim());
                        fieldValueBuffer = new StringBuffer();
                        startNewAttribute = true;
                        attributeCount++;
                    }
                }

                columnCount++;

                // reset columnCount to 1 when hit a physical line delimiter
                if (lineDelimiterBuffer.length() == physicalLineDelimiterLength
                        && lineDelimiterBuffer.toString().equals(physicalLineDelimiter)) {
                    //reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                    columnCount = 1;
                } else if (lineDelimiterBuffer.length() == physicalLineDelimiterLength) {
                    // reset the delimiter buffer
                    lineDelimiterBuffer = new StringBuffer();
                }

                // get a row vector break it.
                if (attributeCount == numberOfAttirbute) {
                    break;
                }
            }

            singleCharactor = dataStream.read();
        }
    }

    // if row vector is not empty and its length less than number of 
    // attributes, we should add "" string to make its length equal to
    // the attribute length.
    if (!oneRowDataVector.isEmpty() && oneRowDataVector.size() < numberOfAttirbute) {
        int size = oneRowDataVector.size();

        for (int i = size; i < numberOfAttirbute; i++) {
            oneRowDataVector.add(DEFAULTVALUE);
        }
    }

    return oneRowDataVector;
}

From source file:org.sakaiproject.calendar.tool.CalendarAction.java

protected Vector getNewEvents(int year, int month, int day, CalendarActionState state, RunData rundata,
        int time, int numberofcycles, Context context, CalendarEventVector CalendarEventVectorObj) {
    boolean firstTime = true; // Don't need to do complex checking the first time.
    Vector events = new Vector(); // A vector of vectors, each of the vectors containing a range of previous events.

    Time timeObj = TimeService.newTimeLocal(year, month, day, time, 00, 00, 000);

    long duration = ((30 * 60) * (1000));
    Time updatedTime = TimeService.newTime(timeObj.getTime() + duration);

    /*** include the start time ***/
    TimeRange timeRangeObj = TimeService.newTimeRange(timeObj, updatedTime, true, false);

    for (int range = 0; range <= numberofcycles; range++) {
        Iterator calEvent = null;

        calEvent = CalendarEventVectorObj.getEvents(timeRangeObj);

        Vector vectorObj = new Vector(); // EventDisplay of calevent.
        EventDisplayClass eventDisplayObj;
        Vector newVectorObj = null; // Ones we haven't see before?
        boolean swapflag = true;
        EventDisplayClass eventdisplayobj = null;

        if (calEvent.hasNext()) // While we still have more events in this range.
        {/*from  www .  j  a v  a 2s.co m*/
            int i = 0; // Size of vectorObj
            while (calEvent.hasNext()) {
                eventdisplayobj = new EventDisplayClass();
                eventdisplayobj.setEvent((CalendarEvent) calEvent.next(), false, i);

                vectorObj.add(i, eventdisplayobj); // Copy into vector, wrapping in EventDisplay
                i++;
            } // while

            if (firstTime) // First range
            {
                events.add(range, vectorObj);
                firstTime = false;
            } else {
                while (swapflag == true) {
                    swapflag = false;
                    for (int mm = 0; mm < events.size(); mm++) // Loop through all the previous ranges.
                    {
                        // 
                        Vector evectorObj = (Vector) events.elementAt(mm); // One vector range.
                        if (!evectorObj.isEmpty()) {
                            for (int eom = 0; eom < evectorObj.size(); eom++) // loop through previous range.
                            {
                                if (!"".equals(evectorObj.elementAt(eom))) {
                                    // Event ID.
                                    String eomId = (((EventDisplayClass) evectorObj.elementAt(eom)).getEvent())
                                            .getId();
                                    newVectorObj = new Vector();
                                    for (int mv = 0; mv < vectorObj.size(); mv++) // Loop back through the current range.
                                    {
                                        if (!"".equals(vectorObj.elementAt(mv))) {
                                            String vectorId = (((EventDisplayClass) vectorObj.elementAt(mv))
                                                    .getEvent()).getId();
                                            if (vectorId.equals(eomId)) // Exists in a previous range.
                                            {
                                                eventDisplayObj = (EventDisplayClass) vectorObj.elementAt(mv);
                                                eventDisplayObj.setFlag(true);
                                                if (mv != eom) // index of current range, 
                                                {
                                                    swapflag = true;
                                                    vectorObj.removeElementAt(mv);
                                                    for (int x = 0; x < eom; x++) {
                                                        if (!vectorObj.isEmpty()) {
                                                            newVectorObj.add(x, vectorObj.elementAt(0)); // Copy data into new array.
                                                            vectorObj.removeElementAt(0);
                                                        } else {
                                                            newVectorObj.add(x, "");
                                                        }
                                                    } // for
                                                    newVectorObj.add(eom, eventDisplayObj); // Add the one that's out of position.
                                                    int neweom = eom;
                                                    neweom = neweom + 1;

                                                    while (vectorObj.isEmpty() == false) {
                                                        newVectorObj.add(neweom, vectorObj.elementAt(0));
                                                        vectorObj.removeElementAt(0);
                                                        neweom++;
                                                    }

                                                    for (int vv = 0; vv < newVectorObj.size(); vv++) {
                                                        vectorObj.add(vv, newVectorObj.elementAt(vv));
                                                    }
                                                } // if
                                            } // if
                                        } // if
                                    } //for
                                } // if
                            } // for
                        } // if
                    } // for
                } // while

                events.add(range, vectorObj);
            } // if - else firstTime

            timeRangeObj.shiftForward(1800000);
        } else {
            events.add(range, vectorObj);
            timeRangeObj.shiftForward(1800000);
        }
    } // for
    return events;
}

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

@SuppressWarnings("unchecked")
    protected void sequentialXMLImport(Element dbImport, String dbTable, String parentName, long parentId) {
        try {/*  w  w w.  j av a2s  .c o  m*/
            String id = new String();
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());

            List records = dbImport.selectNodes("//" + dbTable); //$NON-NLS-1$
            String lowerdbTable = lowerFirstChar(dbTable);
            // TODO: should not assume that is the id name, use getPrimaryKeyName
            DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            String primaryKey = info.getPrimaryKeyName();
            // List ids = dbImport.selectNodes("//"+lowerdbTable+"Id");//assume this is dbs id name
            List ids = dbImport.selectNodes("//" + primaryKey); //$NON-NLS-1$

            if (records.size() < 1) {
                log.debug("Cannot import. Given database type:" + dbTable //$NON-NLS-1$
                        + " does not exsist in import file"); //$NON-NLS-1$
            } else {
                // loop for each record
                for (int k = 0; k < records.size(); k++) { //
                    Vector collectionIds = new Vector(20);
                    Vector<String> collectionNames = new Vector(20);
                    // keep this id to compare against it's collection
                    Element idElement = (Element) ids.get(k);
                    // id = attribute.getText();
                    id = idElement.getStringValue();
                    // make the agent and the element
                    Object agent = parentInfo.getClassObj().newInstance();
                    Map<String, Object> agentMap = new HashMap<String, Object>();
                    Element dbElement = (Element) records.get(k);
                    Iterator i = dbElement.elementIterator();
                    do {// do for each element in the record
                        Element element = (Element) i.next();

                        Object value = findTypeSequential(element, dbTable, parentId, parentName);// the
                                                                                                  // parent
                                                                                                  // is
                                                                                                  // itself,
                                                                                                  // just
                                                                                                  // a
                                                                                                  // dummy
                                                                                                  // variable
                                                                                                  // if(value!=null && value != "collection")
                        if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {
                            agentMap.put(element.getName(), value);

                        }
                        // ignore many-to-many for now
                        else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                        {// RECURSE
                         // get assoicated ids
                         // List temp_collection_ids =
                         // element.selectNodes("//"+dbTable+"["+id+"]/"+element.getName()+"/*");//+upperElement);
                            List temp_collection_ids = element
                                    .selectNodes("//" + dbTable + "[" + primaryKey + " = \"" + id //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                                            + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$
                            // get collection info and still dont add it
                            if (!temp_collection_ids.isEmpty()) {
                                // get child dbName
                                String childDbName = getDbName(temp_collection_ids);
                                collectionNames.addElement(childDbName);
                                for (int index = 0; index < temp_collection_ids.size(); index++) {
                                    collectionIds.addElement(temp_collection_ids.get(index));
                                }
                            }
                        } else
                        // else, dont add it
                        {
                            // if it is an id, just ignore. otherwise print out error
                            if (!element.getName().equals(lowerdbTable + "Id")) //$NON-NLS-1$
                            {
                                log.debug("did not add " + element.getName() //$NON-NLS-1$
                                        + " to the element " + dbTable); //$NON-NLS-1$
                            }
                        }
                    } while (i.hasNext());

                    // populate and save
                    BeanUtils.populate(agent, agentMap);

                    this.session.save(agent);
                    // session.lock(agent, LockMode.NONE);

                    // if there was a collection, then recurse
                    if (!collectionIds.isEmpty()) {
                        long newParentId = new Long(session.getIdentifier(agent).toString()).longValue();

                        sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId);
                    }
                }
            }
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            // String err = ex.toString();
            // the last par tof the string conatins the class
            // if(err.startsWith("org.hibernate.PropertyValueException")){
            try {
                // try again
                // flush
                // do reference work
                // importTable("ReferenceWork");
                // the import aagain
            } catch (Exception ex1) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex1);
                ex1.printStackTrace();
            }
            // }else{
            ex.printStackTrace();
            // }
        }
    }