Example usage for java.util Vector contains

List of usage examples for java.util Vector contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this vector contains the specified element.

Usage

From source file:gov.nih.nci.evs.browser.utils.DataUtils.java

public static HashMap getPropertyValueHashMap(Entity c) {
    if (c == null) {
        return null;
    }//from  ww w.  ja  va 2 s .  c om
    HashMap hmap = new HashMap();
    Property[] properties = c.getProperty();
    for (int j = 0; j < properties.length; j++) {
        Property prop = properties[j];
        String prop_name = prop.getPropertyName();
        String prop_value = prop.getValue().getContent();

        String source = getPropertySource(prop);
        if (source == null)
            source = "None";
        prop_value = prop_value + "|" + source;
        Vector u = new Vector();
        if (hmap.containsKey(prop_name)) {
            u = (Vector) hmap.get(prop_name);
        } else {
            u = new Vector();
        }
        if (!u.contains(prop_value)) {
            u.add(prop_value);
            hmap.put(prop_name, u);
        }
    }
    properties = c.getPresentation();
    for (int j = 0; j < properties.length; j++) {
        Property prop = properties[j];
        String prop_name = prop.getPropertyName();
        String prop_value = prop.getValue().getContent();
        String source = getPropertySource(prop);
        if (source == null)
            source = "None";
        prop_value = prop_value + "|" + source;

        Vector u = new Vector();
        if (hmap.containsKey(prop_name)) {
            u = (Vector) hmap.get(prop_name);
        } else {
            u = new Vector();
        }
        if (!u.contains(prop_value)) {
            u.add(prop_value);
            hmap.put(prop_name, u);
        }
    }
    properties = c.getDefinition();
    for (int j = 0; j < properties.length; j++) {
        Property prop = properties[j];
        String prop_name = prop.getPropertyName();
        String prop_value = prop.getValue().getContent();
        String source = getPropertySource(prop);
        if (source == null)
            source = "None";
        prop_value = prop_value + "|" + source;

        Vector u = new Vector();
        if (hmap.containsKey(prop_name)) {
            u = (Vector) hmap.get(prop_name);
        } else {
            u = new Vector();
        }
        if (!u.contains(prop_value)) {
            u.add(prop_value);
            hmap.put(prop_name, u);
        }
    }
    properties = c.getComment();
    for (int j = 0; j < properties.length; j++) {
        Property prop = properties[j];
        String prop_name = prop.getPropertyName();
        String prop_value = prop.getValue().getContent();
        String source = getPropertySource(prop);
        if (source == null)
            source = "None";
        prop_value = prop_value + "|" + source;

        Vector u = new Vector();
        if (hmap.containsKey(prop_name)) {
            u = (Vector) hmap.get(prop_name);
        } else {
            u = new Vector();
        }
        if (!u.contains(prop_value)) {
            u.add(prop_value);
            hmap.put(prop_name, u);
        }
    }
    return hmap;
}

From source file:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java

/**
 * TODO: IMPORTANT !!!/*from   w  w  w . j  a  v a  2s.co  m*/
 *
 * Updates the list with the controlled WSI's capabilities
 */
public synchronized CGatewayWithSmartDevices createWSIDescr(CGateway givGatewayInfo) {
    //
    //
    //
    if (DEBUG_OFFLINE_MODE) {
        return DEBUG_offline_createWSIDescr(givGatewayInfo);
    }
    //
    Vector<CSmartDevice> currSmartDevicesVec = new Vector<CSmartDevice>();
    CGatewayWithSmartDevices myGatewayForSmartDevs = new CGatewayWithSmartDevices(givGatewayInfo,
            currSmartDevicesVec);

    // An auxiliary structure that maps Unique Generic Capability Descriptions to Lists of SensorTypes ids.
    HashMap<String, Vector<Integer>> myAllCapabilitiesToSensorModelIds = new HashMap<String, Vector<Integer>>();

    //
    // ##########################################################################################################################################
    // ##########################################################################################################################################
    //
    /*
     * TODO: optimize the status/resource retrieval process for uberdust!
     * TODO: Take into account the mote status before ADDING it to the gateway description list (++++ LATER)
     *         For now we assume that the queries to the actual WSN are handled by the middleware.
     *         We search the uberdust "database" for data. (but we can still perform actions to affect the WSI!)
     *
     *         The plan is for a future service
     *         where a peer could submit queries for submission in the actual WSNs, and subsequently gather the data
     *         of the results. (e.g. administration service>reprogramming service)
     */
    HttpClient httpclient = new DefaultHttpClient();
    try {
        //
        //
        // TODO: x, y, z can be used with wisedb Coordinate.java (look code) to produce GoogleEarth Coordinates (what ISO is that? Can it be advertised in SensorML for IDAS ?)
        // TODO: make use of Description and Type and Room Fields when available ?
        // TODO: Make a summary, how many valid from those found in uberdust? How many were registered successfully? How many measurements were registered successfully?
        //
        //
        boolean gotResponseFromHttpNodesGet = false;
        boolean gotResponseFromHttpNodes_STATUS_Get = false;
        boolean gotResponseFromHttpNodes_ADMINSTATUS_Get = false;

        String responseBodyStr = "";

        HttpGet httpUberdustNodesGet = new HttpGet(uberdustNodesGetRestUri);
        HttpResponse httpUberdustNodesGetResponse = httpclient.execute(httpUberdustNodesGet);

        int httpUberdustNodesGetResponseStatusCode = httpUberdustNodesGetResponse.getStatusLine()
                .getStatusCode();
        HttpEntity httpUberdustNodesGetResponseEntity = httpUberdustNodesGetResponse.getEntity();
        if (httpUberdustNodesGetResponseEntity != null) {

            responseBodyStr = EntityUtils.toString(httpUberdustNodesGetResponseEntity);
            if (httpUberdustNodesGetResponseStatusCode != 200) {
                // responseBody will have the error response
                logger.debug("--------ERROR Response: " + httpUberdustNodesGetResponseStatusCode
                        + "------------------------------");
                logger.debug(responseBodyStr);
                logger.debug("----------------------------------------");
            } else {
                //logger.debug("--------OK Response: "+ httpUberdustNodesGetResponseStatusCode+"------------------------------");
                //
                String[] nodeUrnsInUberdust = responseBodyStr.split("\\r?\\n");
                int totalNodeUrnsInUberdust = nodeUrnsInUberdust.length;

                HttpGet httpUberdustNodes_STATUS_Get = new HttpGet(uberdustNodes_Status_GetRestUri);
                HttpResponse httpUberdustNodes_STATUS_GetResponse = httpclient
                        .execute(httpUberdustNodes_STATUS_Get);

                int httpUberdustNodes_STATUS_GetResponseStatusCode = httpUberdustNodes_STATUS_GetResponse
                        .getStatusLine().getStatusCode();
                HttpEntity httpUberdustNodes_STATUS_GetResponseEntity = httpUberdustNodes_STATUS_GetResponse
                        .getEntity();
                if (httpUberdustNodes_STATUS_GetResponseEntity != null) {
                    String responseBody_STATUS_Str = EntityUtils
                            .toString(httpUberdustNodes_STATUS_GetResponseEntity);
                    if (httpUberdustNodes_STATUS_GetResponseStatusCode != 200) {
                        // responseBody_STATUS_Str will have the error response
                        logger.debug("--------ERROR Response: " + httpUberdustNodes_STATUS_GetResponseStatusCode
                                + "------------------------------");
                        logger.debug(responseBody_STATUS_Str);
                        logger.debug("----------------------------------------");
                    } else {
                        //logger.debug("--------OK Response: "+ httpUberdustNodes_STATUS_GetResponseStatusCode+"------------------------------");

                        String[] nodeAndLastCapReadingsUrnsInUberdust = responseBody_STATUS_Str
                                .split("\\r?\\n");
                        int totalNodeWithCapsInUberdust = nodeAndLastCapReadingsUrnsInUberdust.length;

                        //TODO: test this:
                        Vector<String> allFaultyNodesUrns = getFaultyNodes();

                        // LOOP OVER EVERY NODE (smart device), and for each node, get its capabilities from the second response (responseBody_STATUS_Str)
                        for (String aNodeUrnsInUberdust : nodeUrnsInUberdust) {
                            if (allFaultyNodesUrns.contains(aNodeUrnsInUberdust)) {
                                logger.debug("Skiipping node: " + aNodeUrnsInUberdust);
                                continue; //skip faulty nodes!
                            }

                            //                                logger.debug("Iteration " + String.valueOf(k+1) + " of " + String.valueOf(totalNodeUrnsInUberdust));
                            //                                logger.debug(nodeUrnsInUberdust[k]);

                            Vector<Integer> sensorModels_IDs_OfSmartDevVector = new Vector<Integer>();// todo: fix this redundancy!
                            Vector<CSensorModel> sensorModelsOfSmartDevVector = new Vector<CSensorModel>();
                            CSmartDevice tmpSmartDev = new CSmartDevice(aNodeUrnsInUberdust,
                                    "", /* smart device type name */
                                    "", /* location description e.g. room1*/
                                    new GeodesicPoint(), /*  */
                                    sensorModels_IDs_OfSmartDevVector);

                            // TODO: Add an extra early for loop to update the fields for the attributes of the SmartDevice such as:
                            //      Eventually if the SmartDev has NO other valid sensors (e.g. observation sensors or actuators) then it won't be added !
                            String tmp_longitude = "";
                            String tmp_latitude = "";
                            String tmp_altitude = "";

                            for (String aNodeAndLastCapReadingsUrnsInUberdust1 : nodeAndLastCapReadingsUrnsInUberdust) {
                                //to update the device attributes!
                                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust1
                                        .split("\\t");
                                if (nodeCapAndReadingRowItems.length > 3 && nodeCapAndReadingRowItems[0]
                                        .compareToIgnoreCase(aNodeUrnsInUberdust) == 0) {

                                    // [0] is mote (smart device) id
                                    // [1] is capability
                                    // [2] is timestamp
                                    // [3] is measurement value
                                    if ((nodeCapAndReadingRowItems[1] != null)
                                            && !(nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase(""))) {
                                        if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("room")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            {
                                                tmpSmartDev
                                                        .setLocationDesc(nodeCapAndReadingRowItems[3].trim());
                                            }
                                        } else if (nodeCapAndReadingRowItems[1].trim()
                                                .equalsIgnoreCase("nodetype")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            tmpSmartDev.setName(nodeCapAndReadingRowItems[3].trim());
                                        } else if (nodeCapAndReadingRowItems[1].trim()
                                                .equalsIgnoreCase("description")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: do we need this?

                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("x")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: we need the function to derive a valid longitude from the uberdust value (pending)
                                            tmp_longitude = nodeCapAndReadingRowItems[3].trim();
                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("y")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: we need the function to derive a valid latitude)
                                            tmp_latitude = nodeCapAndReadingRowItems[3].trim();
                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("z")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //altitude is in meters (assumption)
                                            tmp_altitude = nodeCapAndReadingRowItems[3].trim();

                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("phi")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: do we need this?
                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("theta")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: do we need this?
                                        }
                                    }

                                }
                            } // end of first round of for loop for attributes
                            if (!tmp_latitude.equalsIgnoreCase("") && !tmp_longitude.equalsIgnoreCase("")
                                    && !tmp_altitude.equalsIgnoreCase("")) {
                                tmpSmartDev.setGplocation(
                                        new GeodesicPoint(tmp_latitude, tmp_longitude, tmp_altitude));
                            }

                            //
                            // Again same loop for measurement and actuation capabilities!
                            //
                            for (String aNodeAndLastCapReadingsUrnsInUberdust : nodeAndLastCapReadingsUrnsInUberdust) {
                                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust
                                        .split("\\t");
                                if (nodeCapAndReadingRowItems.length > 3 && nodeCapAndReadingRowItems[0]
                                        .compareToIgnoreCase(aNodeUrnsInUberdust) == 0) //we are at the capabilities of the current smartdevice
                                {
                                    // [0] is mote (smart device) id
                                    // [1] is capability
                                    // [2] is measurement value
                                    // [3] is timestamp
                                    //                                        logger.debug(nodeCapAndReadingRowItems[1]);
                                    // TODO: FILTER OUT UNSUPPORTED OR COMPLEX CAPABILITIES!!!!
                                    // Since uberdust does not distinguish currenlty between sensing/actuating capabilities and properties, we need to filter out manually
                                    // everything we don't consider a sensing/actuating capability.
                                    // Another filtering out is done at a later stage with the SensorMLMessageAdapter, which will filter out the capabilities not supported by IDAS
                                    // TODO: it could be nice to have this filtering unified.
                                    if ((nodeCapAndReadingRowItems[1] != null)
                                            && (nodeCapAndReadingRowItems[1].trim().compareTo("") != 0)
                                            && !getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim())
                                                    .equalsIgnoreCase("UnknownPhenomenon")) {

                                        //todo: this is just to support actuation during the demo. The code should be improved later on:
                                        // todo: replace with regex
                                        //if(getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight1")
                                        //        || getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight2")
                                        //        ||  getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight3")
                                        //        ||getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim()).equalsIgnoreCase("switchlight4") )
                                        //{

                                        //}
                                        // else
                                        // {
                                        //TODO: don't get light measurements from arduinos even if they advertise light as a capability

                                        // The model id is set as the hashcode of the capability name appended with the model type of the device.
                                        // Perhaps this should be changed to something MORE specific
                                        // TODO: the units should be set here as we know them. Create a small dictionary to set them!
                                        // TODO: the non-observation sensors/ non-actuation should be filtered here!! the Name for the others should be "UnknownPhenomenon"

                                        String tmpGenericCapabilityForSensor = getSimpleCapForUberdustUrn(
                                                nodeCapAndReadingRowItems[1].trim());
                                        Integer thedigestInt = (tmpGenericCapabilityForSensor + "-"
                                                + tmpSmartDev.getName()).hashCode();
                                        if (thedigestInt < 0)
                                            thedigestInt = thedigestInt * (-1);

                                        CSensorModel tmpSensorModel = new CSensorModel(
                                                givGatewayInfo.getId(), /*Gateway Id*/
                                                thedigestInt, /*Sensor Model Id */
                                                (tmpGenericCapabilityForSensor + "-"
                                                        + tmpSmartDev.getName()), /* Sensor Model name */
                                                CSensorModel.numericDataType, /* Data type*/ // TODO: later on this should be adjustable!!!
                                                CSensorModel.defaultAccuracy, /* Accuracy */
                                                CSensorModel.defaultUnits) /* Units */; // TODO: this should be set when it is known!!!
                                        //                                            if(!tmpGenericCapabilityForSensor.equalsIgnoreCase("UnknownPhenomenon" ))
                                        //                                            {
                                        sensorModelsOfSmartDevVector.add(tmpSensorModel);
                                        sensorModels_IDs_OfSmartDevVector.add(tmpSensorModel.getSmid());
                                        //                                            }

                                        if (!myAllCapabilitiesToSensorModelIds
                                                .containsKey(tmpGenericCapabilityForSensor)) {
                                            myAllCapabilitiesToSensorModelIds.put(tmpGenericCapabilityForSensor,
                                                    new Vector<Integer>());
                                            givGatewayInfo.getAllGwGenericCapabilities().put(
                                                    tmpGenericCapabilityForSensor, new Vector<CSensorModel>());
                                        }
                                        // When we reach this part, we already have a key that corresponds to a unique sensor capability description
                                        if (!myAllCapabilitiesToSensorModelIds
                                                .get(tmpGenericCapabilityForSensor)
                                                .contains(Integer.valueOf(tmpSensorModel.getSmid()))) {
                                            myAllCapabilitiesToSensorModelIds.get(tmpGenericCapabilityForSensor)
                                                    .addElement(tmpSensorModel.getSmid());
                                            givGatewayInfo.getAllGwGenericCapabilities()
                                                    .get(tmpGenericCapabilityForSensor)
                                                    .addElement(tmpSensorModel);
                                        }
                                        // }
                                    }
                                }
                            }
                            if (!sensorModelsOfSmartDevVector.isEmpty()) {
                                // TODO: FILTER OUT UNSUPPORTED OR COMPLEX NODES!!!!
                                // For demo purposes let's keep only the first floor and iSense devices
                                String isensePrefixTag = "isense";
                                String arduinoTag = "arduino";
                                String telosBTag = "telosb";
                                String roomsOnZeroFloor_PartI_PrefixTag = "0.I.";
                                String roomsOnZeroFloor_PartII_PrefixTag = "0.II.";

                                if (!VitroGatewayService.getVitroGatewayService()
                                        .getAssignedGatewayUniqueIdFromReg().equalsIgnoreCase("vitrogw_hai")) {
                                    if ((!tmpSmartDev.getLocationDesc().isEmpty())
                                            && ((tmpSmartDev.getLocationDesc()
                                                    .length() >= roomsOnZeroFloor_PartI_PrefixTag.length()
                                                    && tmpSmartDev.getLocationDesc()
                                                            .substring(0,
                                                                    roomsOnZeroFloor_PartI_PrefixTag.length())
                                                            .equalsIgnoreCase(roomsOnZeroFloor_PartI_PrefixTag))
                                                    || (tmpSmartDev.getLocationDesc()
                                                            .length() >= roomsOnZeroFloor_PartII_PrefixTag
                                                                    .length()
                                                            && tmpSmartDev.getLocationDesc()
                                                                    .substring(0,
                                                                            roomsOnZeroFloor_PartII_PrefixTag
                                                                                    .length())
                                                                    .equalsIgnoreCase(
                                                                            roomsOnZeroFloor_PartII_PrefixTag)))
                                            && (!tmpSmartDev.getName().isEmpty())
                                            && ((tmpSmartDev.getName().length() >= isensePrefixTag.length()
                                                    && tmpSmartDev.getName()
                                                            .substring(0, isensePrefixTag.length())
                                                            .equalsIgnoreCase(isensePrefixTag))
                                                    || (tmpSmartDev.getName().length() >= arduinoTag.length()
                                                            && tmpSmartDev.getName()
                                                                    .substring(0, arduinoTag.length())
                                                                    .equalsIgnoreCase(arduinoTag)))) {
                                        currSmartDevicesVec.addElement(tmpSmartDev);
                                    }
                                } else if (VitroGatewayService.getVitroGatewayService()
                                        .getAssignedGatewayUniqueIdFromReg().equalsIgnoreCase("vitrogw_hai")) {
                                    //logger.debug("I am hai");
                                    if ((!tmpSmartDev.getLocationDesc().isEmpty())
                                            && ((tmpSmartDev.getLocationDesc()
                                                    .length() >= roomsOnZeroFloor_PartI_PrefixTag.length()
                                                    && tmpSmartDev.getLocationDesc()
                                                            .substring(0,
                                                                    roomsOnZeroFloor_PartI_PrefixTag.length())
                                                            .equalsIgnoreCase(roomsOnZeroFloor_PartI_PrefixTag))
                                                    || (tmpSmartDev.getLocationDesc()
                                                            .length() >= roomsOnZeroFloor_PartII_PrefixTag
                                                                    .length()
                                                            && tmpSmartDev.getLocationDesc()
                                                                    .substring(0,
                                                                            roomsOnZeroFloor_PartII_PrefixTag
                                                                                    .length())
                                                                    .equalsIgnoreCase(
                                                                            roomsOnZeroFloor_PartII_PrefixTag)))
                                            && (!tmpSmartDev.getName().isEmpty())
                                            && ((tmpSmartDev.getName().length() >= telosBTag.length()
                                                    && tmpSmartDev.getName().substring(0, telosBTag.length())
                                                            .equalsIgnoreCase(telosBTag)))) {
                                        String myoldid = tmpSmartDev.getId();
                                        tmpSmartDev.setId(dictionaryUberdustUrnToHaiUrnName.get(myoldid));
                                        currSmartDevicesVec.addElement(tmpSmartDev);
                                    }
                                }

                                //#####################################
                            }
                        } // ends for loop over all smartdevices discovered!
                    } //if GET STATUS response code is OK!
                } // if GET STATUS response entity is NOT null
            } //if get list of nodes replied validly
        } //if get list of nodes response entity is NOT null
    } catch (Exception e) {
        logger.debug("error::" + e.getMessage());

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate de-allocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // DEBUG: for debugging
    //GatewayDescriptionAdvertisement myGwAdDesc = new GatewayDescriptionAdvertisement(givGatewayInfo,
    //        currSmartDevicesVec,
    //        myAllCapabilitiesToSensorModels);
    //
    return myGatewayForSmartDevs;
}

From source file:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java

Vector<ReqResultOverData> DEBUG_offline_translateAggrQuery(
        Vector<QueriedMoteAndSensors> motesAndTheirSensorAndFunctsVec,
        Vector<ReqFunctionOverData> reqFunctionVec) {
    //logger.debug("IN UBERDUST QUERY");
    /*for(QueriedMoteAndSensors qms: motesAndTheirSensorAndFunctsVec) {
    logger.debug("Mote: " + qms.getMoteid());
       for(ReqSensorAndFunctions rsf : qms.getQueriedSensorIdsAndFuncVec()){
       logger.debug("Capability: " +rsf.getSensorModelid());
       for( Integer fidd: rsf.getFunctionsOverSensorModelVec()) {
           logger.debug("Function: " +fidd);
       }//  www .j a  v a2s .c  o m
            
       }
            
    }*/
    String responseBodyFromHttpNodesGetStr = WsiUberDustCon.DEBUG_OFFLINE_STR_NODE_GETRESTSTATUS;
    String responseBodyFromHttpNodes_STATUS_Get = WsiUberDustCon.DEBUG_OFFLINE_STR_GETRESTSTATUS_RAW;
    String responseBodyFromHttpNodes_ADMINSTATUS_Get = WsiUberDustCon.DEBUG_OFFLINE_STR_BODY_ADMINSTATUS;

    boolean useTheStandardWayToGetStateForActuatorReading = false; // false allows to get explicitly the latest reading instead of the standard one (in the general status page) updated every few minutes
    // TODO: tmp structure to be replaced when this is tested and works
    Vector<VerySimpleSensorEntity> allSensorsWithCapsAndMeasures = new Vector<VerySimpleSensorEntity>();
    // Maps Smart Device ids to Room names, where the room names are available.
    HashMap<String, String> smartDevIdsToRooms = new HashMap<String, String>();
    //
    // ##########################################################################################################################################
    //
    /*
     * TODO: optimize the status/resource retrieval process for uberdust!
     * TODO: Take into account the mote status before ADDING it to the gateway description list (++++ LATER)
     *         For now we assume that the queries to the actual WSN are handled by the middleware.
     *         We search the uberdust "database" for data. (but we can still perform actions to affect the WSI!)
     *
     *         The plan is for a future service
     *         where a peer could submit queries for submission in the actual WSNs, and subsequently gather the data
     *         of the results. (e.g. administration service>reprogramming service)
     */
    try {

        //logger.debug("--------OK Response: "+ httpUberdustNodesGetResponseStatusCode+"------------------------------");
        //
        String[] nodeUrnsInUberdust = responseBodyFromHttpNodesGetStr.split("\\r?\\n");
        int totalNodeUrnsInUberdust = nodeUrnsInUberdust.length;

        String[] nodeAndLastCapReadingsUrnsInUberdust = responseBodyFromHttpNodes_STATUS_Get.split("\\r?\\n");
        int totalNodeWithCapsInUberdust = nodeAndLastCapReadingsUrnsInUberdust.length;

        // LOOP OVER EVERY NODE (smart device), and for each node, get its capabilities from the second response (responseBody_STATUS_Str)
        Vector<String> allFaultyNodesUrns = getFaultyNodes();

        for (String aNodeUrnsInUberdust : nodeUrnsInUberdust) {
            if (allFaultyNodesUrns.contains(aNodeUrnsInUberdust)) {
                logger.debug("Skiipping node: " + aNodeUrnsInUberdust);
                continue;
            }
            Vector<VerySimpleObservationCapabilities> sensObsCapsVector = new Vector<VerySimpleObservationCapabilities>();
            Vector<VerySimpleSensorMeasurement> sensObsMeasurementVector = new Vector<VerySimpleSensorMeasurement>();

            if (VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg()
                    .equalsIgnoreCase("vitrogw_hai")) {
                aNodeUrnsInUberdust = dictionaryUberdustUrnToHaiUrnName.get(aNodeUrnsInUberdust);
                if (aNodeUrnsInUberdust == null)
                    continue;
            }

            //                                logger.debug("Iteration " + String.valueOf(k+1) + " of " + String.valueOf(totalNodeUrnsInUberdust));
            //                                logger.debug(nodeUrnsInUberdust[k]);

            Vector<Integer> sensorModels_IDs_OfSmartDevVector = new Vector<Integer>();
            CSmartDevice tmpSmartDev = new CSmartDevice(aNodeUrnsInUberdust, "", /* smart device type name */
                    "", /* location description e.g. room1*/
                    new GeodesicPoint(), /*  */
                    sensorModels_IDs_OfSmartDevVector);

            // TODO: Add an extra early for loop to update the fields for the attributes of the SmartDevice such as:
            //      Eventually if the SmartDev has NO other valid sensors (e.g. observation sensors or actuators) then it won't be added !
            String tmp_longitude = "";
            String tmp_latitude = "";
            String tmp_altitude = "";

            for (String aNodeAndLastCapReadingsUrnsInUberdust1 : nodeAndLastCapReadingsUrnsInUberdust) {
                //to update the device attributes!
                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust1.split("\\t");
                if (VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg()
                        .equalsIgnoreCase("vitrogw_hai")) {
                    nodeCapAndReadingRowItems[0] = dictionaryUberdustUrnToHaiUrnName
                            .get(nodeCapAndReadingRowItems[0]);
                    if (nodeCapAndReadingRowItems[0] == null)
                        continue;
                }

                if (nodeCapAndReadingRowItems.length > 3
                        && nodeCapAndReadingRowItems[0].compareToIgnoreCase(aNodeUrnsInUberdust) == 0) //we are at the capabilities of the current smartdevice
                {
                    // [0] is mote (smart device) id
                    // [1] is capability
                    // [2] is timestamp
                    // [3] is measurement value
                    if ((nodeCapAndReadingRowItems[1] != null)
                            && !(nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase(""))) {
                        if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("room")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            tmpSmartDev.setLocationDesc(nodeCapAndReadingRowItems[3].trim());
                            smartDevIdsToRooms.put(tmpSmartDev.getId(), tmpSmartDev.getLocationDesc());
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("nodetype")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            tmpSmartDev.setName(nodeCapAndReadingRowItems[3].trim());
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("description")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: do we need this?

                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("x")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: we need the function to derive a valid longitude from the uberdust value (pending)
                            tmp_longitude = nodeCapAndReadingRowItems[3].trim();
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("y")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: we need the function to derive a valid latitude)
                            tmp_latitude = nodeCapAndReadingRowItems[3].trim();
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("z")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //altitude is in meters (assumption)
                            tmp_altitude = nodeCapAndReadingRowItems[3].trim();

                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("phi")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: do we need this?
                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("theta")
                                && nodeCapAndReadingRowItems[3] != null
                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                            //TODO: do we need this?
                        }
                    }
                }
            } // end of first round of for loop for attributes
            if (!tmp_latitude.equalsIgnoreCase("") && !tmp_longitude.equalsIgnoreCase("")
                    && !tmp_altitude.equalsIgnoreCase("")) {
                tmpSmartDev.setGplocation(new GeodesicPoint(tmp_latitude, tmp_longitude, tmp_altitude));
            }

            //
            // Again same loop for measurement and actuation capabilities!
            //
            for (String aNodeAndLastCapReadingsUrnsInUberdust : nodeAndLastCapReadingsUrnsInUberdust) {
                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust.split("\\t");
                if (VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg()
                        .equalsIgnoreCase("vitrogw_hai")) {
                    nodeCapAndReadingRowItems[0] = dictionaryUberdustUrnToHaiUrnName
                            .get(nodeCapAndReadingRowItems[0]);
                    if (nodeCapAndReadingRowItems[0] == null)
                        continue;
                }
                if (nodeCapAndReadingRowItems.length > 3
                        && nodeCapAndReadingRowItems[0].compareToIgnoreCase(aNodeUrnsInUberdust) == 0) //we are at the capabilities of the current smartdevice
                {
                    // [0] is mote (smart device) id
                    // [1] is capability
                    // [2] is measurement value
                    // [3] is timestamp
                    //                                        logger.debug(nodeCapAndReadingRowItems[1]);
                    // TODO: FILTER OUT UNSUPPORTED OR COMPLEX CAPABILITIES!!!!
                    // Since uberdust does not distinguish currenlty between sensing/actuating capabilities and properties, we need to filter out manually
                    // everything we don't consider a sensing/actuating capability.
                    // Another filtering out is done at a later stage with the SensorMLMessageAdapter, which will filter out the capabilities not supported by IDAS
                    // TODO: it could be nice to have this filtering unified.
                    if ((nodeCapAndReadingRowItems[1] != null)
                            && (nodeCapAndReadingRowItems[1].trim().compareTo("") != 0)
                            && !getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim())
                                    .equalsIgnoreCase("UnknownPhenomenon")) {
                        // The model id is set as the hashcode of the capability name appended with the model type of the device.
                        // Perhaps this should be changed to something MORE specific
                        // TODO: the units should be set here as we know them for Uberdust. Create a small dictionary to set them!
                        // TODO: the non-observation sensors/ non-actuation should be filtered here!! the Name for the others should be "UnknownPhenomenon"

                        String tmpGenericCapabilityForSensor = getSimpleCapForUberdustUrn(
                                nodeCapAndReadingRowItems[1].trim());
                        Integer thedigestInt = (tmpGenericCapabilityForSensor + "-" + tmpSmartDev.getName())
                                .hashCode();
                        if (thedigestInt < 0)
                            thedigestInt = thedigestInt * (-1);

                        //                                            /*
                        //                                            CSensorModel tmpSensorModel = new CSensorModel(givGatewayInfo.getId(), /*Gateway Id*/
                        //                                                    thedigestInt, /*Sensor Model Id */
                        //                                                    (tmpGenericCapabilityForSensor + "-" + tmpSmartDev.getName()), /* Sensor Model name */
                        //                                                    CSensorModel.numericDataType, /* Data type*/  // TODO: later on this should be adjustable!!!
                        //                                                    CSensorModel.defaultAccuracy, /* Accuracy */
                        //                                                    CSensorModel.defaultUnits) /* Units */;  // TODO: this should be set when it is known!!!

                        // GET THE OBSERVATION
                        VerySimpleObservationCapabilities tmpObsCap = new VerySimpleObservationCapabilities(
                                nodeCapAndReadingRowItems[1], true);
                        if ((tmpObsCap.getSimpleName() != null)
                                && !(tmpObsCap.getSimpleName().equalsIgnoreCase("UnknownPhenomenon"))) {
                            sensObsCapsVector.add(tmpObsCap);

                            // ts of measurement in place [2]
                            // value of measurement in place [3]
                            // logger.debug(nodeCapAndReadingRowItems[2]+'\t'+nodeCapAndReadingRowItems[3]);
                            long theTimeStamp = Long.parseLong(nodeCapAndReadingRowItems[2]);
                            String theValue = nodeCapAndReadingRowItems[3];
                            if (theValue.contains(" "))
                                theValue = theValue.split(" ")[0]; // if it contains the UOM as a suffix,then just keep the first part
                            String observPropertyDef = tmpObsCap.getPhenomenonIDASUrn();
                            String observOutputUOMCode = tmpObsCap.getUomIDASUrn();// tmpObsCap.getUomIDASCode();
                            // just one (last) value
                            String[] observOutputMeasurementData = new String[1];
                            // Dummy measurement value
                            if (tmpObsCap.getSimpleName().equalsIgnoreCase("temperature")) {
                                //since we assume kelvin to be the default UOM, until fixed, wew set oiur ceslious to Kelvin here:
                                //K = C+273 . TODO. Later on this normalization should be done at the VSP!
                                double d = Double.parseDouble(theValue);
                                double convertedKelvinValue = d + 273.0;
                                String convertedKelvinValueStr = Long.toString((long) convertedKelvinValue);

                                observOutputMeasurementData[0] = convertedKelvinValueStr; //to kelvin
                            } else {
                                observOutputMeasurementData[0] = theValue;
                            }
                            // TODO: Check if timezone is correct!
                            // FOR UBERDUST: override sensors timestamp with reply from uberdust timestamp (now)
                            Date dateNow = new Date();
                            theTimeStamp = dateNow.getTime();
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
                            String observPropertyTSStr = df.format(new Date(theTimeStamp));
                            //logger.debug("---- " + observPropertyTSStr + " ---- " + theValue + " ----------------------------");
                            sensObsMeasurementVector
                                    .add(new VerySimpleSensorMeasurement(observPropertyDef, observOutputUOMCode,
                                            observOutputMeasurementData, observPropertyTSStr, theTimeStamp));
                        }

                        sensorModels_IDs_OfSmartDevVector.add(thedigestInt);

                    }
                }
            }
            if (!sensorModels_IDs_OfSmartDevVector.isEmpty()) {
                // TODO: FILTER OUT UNSUPPORTED OR COMPLEX NODES!!!!
                VerySimpleSensorEntity sens01 = new VerySimpleSensorEntity(aNodeUrnsInUberdust,
                        sensObsCapsVector, sensObsMeasurementVector);
                allSensorsWithCapsAndMeasures.add(sens01);

                // TODO: MAYBE HERE WE CAN CHECK IF THESE MEASUREMENTS are for the results??
                //if (!sensObsMeasurementVector.isEmpty())
                //{
                //    Iterator<VerySimpleSensorMeasurement> it1 = sensObsMeasurementVector.iterator();
                //    while( it1.hasNext())
                //    {
                //        VerySimpleSensorMeasurement sensorMeasurement = (VerySimpleSensorMeasurement)it1.next();
                //
                //    }
                //}
                //#####################################
            }
        } // ends for loop over all smartdevices discovered!
    } catch (Exception e) {
        logger.error("error::" + e.getMessage());

    }

    //
    // TILL HERE WE HAVE A VECTOR WITH ALL Devices and Capabilities and Measurements: allSensorsWithCapsAndMeasures
    //
    //

    Vector<ResultAggrStruct> vOfSensorValues;

    Vector<ReqResultOverData> retVecofResults;
    retVecofResults = new Vector<ReqResultOverData>();

    //logger.debug("Size of motesAndTheirSensorAndFunctsVec::" + Integer.toString(motesAndTheirSensorAndFunctsVec.size())  );

    for (int i = 0; i < motesAndTheirSensorAndFunctsVec.size(); i++) {

        String fullMoteId = motesAndTheirSensorAndFunctsVec.elementAt(i).getMoteid();

        // for each entry, get the vector of queried sensor types and the functions to be applied to the measurements.
        List<ReqSensorAndFunctions> tmpVecSmAndFuncList = motesAndTheirSensorAndFunctsVec.elementAt(i)
                .getQueriedSensorIdsAndFuncVec();
        //            Vector<Integer> tmpVecSmIds =  motesAndTheirSensorHM.get(fullMoteId);
        /**
         *
         *  TODO: So far we assume all of the data types in measurements to be Long! This should be fixed!!!
         *
         */
        try {

            //
            // We have the readings from all sensors.
            // we must select only the readings from the specific sensors of interest (those inside the  tmpVecSmAndFuncList vector) .
            //

            //logger.debug("Size of tmpVecSmAndFuncList::" + Integer.toString(tmpVecSmAndFuncList.size())  );
            for (ReqSensorAndFunctions aTmpVecSmAndFuncList : tmpVecSmAndFuncList) {
                int smid = aTmpVecSmAndFuncList.getSensorModelIdInt();
                int countValuesOfthisSensorModel = 0;

                // TODO : fix to other connectors ->moved vOfSensorValues in the for loop!

                //logger.debug("For mote "+fullMoteId +" and sensor "+Integer.toString(smid) + " function vector size is "+reqFunctionVec.size());
                for (ReqFunctionOverData currentRequestedFunction : reqFunctionVec) {
                    vOfSensorValues = new Vector<ResultAggrStruct>();

                    if (currentRequestedFunction.getfuncId() == ReqFunctionOverData.unknownFuncId) {
                        vOfSensorValues
                                .addElement(new ResultAggrStruct(fullMoteId, smid, "No Result", 1, null));
                        countValuesOfthisSensorModel += 1;
                    } else if (aTmpVecSmAndFuncList.getFunctionsOverSensorModelVec()
                            .contains(currentRequestedFunction.getfuncId())) { // this loop (and this condition) allows to retrieve the valid "functions" to be performed on values of this sensor
                        Vector<VerySimpleSensorMeasurement> mySensorReadingsRelatedToCurrentFunction = new Vector<VerySimpleSensorMeasurement>(); // bugfix: this is now moved inside the functions loop
                        // for each different "function" on the sensor values, we may need to gather completely different values. (e.g. a function could request a history of measurements, or only measurements that are above a threshold)
                        // TODO: Separate cases for binary values (e.g. image or webcam stream) and numeric values  (and string values?)

                        // TODO: for uberdust, loop through all nodes in (http get status vector): allSensorsWithCapsAndMeasures
                        //          and keep the readings, apply functions (FOR NOW WE ALWAYS APPLY LAST READING NO MATTER WHAT)
                        // TODO: Fix -> for now we always apply last reading no matter what the actual function was (since we have no history).
                        // TODO: fix serial numbers for sensor models. They should not just be the hash on the capability simple name...
                        for (VerySimpleSensorEntity tmpSmartDev : allSensorsWithCapsAndMeasures) {
                            if (tmpSmartDev.getSerialID().equalsIgnoreCase(fullMoteId)) // first match based on the requested smart device ID
                            {
                                for (VerySimpleSensorMeasurement tmpMeasurement : tmpSmartDev
                                        .getMeasurementsVector()) {
                                    String obsPropertyIDASUrn = tmpMeasurement.getObservPropertyDef();
                                    String obsPropertySimple = "lalala";
                                    Iterator<String> itDict = dictionaryNameToIDASPhenomenon.keySet()
                                            .iterator();
                                    String tmpSimpleName;
                                    // initial loop to get the "real" simple name for the search key capability (at this poing this is not yet a valid requested sensor)
                                    // we need the simple name because we used it to calculate the sensor model id (with the hashCode() )
                                    // so we get simple names, then calc their hashCodes (turn it into a positive number if it was negative) and then compare it with the requested hashcode (smid)  (assumed positive, because the DVNS will make sure of that)
                                    // logger.debug("^^^^^^^^^^OV: "+ obsPropertyIDASUrn);
                                    while (itDict.hasNext()) {
                                        tmpSimpleName = itDict.next();
                                        //logger.debug("^^^^^^^^^^VS: "+ (dictionaryNameToIDASPhenomenon.get(tmpSimpleName)).toString());

                                        if ((staticprefixPhenomenonIDAS
                                                + (dictionaryNameToIDASPhenomenon.get(tmpSimpleName)))
                                                        .equalsIgnoreCase(obsPropertyIDASUrn)) {
                                            //logger.debug("*** *** *** Found matching capability in dictionary:" + tmpSimpleName);
                                            obsPropertySimple = tmpSimpleName;
                                            break;
                                        }
                                    }

                                    int projectedSmIdforPropertyDef = obsPropertySimple.hashCode();
                                    if (projectedSmIdforPropertyDef < 0) {
                                        projectedSmIdforPropertyDef = projectedSmIdforPropertyDef * (-1);
                                    }

                                    if (smid == projectedSmIdforPropertyDef) {
                                        // debug:
                                        //                                            if((tmpSimpleName.equalsIgnoreCase("switchlight1")
                                        //                                                    ||tmpSimpleName.equalsIgnoreCase("switchlight2")
                                        //                                                    ||tmpSimpleName.equalsIgnoreCase("switchlight3")
                                        //                                                    ||tmpSimpleName.equalsIgnoreCase("switchlight4") )
                                        //                                                &&
                                        //                                            ((smartDevIdsToRooms.get(fullMoteId)!=null) && smartDevIdsToRooms.get(fullMoteId).equalsIgnoreCase("0.I.3")));
                                        //                                                    {
                                        //                                                logger.debug("*** *** *** ADDING A MEASUREMENT FOR: "+ tmpSimpleName + " Mote:" +fullMoteId + "Room: " + smartDevIdsToRooms.get(fullMoteId));
                                        //                                            }
                                        mySensorReadingsRelatedToCurrentFunction.add(tmpMeasurement);

                                        break; // TODO: break since a smartdevice will not have two of the same sensor models. Can it though? in general?
                                    }
                                    //else
                                    //{
                                    //    logger.debug("*** *** *** BUT DOES NOT MATCH A requested sensor: "+ tmpSimpleName);
                                    //}
                                }
                                break; //since we processed  the sensor dev that we wanted.
                            }
                        }

                        //logger.debug("READINGS LENGTH:" + Integer.toString(mySensorReadingsRelatedToCurrentFunction.length) );

                        for (int o = 0; o < mySensorReadingsRelatedToCurrentFunction.size(); o++) {
                            /* TODO: (++++) this could be optimized further (not write the entire data in the vector) / first process it
                             * according to the function.
                             * TODO: Somewhere around here we should handle the History function (not likely for uberdust)
                             */
                            //SensorTypes tmpSensor = jWebTypesManager.selectSensorType(smid);
                            long valueToAdd = -1;
                            //if(tmpSensor.getIsComplex() == false)
                            //{
                            // TODO: here we handle the actuation capabilities for lights as well, if a set value function was requested on them
                            // TODO: if a last value reading was requested we can handle that too by sending their state (as reported)
                            if (mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservPropertyDef()
                                    .equalsIgnoreCase(staticprefixPhenomenonIDAS
                                            + (dictionaryNameToIDASPhenomenon.get("switchlight1")))
                                    || mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservPropertyDef()
                                            .equalsIgnoreCase(staticprefixPhenomenonIDAS
                                                    + (dictionaryNameToIDASPhenomenon.get("switchlight2")))
                                    || mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservPropertyDef()
                                            .equalsIgnoreCase(staticprefixPhenomenonIDAS
                                                    + (dictionaryNameToIDASPhenomenon.get("switchlight3")))
                                    || mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservPropertyDef().equalsIgnoreCase(staticprefixPhenomenonIDAS
                                                    + (dictionaryNameToIDASPhenomenon.get("switchlight4")))) {
                                logger.debug("Function: " + currentRequestedFunction.getfuncName());
                                // TODO: for now we use the threshold field to set the actuation value! Later this could be a separate parameter field
                                if (currentRequestedFunction.getfuncName()
                                        .equalsIgnoreCase(ReqFunctionOverData.setValFunc)
                                        && currentRequestedFunction.getThresholdField() != null
                                        && !currentRequestedFunction.getThresholdField().isEmpty()) {
                                    logger.debug("-------- HANDLING ACTUATION NOW! "
                                            + mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                    .getObservPropertyDef()
                                            + " room: " + smartDevIdsToRooms.get(fullMoteId) + " mote: "
                                            + fullMoteId + " val: " + mySensorReadingsRelatedToCurrentFunction
                                                    .elementAt(o).getObservOutputMeasurementData()[0]);
                                    ThresholdStructure requiredThresholds = new ThresholdStructure(
                                            currentRequestedFunction.getThresholdField());
                                    if (requiredThresholds.getLowerBound() != null
                                            && !requiredThresholds.getLowerBound().isEmpty()) {
                                        logger.debug("Actuation parameter: "
                                                + requiredThresholds.getLowerBound().trim());
                                        // attempt to set the light to the desired value!
                                        // TODO: check if a valid value (0 or 1)
                                        try {
                                            String valStr = actuateSmartDevToValue(fullMoteId,
                                                    smartDevIdsToRooms.get(fullMoteId),
                                                    getUberdustUrnForIDASCapName(
                                                            mySensorReadingsRelatedToCurrentFunction
                                                                    .elementAt(o).getObservPropertyDef()),
                                                    requiredThresholds.getLowerBound().trim());
                                            double d = Double.parseDouble(valStr);
                                            valueToAdd = (long) d;
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            valueToAdd = -1;
                                        }

                                    }
                                } else {

                                    if (useTheStandardWayToGetStateForActuatorReading) {
                                        try {
                                            String valStr = mySensorReadingsRelatedToCurrentFunction
                                                    .elementAt(o).getObservOutputMeasurementData()[0];
                                            double d = Double.parseDouble(valStr);
                                            valueToAdd = (long) d;
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            valueToAdd = -1;
                                        }
                                    } else {
                                        String UberdustUrnForCap = getUberdustUrnForIDASCapName(
                                                mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                        .getObservPropertyDef());
                                        String justtheCapName = UberdustUrnForCap
                                                .substring(staticprefixUberdustCapability.length());
                                        //TODO: this masking is just for the demo!
                                        //mask light4 capability as light5 in order to show it in the demo: (light4 is not visible from the camera's viewpoint)
                                        // Changed light4 to lz4 to reflect naming change in uberdust
                                        if (justtheCapName.equalsIgnoreCase("lz4"))
                                            justtheCapName = "lz5";
                                        String lineOfStateReading = getLatestReadingTabSepLineForVirtualNode(
                                                fullMoteId, justtheCapName);
                                        String[] lineTokens = lineOfStateReading.split("\\t");
                                        // [0] has the timestamp
                                        // [1] has the value
                                        long valueOfReturnedState;
                                        String observPropertyTSStr;
                                        long theTimeStamp = 0;
                                        try {
                                            double d = Double.parseDouble(lineTokens[1]);
                                            valueOfReturnedState = (long) d;
                                            theTimeStamp = Long.parseLong(lineTokens[0]);
                                            DateFormat df = new SimpleDateFormat(
                                                    "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
                                            observPropertyTSStr = df.format(new Date(theTimeStamp));
                                            logger.debug("Actuator state was: " + lineTokens[1] + " at: "
                                                    + observPropertyTSStr);
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            DateFormat df = new SimpleDateFormat(
                                                    "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
                                            observPropertyTSStr = df.format(new Date(theTimeStamp));
                                            valueOfReturnedState = -1;

                                        }
                                        mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                .setObservPropertyTSLong(theTimeStamp);
                                        mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                .setObservPropertyTSStr(observPropertyTSStr);
                                        mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                .getObservOutputMeasurementData()[0] = Long
                                                        .toString(valueOfReturnedState);
                                        // todo: move code repetition
                                        try {
                                            String valStr = mySensorReadingsRelatedToCurrentFunction
                                                    .elementAt(o).getObservOutputMeasurementData()[0];
                                            double d = Double.parseDouble(valStr);
                                            valueToAdd = (long) d;
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            valueToAdd = -1;
                                        }
                                    }
                                }

                            } else {
                                try {
                                    String valStr = mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservOutputMeasurementData()[0];
                                    double d = Double.parseDouble(valStr);
                                    valueToAdd = (long) d;
                                } catch (Exception e) {
                                    //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                    valueToAdd = -1;
                                }
                            }

                            long timestampOfReading = mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                    .getObservPropertyTSLong();
                            Timestamp timestampOfReadingSql = new Timestamp(timestampOfReading);
                            vOfSensorValues.addElement(new ResultAggrStruct(fullMoteId, smid,
                                    Long.toString(valueToAdd), 1,
                                    new TimeIntervalStructure(timestampOfReadingSql, timestampOfReadingSql)));
                            //}
                            //                                else// put blob value as a String (FOR NOW this is just a URL to the binary file so this is ok) (++++)
                            //                                    // TODO: later handling of binary data will change and we should send the real binary files over pipes to the client
                            //                                {
                            //                                    vOfSensorValues.addElement(new ResultAggrStruct(fullMoteId,
                            //                                        smid,
                            //                                        new String(myMotesSensorsReadings[o].getComplexRawData()),
                            //                                        1,
                            //                                        new TimeIntervalStructure(myMotesSensorsReadings[o].getDate(),
                            //                                                myMotesSensorsReadings[o].getDate()))
                            //                                    );
                            //                                }

                            countValuesOfthisSensorModel += 1;
                        }
                        if (countValuesOfthisSensorModel == 0) {
                            vOfSensorValues.addElement(new ResultAggrStruct(fullMoteId, smid,
                                    ReqResultOverData.specialValueNoReading, 1, null));
                            countValuesOfthisSensorModel += 1;
                        } else
                            logger.debug("Counted Values of this sensor: " + fullMoteId + " "
                                    + Integer.toString(countValuesOfthisSensorModel));
                    }
                    // this condition checks that at least one value was retrieved from the sensor and used in the function (even if that value was "no result")
                    if (countValuesOfthisSensorModel > 0) // we should make sure that this is always true.
                    {
                        retVecofResults.addElement(
                                new ReqResultOverData(currentRequestedFunction.getfuncId(), vOfSensorValues));
                    }
                } // ends the block where we gather values of a sensor for a specific function
            } // ends the loop over the requested sensor Models (capabilities) of the current requested Smart Device
        } catch (Exception e) {
            e.printStackTrace();
        }
    } // end of for loop over all requested Smart Devices in the request vector

    // here we have a Vector filled with ResultAggrStruct

    // END OF LEGACY driver code

    return retVecofResults;
}

From source file:org.codecover.eclipse.views.CoverageGraphView.java

private edu.uci.ics.jung.graph.Graph<CoverageGraphNode, CoverageGraphLink> createGraph(String Criterion,
        String SUTLevel, String TestLevel, Boolean ShowOnlyCovered, Boolean CompleteName) {
    edu.uci.ics.jung.graph.Graph<CoverageGraphNode, CoverageGraphLink> graph = new SparseMultigraph<CoverageGraphNode, CoverageGraphLink>();
    try {/*from  w  w w.  j ava 2  s.  c  o m*/
        Set<CoverableItem> coverableItemSet = CreateCoverableItemSet(Criterion);
        Vector<CoverageGraphNode> SUTItems = new Vector<CoverageGraphNode>();
        Vector<String> SUTItemsId = new Vector<String>();
        Vector<CoverageGraphNode> TestItems = new Vector<CoverageGraphNode>();
        Vector<String> TestItemsId = new Vector<String>();
        int NumOfSUTNodes = 0;
        int NumOfTestNodes = 0;
        if (selectedTestCases.size() != 0) {
            CoverageGraphNode SUTNode;
            CoverageGraphNode TestNode;
            List<CoverableItem> SUTItemList = new ArrayList<CoverableItem>(coverableItemSet);
            List<CoverableItem> CoveredItemList;

            //Adding all of the SUT Nodes to the graph:
            //-----------------------------------------
            for (int j = 0; j < SUTItemList.size(); j++) {
                boolean ex = false;
                HierarchyLevel methodLevel = null;
                try {
                    methodLevel = getSUTItemMethod(SUTItemList.get(j));
                } catch (IllegalArgumentException e1) {
                    // the item is a condition, it is not possible to get the parent statement in the tree (it's parent is null)
                    ex = true;
                } catch (Exception e2) {
                    ex = true;
                }

                if (methodLevel != null && !ex) {
                    String PackageName = getSUTItemPackage(getSUTItemClass(methodLevel));
                    String ClassName = getSUTItemClass(methodLevel).getName();
                    String MethodName = methodLevel.getName();

                    String ItemName = getSUTItemId(SUTItemList.get(j).getId());
                    String nodeName = getNodeLable(SUTLevel, PackageName, ClassName, MethodName, ItemName);
                    if (!SUTItemsId.contains(nodeName)) {
                        SUTNode = new CoverageGraphNode("SUT", SUTLevel, PackageName, ClassName,
                                getSUTItemClass(methodLevel).getLocation().getLocations().get(0), MethodName,
                                methodLevel.getLocation().getLocations().get(0), ItemName, loc, StContent,
                                methodLevel, CompleteName);
                        SUTItemsId.add(SUTNode.getLable());
                        SUTItems.add(SUTNode);
                        NumOfSUTNodes++;
                        if (!ShowOnlyCovered)
                            graph.addVertex(SUTNode);
                    }
                }
            }

            Set<CoverableItem> coveredItemSet;
            int testsize = 0;
            if (!selectedTestCases.equals(null))
                testsize = selectedTestCases.size();
            for (int i = 0; i < testsize; i++) {

                //Adding Test Nodes to the graph:
                //-------------------------------
                TestCase tc = (TestCase) selectedTestCases.get(i);
                TestNode = new CoverageGraphNode("Test", TestLevel, getTestNodeName(tc.getName(), "Package"),
                        getTestNodeName(tc.getName(), "Class"), getTestNodeName(tc.getName(), "Method"),
                        CompleteName);
                String testNodeName = TestNode.getLable();
                if (!TestItemsId.contains(testNodeName)) {
                    TestItemsId.add(TestNode.getLable());
                    TestItems.add(TestNode);
                    graph.addVertex(TestNode);
                    TestNode.Testcases.add(tc);
                    NumOfTestNodes++;
                } else {
                    for (int k = 0; k < NumOfTestNodes; k++)
                        if (TestItems.get(k).getLable().compareTo(testNodeName) == 0)
                            TestNode = TestItems.get(k);
                    TestNode.Testcases.add(tc);
                }

                Map<CoverableItem, Long> CoveredItemMap = tc.getCoverageData();
                coveredItemSet = new HashSet<CoverableItem>();
                for (int j = 0; j < SUTItemList.size(); j++) {
                    coveredItemSet.add(SUTItemList.get(j));
                }
                coveredItemSet.retainAll(CoveredItemMap.keySet());
                CoveredItemList = new ArrayList<CoverableItem>(coveredItemSet);

                String nodeName = "";
                for (int j = 0; j < CoveredItemList.size(); j++) {
                    boolean ex = false;
                    HierarchyLevel methodLevel = null;
                    HierarchyLevel currentlevel = null;
                    try {
                        methodLevel = getSUTItemMethod(CoveredItemList.get(j));
                    } catch (Exception ec) {
                        ex = true;
                    }

                    if (methodLevel != null && !ex) {
                        String PackageName = getSUTItemPackage(getSUTItemClass(methodLevel));
                        String ClassName = getSUTItemClass(methodLevel).getName();
                        String MethodName = methodLevel.getName();
                        String ItemName = getSUTItemId(CoveredItemList.get(j).getId());
                        nodeName = getNodeLable(SUTLevel, PackageName, ClassName, MethodName, ItemName);
                        //Adding Edges to the graph:
                        //--------------------------
                        Integer id = graph.getEdgeCount() + 1;
                        CoverageGraphLink CoverageLink = graph.findEdge(TestItems.lastElement(),
                                SUTItems.elementAt(SUTItemsId.indexOf(nodeName)));
                        if (CoverageLink == null) {
                            CoverageLink = new CoverageGraphLink(id);
                            CoverageLink.SUTLevel = SUTLevel;
                        } else
                            graph.removeEdge(CoverageLink);
                        CoverageLink.times++;

                        CoverageGraphNode CurrentNode = new CoverageGraphNode();
                        for (int k = 0; k < NumOfSUTNodes; k++)
                            if (SUTItems.get(k).getLable().compareTo(nodeName) == 0)
                                CurrentNode = SUTItems.get(k);
                        if (CurrentNode != null) {
                            if (ShowOnlyCovered)
                                graph.addVertex(CurrentNode);

                            //For calculating Ratio:
                            if (SUTLevel.compareTo("Method") == 0)
                                currentlevel = methodLevel;
                            else if (SUTLevel.compareTo("Class") == 0)
                                currentlevel = topLevel.getParent(methodLevel);
                            else if (SUTLevel.compareTo("Package") == 0) {
                                currentlevel = topLevel.getParent(methodLevel);
                                currentlevel = topLevel.getParent(currentlevel);
                            }
                            if (currentlevel != null) {
                                CoverageResult coverageResult = null;
                                if (Criterion.compareTo("Statement") == 0) {
                                    StatementCoverage coverageMetric = StatementCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Branch") == 0) {
                                    BranchCoverage coverageMetric = BranchCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Loop") == 0) {
                                    LoopCoverage coverageMetric = LoopCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Term") == 0) {
                                    TermCoverage coverageMetric = TermCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                }
                                if (coverageResult != null) {
                                    float coverage = 0f;
                                    if (coverageResult.getTotalItems() > 0) {
                                        coverage = ((float) coverageResult.getCoveredItems()
                                                / coverageResult.getTotalItems());
                                    }
                                    CoverageLink.ratio = coverage;
                                }
                            } else
                                CoverageLink.ratio = 2;
                            graph.addEdge(CoverageLink, TestItems.lastElement(), CurrentNode,
                                    EdgeType.DIRECTED);
                        }
                    }
                }
                coveredItemSet.clear();
            }
        }
    } catch (Exception ex) {
        return null;
    }
    return graph;
}

From source file:org.sakaiproject.site.tool.AdminSitesAction.java

/**
 * Read the site form and update the site in state.
 * /*from www.jav  a  2s  .  com*/
 * @return true if the form is accepted, false if there's a validation error (an alertMessage will be set)
 */
private boolean readSiteForm(RunData data, SessionState state) {
    // read the form
    String id = StringUtil.trimToNull(data.getParameters().getString("id"));
    String title = StringUtil.trimToNull(data.getParameters().getString("title"));
    String type = StringUtil.trimToNull(data.getParameters().getString("type"));
    String shortDescription = StringUtil.trimToNull(data.getParameters().getString("shortDescription"));
    String description = StringUtil.trimToNull(data.getParameters().getString("description"));
    boolean joinable = data.getParameters().getBoolean("joinable");
    String joinerRole = StringUtil.trimToNull(data.getParameters().getString("joinerRole"));
    String icon = StringUtil.trimToNull(data.getParameters().getString("icon"));
    String info = StringUtil.trimToNull(data.getParameters().getString("info"));
    boolean published = data.getParameters().getBoolean("published");
    boolean softlyDeleted = data.getParameters().getBoolean("softlyDeleted");
    String skin = StringUtil.trimToNull(data.getParameters().getString("skin"));
    boolean pubView = data.getParameters().getBoolean("pubView");
    boolean customOrder = data.getParameters().getBoolean("customOrder");

    // get the site
    Site site = (Site) state.getAttribute("site");

    // add if needed
    if (site == null) {
        try {
            site = SiteService.addSite(id, type);
            // mark the site as new, so on cancel it can be deleted
            site.getPropertiesEdit().addProperty("new", "true");

            // put the site in the state
            state.setAttribute("site", site);
        } catch (IdUsedException e) {
            addAlert(state, rb.getFormattedMessage("sitact.thesitid", new Object[] { id }));
            return false;
        } catch (IdInvalidException e) {
            addAlert(state, rb.getFormattedMessage("sitact.thesitid2", new Object[] { id }));
            return false;
        } catch (PermissionException e) {
            addAlert(state, rb.getFormattedMessage("sitact.youdonot2", new Object[] { id }));
            return false;
        }
    }

    // update
    if (site != null) {
        if (joinable) {
            // check if there is a qualifed role in the role field
            if ((joinerRole == null) || (joinerRole.equals(""))) {
                addAlert(state, rb.getString("sitact.sperol"));
                return false;
            }
            Vector roles = new Vector();
            Vector roleIds = new Vector();
            AuthzGroup realm = null;
            try {
                realm = authzGroupService.getAuthzGroup(site.getReference());
                roles.addAll(realm.getRoles());
            } catch (GroupNotDefinedException e) {
                // use the type's template, if defined
                String realmTemplate = "!site.template";
                if (type != null) {
                    realmTemplate = realmTemplate + "." + type;
                }
                try {
                    AuthzGroup r = authzGroupService.getAuthzGroup(realmTemplate);
                    roles.addAll(r.getRoles());
                } catch (GroupNotDefinedException err) {
                    try {
                        AuthzGroup rr = authzGroupService.getAuthzGroup("!site.template");
                        roles.addAll(rr.getRoles());
                    } catch (GroupNotDefinedException ee) {
                    }
                }
            }

            for (int i = 0; i < roles.size(); i++) {
                roleIds.add(((Role) roles.elementAt(i)).getId());
            }

            if (!roleIds.contains(joinerRole)) {
                addAlert(state, rb.getString("sitact.sperol"));
                return false;
            }
        }

        site.setTitle(title);
        site.setShortDescription(shortDescription);
        site.setDescription(description);
        site.setJoinable(joinable);
        site.setJoinerRole(joinerRole);
        site.setIconUrl(icon);
        site.setInfoUrl(info);
        site.setSkin(skin);
        site.setType(type);
        site.setPubView(pubView);
        site.setPublished(published);
        site.setSoftlyDeleted(softlyDeleted);
        site.setCustomPageOrdered(customOrder);
    }

    return true;

}

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * This method handles the <code>request=logout</code> user request. <br>
 * <br>/*from  w  ww .j  a  v  a 2  s .c om*/
 * <b>Description:</b> <br>
 * The request can be used to logout a user by sending a saml logoutrequest. <br>
 * e.g. if the user sends a normal request=logout but actually was a saml user and should have send a samlrequest <br>
 * <br>
 * <b>Preconditions:</b> <br>
 * Valid TGT <br>
 * <br>
 * <b>Postconditions:</b> <br>
 * <br>
 * 
 * @param htServiceRequest
 *            HashMap containing request parameters
 * @param servletResponse
 *            Used to send (HTTP) information back to user
 * @param pwOut
 *            Used to write information back to the user (HTML)
 * @throws ASelectException
 */
private void handleSamlLogout(HashMap htServiceRequest, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse, PrintWriter pwOut) throws ASelectException {
    String sMethod = "handleSamlLogout";
    String sRemoteAsUrl = null;

    _systemLogger.log(Level.FINER, _sModule, sMethod, "handleSamlLogout");

    String sTgt = (String) htServiceRequest.get("aselect_credentials_tgt");

    if (_htTGTContext != null) { // must be true for samllogout
        LogoutRequestSender logoutRequestSender = new LogoutRequestSender();
        //            String sIssuer = (String)_htTGTContext.get("sp_issuer");
        String sIssuer = _sServerUrl; // set idp as issuer
        String sNameID = (String) _htTGTContext.get("name_id");
        String sAppId = (String) _htTGTContext.get("app_id");
        //  find a way to get the default, maybe from application section
        // If we allow this we must sanitize this url !!!
        String sLogoutReturnUrl = (String) htServiceRequest.get("logout_return_url");
        if (sLogoutReturnUrl != null) {
            _systemLogger.log(Level.FINER, _sModule, sMethod,
                    "Found logout_return_url in request: " + sLogoutReturnUrl);
            // For backward compatibility, avoid double decoding
            boolean doDecode = true; // backward compatibility
            HashMap<String, Vector<String>> parameters2decode = _configManager.getParameters2decode();
            if (parameters2decode != null && !parameters2decode.isEmpty()) {
                Vector<String> appl = parameters2decode.get("logout_return_url");
                if (Utils.hasValue(sAppId) && appl != null && appl.contains(sAppId)) { // already decoded
                    doDecode = false;
                    _systemLogger.log(Level.FINER, _sModule, sMethod, "logout_return_url already urldecoded");
                }
            }
            if (doDecode) {
                try {
                    sLogoutReturnUrl = URLDecoder.decode(sLogoutReturnUrl, "UTF-8");
                    _systemLogger.log(Level.FINER, _sModule, sMethod,
                            "logout_return_url after decoding: " + sLogoutReturnUrl);
                } catch (UnsupportedEncodingException e) {
                    _systemLogger.log(Level.WARNING, _sModule, sMethod,
                            "Unable to urldecode, unsupported encoding UTF-8");
                    throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
                }
            }
        }
        // We need to get the logout url from somewhere too
        String url = _sServerUrl + "/saml20_idp_slo_http_request";

        // 20120611, Bauke: added "usi"
        String sUsi = (String) _htTGTContext.get("usi");
        if (Utils.hasValue(sUsi)) // overwrite
            _timerSensor.setTimerSensorId(sUsi);
        if (Utils.hasValue(sAppId))
            _timerSensor.setTimerSensorAppId(sAppId);

        _systemLogger.log(Level.FINER, _sModule, sMethod, "Compose sendLogoutRequest to: " + url);

        logoutRequestSender.sendLogoutRequest(servletRequest, servletResponse, sTgt, url, sIssuer/* issuer */,
                sNameID, "urn:oasis:names:tc:SAML:2.0:logout:user", sLogoutReturnUrl, null, null);

        return;
    } else {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "No tgt found!");
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
    }
}

From source file:org.exolab.castor.jdo.engine.SQLStatementQuery.java

private void buildStatement() throws MappingException {
    try {//from   w ww.  j  a v  a 2  s  .  c om
        QueryExpression expr = _factory.getQueryExpression();

        Map<String, Boolean> identitiesUsedForTable = new HashMap<String, Boolean>();
        Vector<String> joinTables = new Vector<String>();

        // join all the extended table
        ClassDescriptor curDesc = _engine.getDescriptor();
        ClassDescriptor baseDesc;
        while (curDesc.getExtends() != null) {
            baseDesc = curDesc.getExtends();
            String[] curDescIdNames = SQLHelper.getIdentitySQLNames(curDesc);
            String[] baseDescIdNames = SQLHelper.getIdentitySQLNames(baseDesc);
            expr.addInnerJoin(new ClassDescriptorJDONature(curDesc).getTableName(), curDescIdNames,
                    new ClassDescriptorJDONature(curDesc).getTableName(),
                    new ClassDescriptorJDONature(baseDesc).getTableName(), baseDescIdNames,
                    new ClassDescriptorJDONature(baseDesc).getTableName());
            joinTables.add(new ClassDescriptorJDONature(baseDesc).getTableName());
            curDesc = baseDesc;
        }

        SQLColumnInfo[] ids = _engine.getColumnInfoForIdentities();
        SQLFieldInfo[] fields = _engine.getInfo();

        // join all the related/depended table
        String aliasOld = null;
        String alias = null;

        for (int i = 0; i < fields.length; i++) {
            SQLFieldInfo field = fields[i];

            if (i > 0) {
                aliasOld = alias;
            }
            alias = field.getTableName();

            // add id fields for root table if first field points to a separate table
            if ((i == 0) && field.isJoined()) {
                String[] identities = SQLHelper.getIdentitySQLNames(_engine.getDescriptor());
                for (int j = 0; j < identities.length; j++) {
                    expr.addColumn(new ClassDescriptorJDONature(curDesc).getTableName(), identities[j]);
                }
                identitiesUsedForTable.put(new ClassDescriptorJDONature(curDesc).getTableName(), Boolean.TRUE);
            }

            // add id columns to select statement
            if (!alias.equals(aliasOld) && !field.isJoined()) {
                ClassDescriptor classDescriptor = field.getFieldDescriptor().getContainingClassDescriptor();
                boolean isTableNameAlreadyAdded = identitiesUsedForTable
                        .containsKey(new ClassDescriptorJDONature(classDescriptor).getTableName());
                if (!isTableNameAlreadyAdded) {
                    String[] identities = SQLHelper.getIdentitySQLNames(classDescriptor);
                    for (int j = 0; j < identities.length; j++) {
                        expr.addColumn(alias, identities[j]);
                    }
                    identitiesUsedForTable.put(new ClassDescriptorJDONature(classDescriptor).getTableName(),
                            Boolean.TRUE);
                }
            }

            if (field.isJoined()) {
                int offset = 0;
                String[] rightCol = field.getJoinFields();
                String[] leftCol = new String[ids.length - offset];
                for (int j = 0; j < leftCol.length; j++) {
                    leftCol[j] = ids[j + offset].getName();
                }
                ClassDescriptor clsDescriptor = _engine.getDescriptor();
                ClassDescriptorJDONature nature = new ClassDescriptorJDONature(clsDescriptor);
                if (joinTables.contains(field.getTableName())
                        || nature.getTableName().equals(field.getTableName())) {

                    // should not mix with aliases in ParseTreeWalker
                    alias = alias.replace('.', '_') + "_f" + i;
                    expr.addOuterJoin(_mapTo, leftCol, field.getTableName(), rightCol, alias);
                } else {
                    expr.addOuterJoin(_mapTo, leftCol, field.getTableName(), rightCol, field.getTableName());
                    joinTables.add(field.getTableName());
                }
            }

            for (int j = 0; j < field.getColumnInfo().length; j++) {
                expr.addColumn(alias, field.getColumnInfo()[j].getName());
            }

            expr.addTable(field.getTableName(), alias);
        }

        // 'join' all the extending tables 
        List<ClassDescriptor> classDescriptorsToAdd = new LinkedList<ClassDescriptor>();
        ClassDescriptor classDescriptor = null;
        SQLHelper.addExtendingClassDescriptors(classDescriptorsToAdd,
                new ClassDescriptorJDONature(_engine.getDescriptor()).getExtended());

        if (classDescriptorsToAdd.size() > 0) {
            Iterator<ClassDescriptor> iter = classDescriptorsToAdd.iterator();
            while (iter.hasNext()) {
                classDescriptor = iter.next();
                ClassDescriptorJDONature clsDescNature = new ClassDescriptorJDONature(classDescriptor);
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Adding outer left join for " + classDescriptor.getJavaClass().getName()
                            + " on table " + clsDescNature.getTableName());
                }

                String[] engDescIdNames = SQLHelper.getIdentitySQLNames(_engine.getDescriptor());
                String[] clsDescIdNames = SQLHelper.getIdentitySQLNames(classDescriptor);
                expr.addOuterJoin(_mapTo, engDescIdNames, clsDescNature.getTableName(), clsDescIdNames,
                        clsDescNature.getTableName());

                Persistence persistenceEngine;
                try {
                    persistenceEngine = _factory.getPersistence(classDescriptor);
                } catch (MappingException e) {
                    throw new QueryException("Problem obtaining persistence engine for ClassDescriptor "
                            + classDescriptor.getJavaClass().getName(), e);
                }

                SQLEngine engine = (SQLEngine) persistenceEngine;
                SQLColumnInfo[] idInfos = engine.getColumnInfoForIdentities();
                for (int i = 0; i < idInfos.length; i++) {
                    expr.addColumn(clsDescNature.getTableName(), idInfos[i].getName());
                }

                SQLFieldInfo[] fieldInfos = ((SQLEngine) persistenceEngine).getInfo();
                for (int i = 0; i < fieldInfos.length; i++) {
                    boolean hasFieldToAdd = false;
                    SQLColumnInfo[] columnInfos = fieldInfos[i].getColumnInfo();
                    if (clsDescNature.getTableName().equals(fieldInfos[i].getTableName())) {
                        for (int j = 0; j < columnInfos.length; j++) {
                            expr.addColumn(clsDescNature.getTableName(),
                                    fieldInfos[i].getColumnInfo()[j].getName());
                        }
                        hasFieldToAdd = true;
                    }

                    if (hasFieldToAdd) {
                        expr.addTable(clsDescNature.getTableName(), clsDescNature.getTableName());
                    }
                }
            }
        }

        // add table information if the class in question does not have any non-identity fields
        if (fields.length == 0) {
            for (int i = 0; i < ids.length; i++) {
                expr.addColumn(_mapTo, ids[i].getName());
            }
        }

        _queryExpression = expr;

        if (LOG.isTraceEnabled()) {
            LOG.trace(Messages.format("jdo.finding", _type, _queryExpression));
        }
    } catch (QueryException ex) {
        LOG.warn("Problem building SQL", ex);
        throw new MappingException(ex);
    }
}

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) {

    ////from ww  w  . ja  v a 2s .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:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java

/**
 * Should translate the aggregated query to the appropriate type according to the middleware underneath
 * and return appropriate readings/values. The type of values should be stored elsewhere (at the VITRO Service Provider (VSP) !
 * TODO: NOTICE: for now the SensorModelId here is a hashcode of the simple name of the capability (resource name) .
 * TODO: ^^^^^^^ It is also always positive so multiply by *(-1) if it is not.
 * TODO: ^^^^^^^ This is inconsistent with what we sent for uberdust in the registration
 * TODO: ^^^^^^^ because for now the framework will ignore this setting on the RegisterSensor messages, and will just calculate it on its own from the hashcode of the resource names.
 *
 *
 *
 * @param motesAndTheirSensorAndFunctsVec Vector of moteIds mapped to their sensors (those of them that are involved in the query) and the requested function ids
 * @param reqFunctionVec        Vector with Functions to be applied to query data
 * @return a Vector of the Results as ReqResultOverData structures (XML)
 *//*from   w ww. j a  v a2  s.c  o m*/
// TODO: Important
public synchronized Vector<ReqResultOverData> translateAggrQuery(
        Vector<QueriedMoteAndSensors> motesAndTheirSensorAndFunctsVec,
        Vector<ReqFunctionOverData> reqFunctionVec) {

    if (DEBUG_OFFLINE_MODE) {
        return DEBUG_offline_translateAggrQuery(motesAndTheirSensorAndFunctsVec, reqFunctionVec);
    }

    boolean useTheStandardWayToGetStateForActuatorReading = false; // false allows to get explicitly the latest reading instead of the standard one (in the general status page) updated every few minutes
    // TODO: tmp structure to be replaced when this is tested and works
    Vector<VerySimpleSensorEntity> allSensorsWithCapsAndMeasures = new Vector<VerySimpleSensorEntity>();
    // Maps Smart Device ids to Room names, where the room names are available.
    HashMap<String, String> smartDevIdsToRooms = new HashMap<String, String>();
    //
    // ##########################################################################################################################################
    //
    /*
     * TODO: optimize the status/resource retrieval process for uberdust!
     * TODO: Take into account the mote status before ADDING it to the gateway description list (++++ LATER)
     *         For now we assume that the queries to the actual WSN are handled by the middleware.
     *         We search the uberdust "database" for data. (but we can still perform actions to affect the WSI!)
     *
     *         The plan is for a future service
     *         where a peer could submit queries for submission in the actual WSNs, and subsequently gather the data
     *         of the results. (e.g. administration service>reprogramming service)
     */
    HttpClient httpclient = new DefaultHttpClient();
    try {
        //
        //
        // TODO: x, y, z can be used with wisedb Coordinate.java (look code) to produce GoogleEarth Coordinates (what ISO is that? Can it be advertised in SensorML for IDAS ?)
        // TODO: make use of Description and Type and Room Fields when available ?
        // TODO: Make a summary, how many valid from those found in uberdust? How many were registered successfully? How many measurements were registered successfully?
        //
        //
        HttpGet httpUberdustNodesGet = new HttpGet(uberdustNodesGetRestUri);
        HttpResponse httpUberdustNodesGetResponse = httpclient.execute(httpUberdustNodesGet);

        int httpUberdustNodesGetResponseStatusCode = httpUberdustNodesGetResponse.getStatusLine()
                .getStatusCode();
        HttpEntity httpUberdustNodesGetResponseEntity = httpUberdustNodesGetResponse.getEntity();
        if (httpUberdustNodesGetResponseEntity != null) {

            String responseBodyStr = EntityUtils.toString(httpUberdustNodesGetResponseEntity);
            if (httpUberdustNodesGetResponseStatusCode != 200) {
                // responseBody will have the error response
                logger.debug("--------ERROR Response: " + httpUberdustNodesGetResponseStatusCode
                        + "------------------------------");
                logger.debug(responseBodyStr);
                logger.debug("----------------------------------------");
            } else {
                //logger.debug("--------OK Response: "+ httpUberdustNodesGetResponseStatusCode+"------------------------------");
                //
                String[] nodeUrnsInUberdust = responseBodyStr.split("\\r?\\n");
                int totalNodeUrnsInUberdust = nodeUrnsInUberdust.length;

                HttpGet httpUberdustNodes_STATUS_Get = new HttpGet(uberdustNodes_Status_GetRestUri);
                HttpResponse httpUberdustNodes_STATUS_GetResponse = httpclient
                        .execute(httpUberdustNodes_STATUS_Get);

                int httpUberdustNodes_STATUS_GetResponseStatusCode = httpUberdustNodes_STATUS_GetResponse
                        .getStatusLine().getStatusCode();
                HttpEntity httpUberdustNodes_STATUS_GetResponseEntity = httpUberdustNodes_STATUS_GetResponse
                        .getEntity();
                if (httpUberdustNodes_STATUS_GetResponseEntity != null) {
                    String responseBody_STATUS_Str = EntityUtils
                            .toString(httpUberdustNodes_STATUS_GetResponseEntity);
                    if (httpUberdustNodes_STATUS_GetResponseStatusCode != 200) {
                        // responseBody_STATUS_Str will have the error response
                        logger.debug("--------ERROR Response: " + httpUberdustNodes_STATUS_GetResponseStatusCode
                                + "------------------------------");
                        logger.debug(responseBody_STATUS_Str);
                        logger.debug("----------------------------------------");
                    } else {
                        //logger.debug("--------OK Response: "+ httpUberdustNodes_STATUS_GetResponseStatusCode+"------------------------------");

                        String[] nodeAndLastCapReadingsUrnsInUberdust = responseBody_STATUS_Str
                                .split("\\r?\\n");
                        int totalNodeWithCapsInUberdust = nodeAndLastCapReadingsUrnsInUberdust.length;

                        // LOOP OVER EVERY NODE (smart device), and for each node, get its capabilities from the second response (responseBody_STATUS_Str)
                        Vector<String> allFaultyNodesUrns = getFaultyNodes();

                        for (String aNodeUrnsInUberdust : nodeUrnsInUberdust) {
                            if (allFaultyNodesUrns.contains(aNodeUrnsInUberdust)) {
                                logger.debug("Skiipping node: " + aNodeUrnsInUberdust);
                                continue;
                            }
                            Vector<VerySimpleObservationCapabilities> sensObsCapsVector = new Vector<VerySimpleObservationCapabilities>();
                            Vector<VerySimpleSensorMeasurement> sensObsMeasurementVector = new Vector<VerySimpleSensorMeasurement>();

                            if (VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg()
                                    .equalsIgnoreCase("vitrogw_hai")) {
                                aNodeUrnsInUberdust = dictionaryUberdustUrnToHaiUrnName
                                        .get(aNodeUrnsInUberdust);
                                if (aNodeUrnsInUberdust == null)
                                    continue;
                            }

                            //                                logger.debug("Iteration " + String.valueOf(k+1) + " of " + String.valueOf(totalNodeUrnsInUberdust));
                            //                                logger.debug(nodeUrnsInUberdust[k]);

                            Vector<Integer> sensorModels_IDs_OfSmartDevVector = new Vector<Integer>();
                            CSmartDevice tmpSmartDev = new CSmartDevice(aNodeUrnsInUberdust,
                                    "", /* smart device type name */
                                    "", /* location description e.g. room1*/
                                    new GeodesicPoint(), /*  */
                                    sensorModels_IDs_OfSmartDevVector);

                            // TODO: Add an extra early for loop to update the fields for the attributes of the SmartDevice such as:
                            //      Eventually if the SmartDev has NO other valid sensors (e.g. observation sensors or actuators) then it won't be added !
                            String tmp_longitude = "";
                            String tmp_latitude = "";
                            String tmp_altitude = "";

                            for (String aNodeAndLastCapReadingsUrnsInUberdust1 : nodeAndLastCapReadingsUrnsInUberdust) {
                                //to update the device attributes!
                                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust1
                                        .split("\\t");
                                if (VitroGatewayService.getVitroGatewayService()
                                        .getAssignedGatewayUniqueIdFromReg().equalsIgnoreCase("vitrogw_hai")) {
                                    nodeCapAndReadingRowItems[0] = dictionaryUberdustUrnToHaiUrnName
                                            .get(nodeCapAndReadingRowItems[0]);
                                    if (nodeCapAndReadingRowItems[0] == null)
                                        continue;
                                }

                                if (nodeCapAndReadingRowItems.length > 3 && nodeCapAndReadingRowItems[0]
                                        .compareToIgnoreCase(aNodeUrnsInUberdust) == 0) //we are at the capabilities of the current smartdevice
                                {
                                    // [0] is mote (smart device) id
                                    // [1] is capability
                                    // [2] is timestamp
                                    // [3] is measurement value
                                    if ((nodeCapAndReadingRowItems[1] != null)
                                            && !(nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase(""))) {
                                        if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("room")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            tmpSmartDev.setLocationDesc(nodeCapAndReadingRowItems[3].trim());
                                            smartDevIdsToRooms.put(tmpSmartDev.getId(),
                                                    tmpSmartDev.getLocationDesc());
                                        } else if (nodeCapAndReadingRowItems[1].trim()
                                                .equalsIgnoreCase("nodetype")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            tmpSmartDev.setName(nodeCapAndReadingRowItems[3].trim());
                                        } else if (nodeCapAndReadingRowItems[1].trim()
                                                .equalsIgnoreCase("description")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: do we need this?

                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("x")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: we need the function to derive a valid longitude from the uberdust value (pending)
                                            tmp_longitude = nodeCapAndReadingRowItems[3].trim();
                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("y")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: we need the function to derive a valid latitude)
                                            tmp_latitude = nodeCapAndReadingRowItems[3].trim();
                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("z")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //altitude is in meters (assumption)
                                            tmp_altitude = nodeCapAndReadingRowItems[3].trim();

                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("phi")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: do we need this?
                                        } else if (nodeCapAndReadingRowItems[1].trim().equalsIgnoreCase("theta")
                                                && nodeCapAndReadingRowItems[3] != null
                                                && !nodeCapAndReadingRowItems[3].trim().equalsIgnoreCase("")) {
                                            //TODO: do we need this?
                                        }
                                    }
                                }
                            } // end of first round of for loop for attributes
                            if (!tmp_latitude.equalsIgnoreCase("") && !tmp_longitude.equalsIgnoreCase("")
                                    && !tmp_altitude.equalsIgnoreCase("")) {
                                tmpSmartDev.setGplocation(
                                        new GeodesicPoint(tmp_latitude, tmp_longitude, tmp_altitude));
                            }

                            //
                            // Again same loop for measurement and actuation capabilities!
                            //
                            for (String aNodeAndLastCapReadingsUrnsInUberdust : nodeAndLastCapReadingsUrnsInUberdust) {
                                String[] nodeCapAndReadingRowItems = aNodeAndLastCapReadingsUrnsInUberdust
                                        .split("\\t");
                                if (VitroGatewayService.getVitroGatewayService()
                                        .getAssignedGatewayUniqueIdFromReg().equalsIgnoreCase("vitrogw_hai")) {
                                    nodeCapAndReadingRowItems[0] = dictionaryUberdustUrnToHaiUrnName
                                            .get(nodeCapAndReadingRowItems[0]);
                                    if (nodeCapAndReadingRowItems[0] == null)
                                        continue;
                                }
                                if (nodeCapAndReadingRowItems.length > 3 && nodeCapAndReadingRowItems[0]
                                        .compareToIgnoreCase(aNodeUrnsInUberdust) == 0) //we are at the capabilities of the current smartdevice
                                {
                                    // [0] is mote (smart device) id
                                    // [1] is capability
                                    // [2] is measurement value
                                    // [3] is timestamp
                                    //                                        logger.debug(nodeCapAndReadingRowItems[1]);
                                    // TODO: FILTER OUT UNSUPPORTED OR COMPLEX CAPABILITIES!!!!
                                    // Since uberdust does not distinguish currenlty between sensing/actuating capabilities and properties, we need to filter out manually
                                    // everything we don't consider a sensing/actuating capability.
                                    // Another filtering out is done at a later stage with the SensorMLMessageAdapter, which will filter out the capabilities not supported by IDAS
                                    // TODO: it could be nice to have this filtering unified.
                                    if ((nodeCapAndReadingRowItems[1] != null)
                                            && (nodeCapAndReadingRowItems[1].trim().compareTo("") != 0)
                                            && !getSimpleCapForUberdustUrn(nodeCapAndReadingRowItems[1].trim())
                                                    .equalsIgnoreCase("UnknownPhenomenon")) {
                                        // The model id is set as the hashcode of the capability name appended with the model type of the device.
                                        // Perhaps this should be changed to something MORE specific
                                        // TODO: the units should be set here as we know them for Uberdust. Create a small dictionary to set them!
                                        // TODO: the non-observation sensors/ non-actuation should be filtered here!! the Name for the others should be "UnknownPhenomenon"

                                        String tmpGenericCapabilityForSensor = getSimpleCapForUberdustUrn(
                                                nodeCapAndReadingRowItems[1].trim());
                                        Integer thedigestInt = (tmpGenericCapabilityForSensor + "-"
                                                + tmpSmartDev.getName()).hashCode();
                                        if (thedigestInt < 0)
                                            thedigestInt = thedigestInt * (-1);

                                        //                                            /*
                                        //                                            CSensorModel tmpSensorModel = new CSensorModel(givGatewayInfo.getId(), /*Gateway Id*/
                                        //                                                    thedigestInt, /*Sensor Model Id */
                                        //                                                    (tmpGenericCapabilityForSensor + "-" + tmpSmartDev.getName()), /* Sensor Model name */
                                        //                                                    CSensorModel.numericDataType, /* Data type*/  // TODO: later on this should be adjustable!!!
                                        //                                                    CSensorModel.defaultAccuracy, /* Accuracy */
                                        //                                                    CSensorModel.defaultUnits) /* Units */;  // TODO: this should be set when it is known!!!

                                        // GET THE OBSERVATION
                                        VerySimpleObservationCapabilities tmpObsCap = new VerySimpleObservationCapabilities(
                                                nodeCapAndReadingRowItems[1], true);
                                        if ((tmpObsCap.getSimpleName() != null) && !(tmpObsCap.getSimpleName()
                                                .equalsIgnoreCase("UnknownPhenomenon"))) {
                                            sensObsCapsVector.add(tmpObsCap);

                                            // ts of measurement in place [2]
                                            // value of measurement in place [3]
                                            // logger.debug(nodeCapAndReadingRowItems[2]+'\t'+nodeCapAndReadingRowItems[3]);
                                            long theTimeStamp = Long.parseLong(nodeCapAndReadingRowItems[2]);
                                            String theValue = nodeCapAndReadingRowItems[3];
                                            if (theValue.contains(" "))
                                                theValue = theValue.split(" ")[0]; // if it contains the UOM as a suffix,then just keep the first part
                                            String observPropertyDef = tmpObsCap.getPhenomenonIDASUrn();
                                            String observOutputUOMCode = tmpObsCap.getUomIDASUrn();// tmpObsCap.getUomIDASCode();
                                            // just one (last) value
                                            String[] observOutputMeasurementData = new String[1];
                                            // Dummy measurement value
                                            if (tmpObsCap.getSimpleName().equalsIgnoreCase("temperature")) {
                                                //since we assume kelvin to be the default UOM, until fixed, wew set oiur ceslious to Kelvin here:
                                                //K = C+273 . TODO. Later on this normalization should be done at the VSP!
                                                double d = Double.parseDouble(theValue);
                                                double convertedKelvinValue = d + 273.0;
                                                String convertedKelvinValueStr = Long
                                                        .toString((long) convertedKelvinValue);

                                                observOutputMeasurementData[0] = convertedKelvinValueStr; //to kelvin
                                            } else {
                                                observOutputMeasurementData[0] = theValue;
                                            }
                                            // TODO: Check if timezone is correct!
                                            // FOR UBERDUST: override sensors timestamp with reply from uberdust timestamp (now)
                                            Date dateNow = new Date();
                                            theTimeStamp = dateNow.getTime();
                                            DateFormat df = new SimpleDateFormat(
                                                    "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
                                            String observPropertyTSStr = df.format(new Date(theTimeStamp));
                                            //logger.debug("---- " + observPropertyTSStr + " ---- " + theValue + " ----------------------------");
                                            sensObsMeasurementVector
                                                    .add(new VerySimpleSensorMeasurement(observPropertyDef,
                                                            observOutputUOMCode, observOutputMeasurementData,
                                                            observPropertyTSStr, theTimeStamp));
                                        }

                                        sensorModels_IDs_OfSmartDevVector.add(thedigestInt);

                                    }
                                }
                            }
                            if (!sensorModels_IDs_OfSmartDevVector.isEmpty()) {
                                // TODO: FILTER OUT UNSUPPORTED OR COMPLEX NODES!!!!
                                VerySimpleSensorEntity sens01 = new VerySimpleSensorEntity(aNodeUrnsInUberdust,
                                        sensObsCapsVector, sensObsMeasurementVector);
                                allSensorsWithCapsAndMeasures.add(sens01);

                                // TODO: MAYBE HERE WE CAN CHECK IF THESE MEASUREMENTS are for the results??
                                //if (!sensObsMeasurementVector.isEmpty())
                                //{
                                //    Iterator<VerySimpleSensorMeasurement> it1 = sensObsMeasurementVector.iterator();
                                //    while( it1.hasNext())
                                //    {
                                //        VerySimpleSensorMeasurement sensorMeasurement = (VerySimpleSensorMeasurement)it1.next();
                                //
                                //    }
                                //}
                                //#####################################
                            }
                        } // ends for loop over all smartdevices discovered!
                    } //if GET STATUS response code is OK!
                } // if GET STATUS response entity is NOT null
            } //if get list of nodes replied validly
        } //if get list of nodes response entity is NOT null
    } catch (Exception e) {
        logger.debug("error::" + e.getMessage());

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate de-allocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    //
    // TILL HERE WE HAVE A VECTOR WITH ALL Devices and Capabilities and Measurements: allSensorsWithCapsAndMeasures
    //
    //
    // LEGACY CODE
    //
    //
    //  TODO: This vector works now, but if we integrate components for sensors, we will need the real sensormodelIds to be registered by IDAS (DVNS),
    // (for now, only the hashcode of simple capabilities are considered to be the sensormodelids,(and this "hashcode" is set to always be a positive value, so if it is negative multiply it by (-1))
    //          thus forcing all sensor models that measure the same phenomenon to be considered identical .
    //
    // Q: a MAX function means maximum among readings from a sensor of a specific mote (aggregation)
    // or among readings from ALL motes (aggregation in a higher level)
    // A: We should actually interpret it as both. Since we have a timeperiod tag in the Function XML
    //    we can assume that we want the MAX over the values we took within that specified timeperiod (from all desired motes and all readings of their corresponding sensor)
    //    e.g.  In the period (Mon to Wed) mote-1 can have 20 light values from its light sensor, mote-2 can have 34 values etc. We calculate the max over all these.
    //    However if no timeperiod tag is set, we should assume that we get the MAX over only the Latest Value per mote, and probably in relatively current timewindow (e.g. from now() until a few hours ago)
    //    e.g. mote-1's latest light value is x1, mote-2 latest light value is x2 etc., and we calculate the max over just these values.
    //
    // We have a Vectors of functions to be applied and
    // a HashMap of SmartDevices (motes) mapped to those of their sensors that should be "queries"
    //
    // The steps are::
    // 1. For each mote ID:
    //        get each sensor ID and get all readings of mote.
    // 2. Fill in a Vector of ResultAggrStucts and send them with the Vector of Functions to executeFuctOverData for each function.
    //     This array is used because we want a generic format to send data to the function
    //     and that is the XML structure of the ResultAggrStruct.
    //     Each entry in the array has a mid, sid, (datatype), value AND timeperiod (from=to=timestamp) from database).
    // 3. Return a Vector of ReqResultOverData
    //
    // Note: Levels of aggregations should be:
    //       1. Values of motes specific sensor model (from light sensor 3006) (within a period of time, or all readings from the beginning of time!!)
    //       2. Values of all motes with the same sensor model   (aggragate over the results of step 1, over the involved motes)
    //       3. Values of all motes with sensor model that belongs to the same generic capability (e.g. light sensor 2000 and light sensor 3006 ( aggregate over the results of step 2)
    //       4. Values among gateways (this can be done only at the user peer).
    //
    // !! Note: No Longer Needed: --> Parse the moteID and extract WSN_ID and SMARTDEVICE_ID info (the format is WSN_ID::SMARTDEVICE_ID)
    //
    Vector<ResultAggrStruct> vOfSensorValues;

    Vector<ReqResultOverData> retVecofResults;
    retVecofResults = new Vector<ReqResultOverData>();

    //logger.debug("Size of motesAndTheirSensorAndFunctsVec::" + Integer.toString(motesAndTheirSensorAndFunctsVec.size())  );

    for (int i = 0; i < motesAndTheirSensorAndFunctsVec.size(); i++) {

        String fullMoteId = motesAndTheirSensorAndFunctsVec.elementAt(i).getMoteid();

        // for each entry, get the vector of queried sensor types and the functions to be applied to the measurements.
        List<ReqSensorAndFunctions> tmpVecSmAndFuncList = motesAndTheirSensorAndFunctsVec.elementAt(i)
                .getQueriedSensorIdsAndFuncVec();
        //            Vector<Integer> tmpVecSmIds =  motesAndTheirSensorHM.get(fullMoteId);
        /**
         *
         *  TODO: So far we assume all of the data types in measurements to be Long! This should be fixed!!!
         *
         */
        try {

            //
            // We have the readings from all sensors.
            // we must select only the readings from the specific sensors of interest (those inside the  tmpVecSmAndFuncList vector) .
            //

            //logger.debug("Size of tmpVecSmAndFuncList::" + Integer.toString(tmpVecSmAndFuncList.size())  );
            for (ReqSensorAndFunctions currentSensorModel : tmpVecSmAndFuncList) {
                int smid = currentSensorModel.getSensorModelIdInt();
                int countValuesOfthisSensorModel = 0;

                // TODO : fix to other connectors ->moved vOfSensorValues in the for loop!

                //logger.debug("For mote "+fullMoteId +" and sensor "+Integer.toString(smid) + " function vector size is "+reqFunctionVec.size());
                for (ReqFunctionOverData currentRequestedFunction : reqFunctionVec) {
                    vOfSensorValues = new Vector<ResultAggrStruct>();

                    if (currentRequestedFunction.getfuncId() == ReqFunctionOverData.unknownFuncId) {
                        vOfSensorValues
                                .addElement(new ResultAggrStruct(fullMoteId, smid, "No Result", 1, null));
                        countValuesOfthisSensorModel += 1;
                    } else if (currentSensorModel.getFunctionsOverSensorModelVec()
                            .contains(currentRequestedFunction.getfuncId())) { // this loop (and this condition) allows to retrieve the valid "functions" to be performed on values of this sensor
                        Vector<VerySimpleSensorMeasurement> mySensorReadingsRelatedToCurrentFunction = new Vector<VerySimpleSensorMeasurement>(); // bugfix: this is now moved inside the functions loop
                        // for each different "function" on the sensor values, we may need to gather completely different values. (e.g. a function could request a history of measurements, or only measurements that are above a threshold)
                        // TODO: Separate cases for binary values (e.g. image or webcam stream) and numeric values  (and string values?)

                        // TODO: for uberdust, loop through all nodes in (http get status vector): allSensorsWithCapsAndMeasures
                        //          and keep the readings, apply functions (FOR NOW WE ALWAYS APPLY LAST READING NO MATTER WHAT)
                        // TODO: Fix -> for now we always apply last reading no matter what the actual function was (since we have no history).
                        // TODO: fix serial numbers for sensor models. They should not just be the hash on the capability simple name...
                        for (VerySimpleSensorEntity tmpSmartDev : allSensorsWithCapsAndMeasures) {
                            if (tmpSmartDev.getSerialID().equalsIgnoreCase(fullMoteId)) // first match based on the requested smart device ID
                            {
                                for (VerySimpleSensorMeasurement tmpMeasurement : tmpSmartDev
                                        .getMeasurementsVector()) {
                                    String obsPropertyIDASUrn = tmpMeasurement.getObservPropertyDef();
                                    String obsPropertySimple = "lalala";
                                    Iterator<String> itDict = dictionaryNameToIDASPhenomenon.keySet()
                                            .iterator();
                                    String tmpSimpleName;
                                    // initial loop to get the "real" simple name for the search key capability (at this poing this is not yet a valid requested sensor)
                                    // we need the simple name because we used it to calculate the sensor model id (with the hashCode() )
                                    // so we get simple names, then calc their hashCodes (turn it into a positive number if it was negative) and then compare it with the requested hashcode (smid)  (assumed positive, because the DVNS will make sure of that)
                                    // logger.debug("^^^^^^^^^^OV: "+ obsPropertyIDASUrn);
                                    while (itDict.hasNext()) {
                                        tmpSimpleName = itDict.next();
                                        //logger.debug("^^^^^^^^^^VS: "+ (dictionaryNameToIDASPhenomenon.get(tmpSimpleName)).toString());

                                        if ((staticprefixPhenomenonIDAS
                                                + (dictionaryNameToIDASPhenomenon.get(tmpSimpleName)))
                                                        .equalsIgnoreCase(obsPropertyIDASUrn)) {
                                            //logger.debug("*** *** *** Found matching capability in dictionary:" + tmpSimpleName);
                                            obsPropertySimple = tmpSimpleName;
                                            break;
                                        }
                                    }

                                    int projectedSmIdforPropertyDef = obsPropertySimple.hashCode();
                                    if (projectedSmIdforPropertyDef < 0) {
                                        projectedSmIdforPropertyDef = projectedSmIdforPropertyDef * (-1);
                                    }

                                    if (smid == projectedSmIdforPropertyDef) {
                                        // debug:
                                        //                                            if((tmpSimpleName.equalsIgnoreCase("switchlight1")
                                        //                                                    ||tmpSimpleName.equalsIgnoreCase("switchlight2")
                                        //                                                    ||tmpSimpleName.equalsIgnoreCase("switchlight3")
                                        //                                                    ||tmpSimpleName.equalsIgnoreCase("switchlight4") )
                                        //                                                &&
                                        //                                            ((smartDevIdsToRooms.get(fullMoteId)!=null) && smartDevIdsToRooms.get(fullMoteId).equalsIgnoreCase("0.I.3")));
                                        //                                                    {
                                        //                                                logger.debug("*** *** *** ADDING A MEASUREMENT FOR: "+ tmpSimpleName + " Mote:" +fullMoteId + "Room: " + smartDevIdsToRooms.get(fullMoteId));
                                        //                                            }
                                        mySensorReadingsRelatedToCurrentFunction.add(tmpMeasurement);

                                        break; // TODO: break since a smartdevice will not have two of the same sensor models. Can it though? in general?
                                    }
                                    //else
                                    //{
                                    //    logger.debug("*** *** *** BUT DOES NOT MATCH A requested sensor: "+ tmpSimpleName);
                                    //}
                                }
                                break; //since we processed  the sensor dev that we wanted.
                            }
                        }

                        //logger.debug("READINGS LENGTH:" + Integer.toString(mySensorReadingsRelatedToCurrentFunction.length) );

                        for (int o = 0; o < mySensorReadingsRelatedToCurrentFunction.size(); o++) {
                            /* TODO: (++++) this could be optimized further (not write the entire data in the vector) / first process it
                             * according to the function.
                             * TODO: Somewhere around here we should handle the History function (not likely for uberdust)
                             */
                            //SensorTypes tmpSensor = jWebTypesManager.selectSensorType(smid);
                            long valueToAdd = -1;
                            //if(tmpSensor.getIsComplex() == false)
                            //{
                            // TODO: here we handle the actuation capabilities for lights as well, if a set value function was requested on them
                            // TODO: if a last value reading was requested we can handle that too by sending their state (as reported)
                            if (mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservPropertyDef()
                                    .equalsIgnoreCase(staticprefixPhenomenonIDAS
                                            + (dictionaryNameToIDASPhenomenon.get("switchlight1")))
                                    || mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservPropertyDef()
                                            .equalsIgnoreCase(staticprefixPhenomenonIDAS
                                                    + (dictionaryNameToIDASPhenomenon.get("switchlight2")))
                                    || mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservPropertyDef()
                                            .equalsIgnoreCase(staticprefixPhenomenonIDAS
                                                    + (dictionaryNameToIDASPhenomenon.get("switchlight3")))
                                    || mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservPropertyDef().equalsIgnoreCase(staticprefixPhenomenonIDAS
                                                    + (dictionaryNameToIDASPhenomenon.get("switchlight4")))) {
                                logger.debug("Function: " + currentRequestedFunction.getfuncName());
                                // TODO: for now we use the threshold field to set the actuation value! Later this could be a separate parameter field
                                if (currentRequestedFunction.getfuncName()
                                        .equalsIgnoreCase(ReqFunctionOverData.setValFunc)
                                        && currentRequestedFunction.getThresholdField() != null
                                        && !currentRequestedFunction.getThresholdField().isEmpty()) {
                                    logger.debug("-------- HANDLING ACTUATION NOW! "
                                            + mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                    .getObservPropertyDef()
                                            + " room: " + smartDevIdsToRooms.get(fullMoteId) + " mote: "
                                            + fullMoteId + " val: " + mySensorReadingsRelatedToCurrentFunction
                                                    .elementAt(o).getObservOutputMeasurementData()[0]);
                                    ThresholdStructure requiredThresholds = new ThresholdStructure(
                                            currentRequestedFunction.getThresholdField());
                                    if (requiredThresholds.getLowerBound() != null
                                            && !requiredThresholds.getLowerBound().isEmpty()) {
                                        logger.debug("Actuation parameter: "
                                                + requiredThresholds.getLowerBound().trim());
                                        // attempt to set the light to the desired value!
                                        // TODO: check if a valid value (0 or 1)
                                        try {
                                            String valStr = actuateSmartDevToValue(fullMoteId,
                                                    smartDevIdsToRooms.get(fullMoteId),
                                                    getUberdustUrnForIDASCapName(
                                                            mySensorReadingsRelatedToCurrentFunction
                                                                    .elementAt(o).getObservPropertyDef()),
                                                    requiredThresholds.getLowerBound().trim());
                                            double d = Double.parseDouble(valStr);
                                            valueToAdd = (long) d;
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            valueToAdd = -1;
                                        }

                                    }
                                } else {

                                    if (useTheStandardWayToGetStateForActuatorReading) {
                                        try {
                                            String valStr = mySensorReadingsRelatedToCurrentFunction
                                                    .elementAt(o).getObservOutputMeasurementData()[0];
                                            double d = Double.parseDouble(valStr);
                                            valueToAdd = (long) d;
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            valueToAdd = -1;
                                        }
                                    } else {
                                        String UberdustUrnForCap = getUberdustUrnForIDASCapName(
                                                mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                        .getObservPropertyDef());
                                        String justtheCapName = UberdustUrnForCap
                                                .substring(staticprefixUberdustCapability.length());
                                        //TODO: this masking is just for the demo!
                                        //mask light4 capability as light5 in order to show it in the demo: (light4 is not visible from the camera's viewpoint)
                                        // Changed light4 to lz4 to reflect naming change in uberdust
                                        if (justtheCapName.equalsIgnoreCase("lz4"))
                                            justtheCapName = "lz5";
                                        String lineOfStateReading = getLatestReadingTabSepLineForVirtualNode(
                                                fullMoteId, justtheCapName);
                                        String[] lineTokens = lineOfStateReading.split("\\t");
                                        // [0] has the timestamp
                                        // [1] has the value
                                        long valueOfReturnedState;
                                        String observPropertyTSStr;
                                        long theTimeStamp = 0;
                                        try {
                                            double d = Double.parseDouble(lineTokens[1]);
                                            valueOfReturnedState = (long) d;
                                            theTimeStamp = Long.parseLong(lineTokens[0]);
                                            DateFormat df = new SimpleDateFormat(
                                                    "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
                                            observPropertyTSStr = df.format(new Date(theTimeStamp));
                                            logger.debug("Actuator state was: " + lineTokens[1] + " at: "
                                                    + observPropertyTSStr);
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            DateFormat df = new SimpleDateFormat(
                                                    "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
                                            observPropertyTSStr = df.format(new Date(theTimeStamp));
                                            valueOfReturnedState = -1;

                                        }
                                        mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                .setObservPropertyTSLong(theTimeStamp);
                                        mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                .setObservPropertyTSStr(observPropertyTSStr);
                                        mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                                .getObservOutputMeasurementData()[0] = Long
                                                        .toString(valueOfReturnedState);
                                        // todo: move code repetition
                                        try {
                                            String valStr = mySensorReadingsRelatedToCurrentFunction
                                                    .elementAt(o).getObservOutputMeasurementData()[0];
                                            double d = Double.parseDouble(valStr);
                                            valueToAdd = (long) d;
                                        } catch (Exception e) {
                                            //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                            valueToAdd = -1;
                                        }
                                    }
                                }

                            } else {
                                try {
                                    String valStr = mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                            .getObservOutputMeasurementData()[0];
                                    double d = Double.parseDouble(valStr);
                                    valueToAdd = (long) d;
                                } catch (Exception e) {
                                    //logger.debug("*** *** *** OOOOO it's an exception for  ************ "+ mySensorReadingsRelatedToCurrentFunction.elementAt(o).getObservOutputMeasurementData()[0]);
                                    valueToAdd = -1;
                                }
                            }

                            long timestampOfReading = mySensorReadingsRelatedToCurrentFunction.elementAt(o)
                                    .getObservPropertyTSLong();
                            Timestamp timestampOfReadingSql = new Timestamp(timestampOfReading);
                            vOfSensorValues.addElement(new ResultAggrStruct(fullMoteId, smid,
                                    Long.toString(valueToAdd), 1,
                                    new TimeIntervalStructure(timestampOfReadingSql, timestampOfReadingSql)));
                            //}
                            //                                else// put blob value as a String (FOR NOW this is just a URL to the binary file so this is ok) (++++)
                            //                                    // TODO: later handling of binary data will change and we should send the real binary files over pipes to the client
                            //                                {
                            //                                    vOfSensorValues.addElement(new ResultAggrStruct(fullMoteId,
                            //                                        smid,
                            //                                        new String(myMotesSensorsReadings[o].getComplexRawData()),
                            //                                        1,
                            //                                        new TimeIntervalStructure(myMotesSensorsReadings[o].getDate(),
                            //                                                myMotesSensorsReadings[o].getDate()))
                            //                                    );
                            //                                }

                            countValuesOfthisSensorModel += 1;
                        }
                        if (countValuesOfthisSensorModel == 0) {
                            vOfSensorValues.addElement(new ResultAggrStruct(fullMoteId, smid,
                                    ReqResultOverData.specialValueNoReading, 1, null));
                            countValuesOfthisSensorModel += 1;
                        } else
                            logger.debug("Counted Values of this sensor: " + fullMoteId + " "
                                    + Integer.toString(countValuesOfthisSensorModel));
                    }
                    // this condition checks that at least one value was retrieved from the sensor and used in the function (even if that value was "no result")
                    if (countValuesOfthisSensorModel > 0) // we should make sure that this is always true.
                    {
                        retVecofResults.addElement(
                                new ReqResultOverData(currentRequestedFunction.getfuncId(), vOfSensorValues));
                    }
                } // ends the block where we gather values of a sensor for a specific function
            } // ends the loop over the requested sensor Models (capabilities) of the current requested Smart Device
        } catch (Exception e) {
            e.printStackTrace();
        }
    } // end of for loop over all requested Smart Devices in the request vector

    // here we have a Vector filled with ResultAggrStruct

    // END OF LEGACY driver code

    return retVecofResults;
}

From source file:csiro.pidsvc.mappingstore.ManagerJson.java

@SuppressWarnings("unchecked")
public JSONObject getMappingDependencies(Object thisMapping, String parentPath) throws SQLException {
    Vector<String> parentsList = new Vector<String>();
    PreparedStatement pst = null;
    ResultSet rs = null;/*from   w  w w. j  av a 2 s  .  c o m*/
    JSONObject ret = null, jsonThis = null, jsonParent = null, jsonParent2 = null;
    JSONArray jsonArr = null;
    String mappingPath, title;
    int mappingId, inheritors;

    try {
        // Get current mapping descriptor.
        if (thisMapping instanceof JSONObject) {
            jsonThis = (JSONObject) thisMapping;
            parentsList.add("__this");
        } else {
            mappingId = (Integer) thisMapping;
            pst = _connection.prepareStatement("SELECT a.mapping_path, a.title, a.description, a.creator, "
                    + "   (SELECT COUNT(1) FROM vw_active_mapping aa WHERE aa.parent = a.mapping_path) AS inheritors "
                    + "FROM mapping a " + "WHERE a.mapping_id = ?");
            pst.setInt(1, mappingId);

            if (pst.execute()) {
                jsonThis = new JSONObject();

                rs = pst.getResultSet();
                if (rs.next()) {
                    mappingPath = rs.getString("mapping_path");
                    title = rs.getString("title");
                    inheritors = rs.getInt("inheritors");

                    // Initial mapping ID is required for detection of cyclic inheritance.
                    parentsList.add(mappingPath);

                    jsonThis.put("id", "__this");
                    jsonThis.put("name", title == null ? mappingPath : title);
                    jsonThis.put("data",
                            JSONObjectHelper.create("mapping_path", mappingPath, "title", title, "description",
                                    rs.getString("description"), "author", rs.getString("creator"), "css",
                                    "chart_label_current", "inheritors", inheritors));
                    if (inheritors > 0) {
                        jsonArr = new JSONArray();
                        jsonArr.add(JSONObjectHelper.create("id", -2, "name",
                                inheritors + " inheritor" + (inheritors == 1 ? "" : "s") + "...", "data",
                                JSONObjectHelper.create("css", "chart_label_hidden", "inheritors",
                                        inheritors)));
                        jsonThis.put("children", jsonArr);
                    }
                }
            }
        }

        // Get parents.
        while (parentPath != null) {
            pst = _connection.prepareStatement("SELECT mapping_path, title, description, creator, parent "
                    + "FROM vw_active_mapping " + "WHERE mapping_path = ? AND type = 'Regex'");
            pst.setString(1, parentPath);

            parentPath = null;
            if (pst.execute()) {
                rs = pst.getResultSet();
                if (rs.next()) {
                    mappingPath = rs.getString("mapping_path");
                    title = rs.getString("title");
                    parentPath = rs.getString("parent");

                    // Prevent cyclic inheritance syndrome.
                    if (parentsList.contains(mappingPath)) {
                        jsonArr = new JSONArray();
                        jsonArr.add(jsonThis);

                        jsonParent = JSONObjectHelper.create("id", -3, "name", "ERROR", "data",
                                JSONObjectHelper.create("css", "chart_label_error", "description",
                                        "Cyclic inheritance encountered!<br/><br/>Please inspect the inheritance chain and rectify the problem. Mappings with detected cyclic inheritance will fall back to Catch-all mapping automatically."),
                                "children", jsonArr);
                        return jsonParent;
                    }

                    // Construct JSON for the first parent.
                    if (jsonParent2 == null) {
                        JSONObject tmp = new JSONObject();
                        tmp.put("id", mappingPath);
                        tmp.put("name", title == null ? mappingPath : title);
                        tmp.put("data", JSONObjectHelper.create("mapping_path", mappingPath, "title", title,
                                "description", rs.getString("description"), "author", rs.getString("creator")));

                        if (jsonParent == null) {
                            jsonArr = new JSONArray();
                            jsonArr.add(jsonThis);
                            jsonParent = tmp;
                            jsonParent.put("children", jsonArr);
                        } else if (jsonParent2 == null) {
                            jsonArr = new JSONArray();
                            jsonArr.add(jsonParent);
                            jsonParent2 = tmp;
                            jsonParent2.put("children", jsonArr);
                        }
                    }

                    // Add new parent to the list.
                    parentsList.add(mappingPath);
                }
            }
        }
        if (jsonParent == null)
            jsonParent = jsonThis;

        // Get catch-all mapping descriptor.
        String author = null, description = null;
        int hiddenParents = parentsList.size() - 2;

        pst = _connection.prepareStatement("SELECT description, creator " + "FROM vw_active_mapping "
                + "WHERE mapping_path IS NULL AND type = 'Regex'");
        if (pst.execute()) {
            if ((rs = pst.getResultSet()).next()) {
                author = rs.getString("creator");
                description = rs.getString("description");
            }
        }
        if (hiddenParents == 1)
            jsonParent = jsonParent2;
        else if (hiddenParents > 1) {
            jsonArr = new JSONArray();
            jsonArr.add(jsonParent);

            jsonParent = JSONObjectHelper.create("id", -1, "name", hiddenParents + " more parents...", "data",
                    JSONObjectHelper.create("css", "chart_label_hidden"), "children", jsonArr);
        }

        // Create return object.
        jsonArr = new JSONArray();
        jsonArr.add(jsonParent);
        ret = JSONObjectHelper.create("id", 0, "name", "&lt;Catch-all&gt;", "data", JSONObjectHelper.create(
                "author", author, "description", description, "css", "chart_label_root"), "children", jsonArr

        );
    } finally {
        if (rs != null)
            rs.close();
        if (pst != null)
            pst.close();
    }
    return ret;
}