List of usage examples for java.util Vector isEmpty
public synchronized boolean isEmpty()
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
@SuppressWarnings("unchecked") protected void sequentialXMLImportRecursion(Vector collectionNames, Vector collectionIds, String parentName, long parentId) { int idIndex = 0; try {/*from w w w. j a v a 2s. co m*/ // for each collection for (int z = 0; z < collectionNames.size(); z++) { // get table to work on String dbTable = collectionNames.get(z).toString(); String lowerdbTable = lowerFirstChar(dbTable); DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); String primaryKey = info.getPrimaryKeyName(); // open xml file File path = new File(importFolderPath + dbTable + ".xml"); //$NON-NLS-1$ Element dbImport = XMLHelper.readFileToDOM4J(path); DBTableInfo tableInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); // loop for each id that we need in this table for (int k = 0; k < collectionIds.size() && idIndex < collectionIds.size(); k++) { Vector newCollectionIds = new Vector(20); Vector newCollectionNames = new Vector(20); // the only way to get the value out of collectionIds Element temp_id = (Element) collectionIds.get(idIndex); // is this the right element to work on // if so use else; otherwise stop the loop if (temp_id.getName().equals(dbTable)) { idIndex++; String id = temp_id.getText(); // select the node // TODO shouldl not assume things are in order // Element collectingevent = // (Element)dbImport.selectSingleNode("//"+dbTable+"["+id+"]");//temp_id.getText()+"]"); Element collectingevent = (Element) dbImport.selectSingleNode("//" //$NON-NLS-1$ + dbTable + "[" + primaryKey + " = \"" + id + "\"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Iterator iter = collectingevent.elementIterator(); // make the element and the agent Map<String, Object> agentMap = new HashMap<String, Object>(); Object agent = tableInfo.getClassObj().newInstance(); do { Element element = (Element) iter.next(); Object value2 = findTypeSequential(element, dbTable, parentId, parentName); if (value2 != null && value2 != "OneToMany" && value2 != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ { agentMap.put(element.getName(), value2); } else if (value2 == "ManyToMany") //$NON-NLS-1$ { Set<Object> parentSet = new HashSet<Object>(); Object parentObject = genericDBObject2(parentName, parentId); parentSet.add(parentObject); agentMap.put(element.getName(), parentSet); } else if (value2 == "OneToMany") //$NON-NLS-1$ { // RECURSE // get assoicated ids // TODO shouldl not assume things are in order // List temp_collection_ids = // element.selectNodes("//"+dbTable+"["+id+"]/"+element.getName()+"/*");//+upperElement); List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$ + primaryKey + " = \"" + id + "\"]/" + element.getName() //$NON-NLS-1$ //$NON-NLS-2$ + "/*"); //$NON-NLS-1$ // get collection info and still dont add it if (!temp_collection_ids.isEmpty()) { // get child dbName String childDbName = getDbName(temp_collection_ids); newCollectionNames.addElement(childDbName); for (int index = 0; index < temp_collection_ids.size(); index++) { newCollectionIds.addElement(temp_collection_ids.get(index)); } } } else { // if it is an id, just ignore. otherwise print out error if (!element.getName().equals(lowerdbTable + "Id")) //$NON-NLS-1$ { log.debug("did not add " + element.getName() //$NON-NLS-1$ + " to the element " + dbTable); //$NON-NLS-1$ } } } while (iter.hasNext()); // add to the set BeanUtils.populate(agent, agentMap); this.session.saveOrUpdate(agent); // if there was a collection, then recurse if (!newCollectionIds.isEmpty()) { long newParentId = new Long(session.getIdentifier(agent).toString()).longValue(); sequentialXMLImportRecursion(newCollectionNames, newCollectionIds, dbTable, newParentId); } } else {// stop the loop k = collectionIds.size(); } } } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); // the last par tof the string conatins the class // if(err.startsWith("org.hibernate.PropertyValueException")){ try { // try again // flush // do reference work // importTable("ReferenceWork"); // the import aagain } catch (Exception ex1) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex1); ex1.printStackTrace(); } // }else{ ex.printStackTrace(); // } } }
From source file:org.sakaiproject.calendar.tool.CalendarAction.java
/** * Build the context for showing list view *//* w w w.j a v a 2s .c o m*/ protected void buildListContext(VelocityPortlet portlet, Context context, RunData runData, CalendarActionState state) { // to get the content Type Image Service context.put("contentTypeImageService", ContentTypeImageService.getInstance()); context.put("tlang", rb); context.put("config", configProps); MyMonth monthObj2 = null; MyDate dateObj1 = new MyDate(); CalendarEventVector calendarEventVectorObj = null; boolean allowed = false; LinkedHashMap yearMap = new LinkedHashMap(); // Initialize month format object if (monthFormat == null) { monthFormat = NumberFormat.getInstance(new ResourceLoader().getLocale()); monthFormat.setMinimumIntegerDigits(2); } String peid = ((JetspeedRunData) runData).getJs_peid(); SessionState sstate = ((JetspeedRunData) runData).getPortletSessionState(peid); Time m_time = TimeService.newTime(); TimeBreakdown b = m_time.breakdownLocal(); int stateYear = b.getYear(); int stateMonth = b.getMonth(); int stateDay = b.getDay(); if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null) && (sstate.getAttribute(STATE_DAY) != null)) { stateYear = ((Integer) sstate.getAttribute(STATE_YEAR)).intValue(); stateMonth = ((Integer) sstate.getAttribute(STATE_MONTH)).intValue(); stateDay = ((Integer) sstate.getAttribute(STATE_DAY)).intValue(); } // Set up list filtering information in the context. context.put(TIME_FILTER_OPTION_VAR, state.getCalendarFilter().getListViewFilterMode()); // // Fill in the custom dates // String sDate; // starting date String eDate; // ending date java.util.Calendar userCal = java.util.Calendar.getInstance(); context.put("ddStartYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) - 3)); context.put("ddEndYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) + 4)); String sM; String eM; String sD; String eD; String sY; String eY; if (state.getCalendarFilter().isCustomListViewDates()) { sDate = state.getCalendarFilter().getStartingListViewDateString(); eDate = state.getCalendarFilter().getEndingListViewDateString(); sM = sDate.substring(0, 2); eM = eDate.substring(0, 2); sD = sDate.substring(3, 5); eD = eDate.substring(3, 5); sY = "20" + sDate.substring(6); eY = "20" + eDate.substring(6); } else { //default to current week CalendarUtil calObj = new CalendarUtil(); calObj.setDay(stateYear, stateMonth, stateDay); TimeRange weekRange = getWeekTimeRange(calObj); sD = String.valueOf(weekRange.firstTime().breakdownLocal().getDay()); sY = String.valueOf(weekRange.firstTime().breakdownLocal().getYear()); sM = monthFormat.format(weekRange.firstTime().breakdownLocal().getMonth()); eD = String.valueOf(weekRange.lastTime().breakdownLocal().getDay()); eY = String.valueOf(weekRange.lastTime().breakdownLocal().getYear()); eM = monthFormat.format(weekRange.lastTime().breakdownLocal().getMonth()); } context.put(TIME_FILTER_SETTING_CUSTOM_START_YEAR, Integer.valueOf(sY)); context.put(TIME_FILTER_SETTING_CUSTOM_END_YEAR, Integer.valueOf(eY)); context.put(TIME_FILTER_SETTING_CUSTOM_START_MONTH, Integer.valueOf(sM)); context.put(TIME_FILTER_SETTING_CUSTOM_END_MONTH, Integer.valueOf(eM)); context.put(TIME_FILTER_SETTING_CUSTOM_START_DAY, Integer.valueOf(sD)); context.put(TIME_FILTER_SETTING_CUSTOM_END_DAY, Integer.valueOf(eD)); CalendarUtil calObj = new CalendarUtil(); calObj.setDay(stateYear, stateMonth, stateDay); dateObj1.setTodayDate(calObj.getMonthInteger(), calObj.getDayOfMonth(), calObj.getYear()); // fill this month object with all days avilable for this month if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference()) == false) { allowed = false; context.put(ALERT_MSG_KEY, rb.getString("java.alert.younotallow")); calendarEventVectorObj = new CalendarEventVector(); } else { try { allowed = CalendarService.getCalendar(state.getPrimaryCalendarReference()).allowAddEvent(); } catch (IdUnusedException e) { context.put(ALERT_MSG_KEY, rb.getString("java.alert.therenoactv")); M_log.debug(".buildMonthContext(): " + e); } catch (PermissionException e) { context.put(ALERT_MSG_KEY, rb.getString("java.alert.younotperm")); M_log.debug(".buildMonthContext(): " + e); } } int yearInt, monthInt, dayInt = 1; TimeRange fullTimeRange = TimeService.newTimeRange( TimeService.newTimeLocal(CalendarFilter.LIST_VIEW_STARTING_YEAR, 1, 1, 0, 0, 0, 0), TimeService.newTimeLocal(CalendarFilter.LIST_VIEW_ENDING_YEAR, 12, 31, 23, 59, 59, 999)); // We need to get events from all calendars for the full time range. CalendarEventVector masterEventVectorObj = CalendarService.getEvents( getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(), isOnWorkspaceTab()), fullTimeRange); // groups awareness - filtering String calId = state.getPrimaryCalendarReference(); String scheduleTo = (String) sstate.getAttribute(STATE_SCHEDULE_TO); try { Calendar calendarObj = CalendarService.getCalendar(calId); context.put("cal", calendarObj); if (scheduleTo != null && scheduleTo.length() != 0) { context.put("scheduleTo", scheduleTo); } else { if (calendarObj.allowGetEvents()) { // default to make site selection context.put("scheduleTo", "site"); } else if (calendarObj.getGroupsAllowGetEvent().size() > 0) { // to group otherwise context.put("scheduleTo", "groups"); } } Collection groups = calendarObj.getGroupsAllowGetEvent(); if (groups.size() > 0) { context.put("groups", groups); } List schToGroups = (List) (sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS)); context.put("scheduleToGroups", schToGroups); CalendarEventVector newEventVectorObj = new CalendarEventVector(); newEventVectorObj.addAll(masterEventVectorObj); for (Iterator i = masterEventVectorObj.iterator(); i.hasNext();) { CalendarEvent e = (CalendarEvent) (i.next()); String origSiteId = (CalendarService.getCalendar(e.getCalendarReference())).getContext(); if (!origSiteId.equals(ToolManager.getCurrentPlacement().getContext())) { context.put("fromColExist", Boolean.TRUE); } if ((schToGroups != null) && (schToGroups.size() > 0)) { boolean eventInGroup = false; for (Iterator j = schToGroups.iterator(); j.hasNext();) { String groupRangeForDisplay = e.getGroupRangeForDisplay(calendarObj); String groupId = j.next().toString(); Site site = SiteService.getSite(calendarObj.getContext()); Group group = site.getGroup(groupId); if (groupRangeForDisplay.equals("") || groupRangeForDisplay.equals("site")) eventInGroup = true; if (groupRangeForDisplay.indexOf(group.getTitle()) != -1) eventInGroup = true; } if (!eventInGroup) newEventVectorObj.remove(e); } } if ((schToGroups != null) && (schToGroups.size() > 0)) { masterEventVectorObj.clear(); masterEventVectorObj.addAll(newEventVectorObj); } } catch (IdUnusedException e) { M_log.debug(".buildListContext(): " + e); } catch (PermissionException e) { M_log.debug(".buildListContext(): " + e); } boolean dateDsc = sstate.getAttribute(STATE_DATE_SORT_DSC) != null; context.put("currentDateSortAsc", Boolean.valueOf(!dateDsc)); if (!dateDsc) { for (yearInt = CalendarFilter.LIST_VIEW_STARTING_YEAR; yearInt <= CalendarFilter.LIST_VIEW_ENDING_YEAR; yearInt++) { Vector arrayOfMonths = new Vector(20); for (monthInt = 1; monthInt < 13; monthInt++) { CalendarUtil AcalObj = new CalendarUtil(); monthObj2 = new MyMonth(); AcalObj.setDay(yearInt, monthInt, dayInt); dateObj1.setTodayDate(AcalObj.getMonthInteger(), AcalObj.getDayOfMonth(), AcalObj.getYear()); // Get the events for the particular month from the // master list of events. calendarEventVectorObj = new CalendarEventVector(state.getCalendarFilter().filterEvents( masterEventVectorObj.getEvents(getMonthTimeRange((CalendarUtil) AcalObj)))); if (!calendarEventVectorObj.isEmpty()) { AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay()); monthObj2 = calMonth(monthInt, (CalendarUtil) AcalObj, state, calendarEventVectorObj); AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay()); if (!calendarEventVectorObj.isEmpty()) arrayOfMonths.addElement(monthObj2); } } if (!arrayOfMonths.isEmpty()) yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator()); } } else { for (yearInt = CalendarFilter.LIST_VIEW_ENDING_YEAR; yearInt >= CalendarFilter.LIST_VIEW_STARTING_YEAR; yearInt--) { Vector arrayOfMonths = new Vector(20); for (monthInt = 12; monthInt >= 1; monthInt--) { CalendarUtil AcalObj = new CalendarUtil(); monthObj2 = new MyMonth(); AcalObj.setDay(yearInt, monthInt, dayInt); dateObj1.setTodayDate(AcalObj.getMonthInteger(), AcalObj.getDayOfMonth(), AcalObj.getYear()); // Get the events for the particular month from the // master list of events. calendarEventVectorObj = new CalendarEventVector(state.getCalendarFilter().filterEvents( masterEventVectorObj.getEvents(getMonthTimeRange((CalendarUtil) AcalObj)))); if (!calendarEventVectorObj.isEmpty()) { AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay()); monthObj2 = calMonth(monthInt, (CalendarUtil) AcalObj, state, calendarEventVectorObj); AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay()); if (!calendarEventVectorObj.isEmpty()) arrayOfMonths.addElement(monthObj2); } } if (!arrayOfMonths.isEmpty()) yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator()); } } context.put("yearMap", yearMap); int row = 5; context.put("row", Integer.valueOf(row)); calObj.setDay(stateYear, stateMonth, stateDay); // using session state stored year-month-day to replace saving calObj sstate.setAttribute(STATE_YEAR, Integer.valueOf(stateYear)); sstate.setAttribute(STATE_MONTH, Integer.valueOf(stateMonth)); sstate.setAttribute(STATE_DAY, Integer.valueOf(stateDay)); state.setState("list"); context.put("date", dateObj1); // output CalendarService and SiteService context.put("CalendarService", CalendarService.getInstance()); context.put("SiteService", SiteService.getInstance()); context.put("Context", ToolManager.getCurrentPlacement().getContext()); buildMenu(portlet, context, runData, state, CalendarPermissions.allowCreateEvents(state.getPrimaryCalendarReference(), state.getSelectedCalendarReference()), CalendarPermissions.allowDeleteEvent(state.getPrimaryCalendarReference(), state.getSelectedCalendarReference(), state.getCalendarEventId()), CalendarPermissions.allowReviseEvents(state.getPrimaryCalendarReference(), state.getSelectedCalendarReference(), state.getCalendarEventId()), CalendarPermissions.allowMergeCalendars(state.getPrimaryCalendarReference()), CalendarPermissions.allowModifyCalendarProperties(state.getPrimaryCalendarReference()), CalendarPermissions.allowImport(state.getPrimaryCalendarReference()), CalendarPermissions.allowSubscribe(state.getPrimaryCalendarReference()), CalendarPermissions.allowSubscribeThis(state.getPrimaryCalendarReference())); // added by zqian for toolbar context.put("allow_new", Boolean.valueOf(allowed)); context.put("allow_delete", Boolean.valueOf(false)); context.put("allow_revise", Boolean.valueOf(false)); context.put("realDate", TimeService.newTime()); context.put("selectedView", rb.getString("java.listeve")); context.put("tlang", rb); context.put("config", configProps); context.put("calendarFormattedText", new CalendarFormattedText()); String currentUserId = UserDirectoryService.getCurrentUser().getId(); boolean canViewEventAudience = SecurityService.unlock(currentUserId, org.sakaiproject.calendar.api.CalendarService.AUTH_VIEW_AUDIENCE, "/site/" + ToolManager.getCurrentPlacement().getContext()); context.put("canViewAudience", !canViewEventAudience); }
From source file:org.apache.hadoop.hive.metastore.MyXid.java
public static String getUrlForRead(String url) { JDBCUrl jdbcUrl = new JDBCUrl(url); Vector<String> slaveurls = masterToSlave.get(jdbcUrl.getHost()); if (slaveurls == null || slaveurls.isEmpty()) { return url; }/* www. j a v a 2 s .c o m*/ Random r = new Random(); int index = r.nextInt(100000000) % slaveurls.size(); return "jdbc:" + jdbcUrl.getDriver() + "://" + slaveurls.get(index) + ":" + jdbcUrl.getPort() + "/" + jdbcUrl.getDB(); }
From source file:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java
/** * Test function in order to debug resource discovery even when uberdust is not accessible * @param givGatewayInfo/*w ww. ja v a 2 s. co m*/ * @return */ private CGatewayWithSmartDevices DEBUG_offline_createWSIDescr(CGateway 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>>(); 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; try { // String[] nodeUrnsInUberdust = responseBodyFromHttpNodesGetStr.split("\\r?\\n"); int totalNodeUrnsInUberdust = nodeUrnsInUberdust.length; String[] nodeAndLastCapReadingsUrnsInUberdust = responseBodyFromHttpNodes_STATUS_Get.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) logger.debug("Total nodes:" + String.valueOf(totalNodeUrnsInUberdust)); for (String aNodeUrnsInUberdust : nodeUrnsInUberdust) { if (allFaultyNodesUrns.contains(aNodeUrnsInUberdust)) { logger.debug("Skiipping node: " + aNodeUrnsInUberdust); continue; //skip faulty nodes! } logger.debug("Discovering resources of node: " + aNodeUrnsInUberdust); 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) //we are at the capabilities of the current smartdevice { logger.debug(" node id: " + nodeCapAndReadingRowItems[0]); logger.debug(" capability: " + nodeCapAndReadingRowItems[1] != null ? nodeCapAndReadingRowItems[1] : ""); logger.debug( " timestamp: " + nodeCapAndReadingRowItems[2] != null ? nodeCapAndReadingRowItems[2] : ""); logger.debug(" measurement: " + nodeCapAndReadingRowItems[3] != null ? nodeCapAndReadingRowItems[3] : ""); // [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()); //logger.debug("HER HE R HER : Adding id: "+ Integer.toString(thedigestInt)+ " for cap: " + tmpGenericCapabilityForSensor); //Integer thedigestIntAlt = (tmpGenericCapabilityForSensor).hashCode(); //if (thedigestIntAlt < 0) thedigestIntAlt = thedigestIntAlt * (-1); //logger.debug("HER HE R HER : WHEREAS EXPERIMENT id: "+ Integer.toString(thedigestIntAlt)+ " for cap: " + tmpGenericCapabilityForSensor); // } 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! } catch (Exception ex) { logger.error(ex.getMessage()); } 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); }//from w w w. j a va 2s . 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:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java
/** * TODO: IMPORTANT !!!//from w w w .j a v a 2 s .c o 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
/** * 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) */// www . ja 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:org.hyperledger.fabric.sdkintegration.End2endIT.java
void runChannel(HFClient client, Channel channel, boolean installChaincode, SampleOrg sampleOrg, int delta) { class ChaincodeEventCapture { //A test class to capture chaincode events final String handle; final BlockEvent blockEvent; final ChaincodeEvent chaincodeEvent; ChaincodeEventCapture(String handle, BlockEvent blockEvent, ChaincodeEvent chaincodeEvent) { this.handle = handle; this.blockEvent = blockEvent; this.chaincodeEvent = chaincodeEvent; }//from ww w.j a v a2 s. c om } // The following is just a test to see if peers and orderers can be added and removed. // not pertinent to the code flow. testRemovingAddingPeersOrderers(client, channel); Vector<ChaincodeEventCapture> chaincodeEvents = new Vector<>(); // Test list to capture chaincode events. try { final String channelName = channel.getName(); boolean isFooChain = FOO_CHANNEL_NAME.equals(channelName); out("Running channel %s", channelName); Collection<Orderer> orderers = channel.getOrderers(); final ChaincodeID chaincodeID; Collection<ProposalResponse> responses; Collection<ProposalResponse> successful = new LinkedList<>(); Collection<ProposalResponse> failed = new LinkedList<>(); // Register a chaincode event listener that will trigger for any chaincode id and only for EXPECTED_EVENT_NAME event. String chaincodeEventListenerHandle = channel.registerChaincodeEventListener(Pattern.compile(".*"), Pattern.compile(Pattern.quote(EXPECTED_EVENT_NAME)), (handle, blockEvent, chaincodeEvent) -> { chaincodeEvents.add(new ChaincodeEventCapture(handle, blockEvent, chaincodeEvent)); String es = blockEvent.getPeer() != null ? blockEvent.getPeer().getName() : blockEvent.getEventHub().getName(); out("RECEIVED Chaincode event with handle: %s, chaincode Id: %s, chaincode event name: %s, " + "transaction id: %s, event payload: \"%s\", from eventhub: %s", handle, chaincodeEvent.getChaincodeId(), chaincodeEvent.getEventName(), chaincodeEvent.getTxId(), new String(chaincodeEvent.getPayload()), es); }); //For non foo channel unregister event listener to test events are not called. if (!isFooChain) { channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle); chaincodeEventListenerHandle = null; } ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME) .setVersion(CHAIN_CODE_VERSION); if (null != CHAIN_CODE_PATH) { chaincodeIDBuilder.setPath(CHAIN_CODE_PATH); } chaincodeID = chaincodeIDBuilder.build(); if (installChaincode) { //////////////////////////// // Install Proposal Request // client.setUserContext(sampleOrg.getPeerAdmin()); out("Creating install proposal"); InstallProposalRequest installProposalRequest = client.newInstallProposalRequest(); installProposalRequest.setChaincodeID(chaincodeID); if (isFooChain) { // on foo chain install from directory. ////For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH installProposalRequest.setChaincodeSourceLocation( Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile()); if (testConfig.isFabricVersionAtOrAfter("1.1")) { // Fabric 1.1 added support for META-INF in the chaincode image. //This sets an index on the variable a in the chaincode // see http://hyperledger-fabric.readthedocs.io/en/master/couchdb_as_state_database.html#using-couchdb-from-chaincode // The file IndexA.json as part of the META-INF will be packaged with the source to create the index. installProposalRequest .setChaincodeMetaInfLocation(new File("src/test/fixture/meta-infs/end2endit")); } } else { // On bar chain install from an input stream. // For inputstream if indicies are desired the application needs to make sure the META-INF is provided in the stream. // The SDK does not change anything in the stream. if (CHAIN_CODE_LANG.equals(Type.GO_LANG)) { installProposalRequest .setChaincodeInputStream( Util.generateTarGzInputStream( (Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH, "src", CHAIN_CODE_PATH).toFile()), Paths.get("src", CHAIN_CODE_PATH).toString())); } else { installProposalRequest.setChaincodeInputStream(Util.generateTarGzInputStream( (Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile()), "src")); } } installProposalRequest.setChaincodeVersion(CHAIN_CODE_VERSION); installProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG); out("Sending install proposal"); //////////////////////////// // only a client from the same org as the peer can issue an install request int numInstallProposal = 0; // Set<String> orgs = orgPeers.keySet(); // for (SampleOrg org : testSampleOrgs) { Collection<Peer> peers = channel.getPeers(); numInstallProposal = numInstallProposal + peers.size(); responses = client.sendInstallProposal(installProposalRequest, peers); for (ProposalResponse response : responses) { if (response.getStatus() == ProposalResponse.Status.SUCCESS) { out("Successful install proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName()); successful.add(response); } else { failed.add(response); } } // } out("Received %d install proposal responses. Successful+verified: %d . Failed: %d", numInstallProposal, successful.size(), failed.size()); if (failed.size() > 0) { ProposalResponse first = failed.iterator().next(); fail("Not enough endorsers for install :" + successful.size() + ". " + first.getMessage()); } } // client.setUserContext(sampleOrg.getUser(TEST_ADMIN_NAME)); // final ChaincodeID chaincodeID = firstInstallProposalResponse.getChaincodeID(); // Note installing chaincode does not require transaction no need to // send to Orderers /////////////// //// Instantiate chaincode. InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest(); instantiateProposalRequest.setProposalWaitTime(DEPLOYWAITTIME); instantiateProposalRequest.setChaincodeID(chaincodeID); instantiateProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG); instantiateProposalRequest.setFcn("init"); instantiateProposalRequest.setArgs(new String[] { "a", "500", "b", "" + (200 + delta) }); Map<String, byte[]> tm = new HashMap<>(); tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8)); tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8)); instantiateProposalRequest.setTransientMap(tm); /* policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in either Org1 or Org2 See README.md Chaincode endorsement policies section for more details. */ ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy(); chaincodeEndorsementPolicy .fromYamlFile(new File(TEST_FIXTURES_PATH + "/sdkintegration/chaincodeendorsementpolicy.yaml")); instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy); out("Sending instantiateProposalRequest to all peers with arguments: a and b set to 100 and %s respectively", "" + (200 + delta)); successful.clear(); failed.clear(); if (isFooChain) { //Send responses both ways with specifying peers and by using those on the channel. responses = channel.sendInstantiationProposal(instantiateProposalRequest, channel.getPeers()); } else { responses = channel.sendInstantiationProposal(instantiateProposalRequest); } for (ProposalResponse response : responses) { if (response.isVerified() && response.getStatus() == ProposalResponse.Status.SUCCESS) { successful.add(response); out("Succesful instantiate proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName()); } else { failed.add(response); } } out("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d", responses.size(), successful.size(), failed.size()); if (failed.size() > 0) { for (ProposalResponse fail : failed) { out("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + fail.getMessage() + ", on peer" + fail.getPeer()); } ProposalResponse first = failed.iterator().next(); fail("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + first.getMessage() + ". Was verified:" + first.isVerified()); } /////////////// /// Send instantiate transaction to orderer out("Sending instantiateTransaction to orderer with a and b set to 100 and %s respectively", "" + (200 + delta)); //Specify what events should complete the interest in this transaction. This is the default // for all to complete. It's possible to specify many different combinations like //any from a group, all from one group and just one from another or even None(NOfEvents.createNoEvents). // See. Channel.NOfEvents Channel.NOfEvents nOfEvents = createNofEvents(); if (!channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).isEmpty()) { nOfEvents.addPeers(channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE))); } if (!channel.getEventHubs().isEmpty()) { nOfEvents.addEventHubs(channel.getEventHubs()); } channel.sendTransaction(successful, createTransactionOptions() //Basically the default options but shows it's usage. .userContext(client.getUserContext()) //could be a different user context. this is the default. .shuffleOrders(false) // don't shuffle any orderers the default is true. .orderers(channel.getOrderers()) // specify the orderers we want to try this transaction. Fails once all Orderers are tried. .nOfEvents(nOfEvents) // The events to signal the completion of the interest in the transaction ).thenApply(transactionEvent -> { waitOnFabric(0); assertTrue(transactionEvent.isValid()); // must be valid to be here. assertNotNull(transactionEvent.getSignature()); //musth have a signature. BlockEvent blockEvent = transactionEvent.getBlockEvent(); // This is the blockevent that has this transaction. assertNotNull(blockEvent.getBlock()); // Make sure the RAW Fabric block is returned. out("Finished instantiate transaction with transaction id %s", transactionEvent.getTransactionID()); try { assertEquals(blockEvent.getChannelId(), channel.getName()); successful.clear(); failed.clear(); client.setUserContext(sampleOrg.getUser(testUser1)); /////////////// /// Send transaction proposal to all peers TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest(); transactionProposalRequest.setChaincodeID(chaincodeID); transactionProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG); //transactionProposalRequest.setFcn("invoke"); transactionProposalRequest.setFcn("move"); transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime()); transactionProposalRequest.setArgs("a", "b", "100"); Map<String, byte[]> tm2 = new HashMap<>(); tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8)); //Just some extra junk in transient map tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8)); // ditto tm2.put("result", ":)".getBytes(UTF_8)); // This should be returned in the payload see chaincode why. if (Type.GO_LANG.equals(CHAIN_CODE_LANG) && testConfig.isFabricVersionAtOrAfter("1.2")) { expectedMoveRCMap.put(channelName, random.nextInt(300) + 100L); // the chaincode will return this as status see chaincode why. tm2.put("rc", (expectedMoveRCMap.get(channelName) + "").getBytes(UTF_8)); // This should be returned see chaincode why. // 400 and above results in the peer not endorsing! } else { expectedMoveRCMap.put(channelName, 200L); // not really supported for Java or Node. } tm2.put(EXPECTED_EVENT_NAME, EXPECTED_EVENT_DATA); //This should trigger an event see chaincode why. transactionProposalRequest.setTransientMap(tm2); out("sending transactionProposal to all peers with arguments: move(a,b,100)"); // Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposalToEndorsers(transactionProposalRequest); Collection<ProposalResponse> transactionPropResp = channel .sendTransactionProposal(transactionProposalRequest, channel.getPeers()); for (ProposalResponse response : transactionPropResp) { if (response.getStatus() == ProposalResponse.Status.SUCCESS) { out("Successful transaction proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName()); successful.add(response); } else { failed.add(response); } } out("Received %d transaction proposal responses. Successful+verified: %d . Failed: %d", transactionPropResp.size(), successful.size(), failed.size()); if (failed.size() > 0) { ProposalResponse firstTransactionProposalResponse = failed.iterator().next(); fail("Not enough endorsers for invoke(move a,b,100):" + failed.size() + " endorser error: " + firstTransactionProposalResponse.getMessage() + ". Was verified: " + firstTransactionProposalResponse.isVerified()); } // Check that all the proposals are consistent with each other. We should have only one set // where all the proposals above are consistent. Note the when sending to Orderer this is done automatically. // Shown here as an example that applications can invoke and select. // See org.hyperledger.fabric.sdk.proposal.consistency_validation config property. Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils .getProposalConsistencySets(transactionPropResp); if (proposalConsistencySets.size() != 1) { fail(format("Expected only one set of consistent proposal responses but got %d", proposalConsistencySets.size())); } out("Successfully received transaction proposal responses."); // System.exit(10); ProposalResponse resp = successful.iterator().next(); byte[] x = resp.getChaincodeActionResponsePayload(); // This is the data returned by the chaincode. String resultAsString = null; if (x != null) { resultAsString = new String(x, UTF_8); } assertEquals(":)", resultAsString); assertEquals(expectedMoveRCMap.get(channelName).longValue(), resp.getChaincodeActionResponseStatus()); //Chaincode's status. TxReadWriteSetInfo readWriteSetInfo = resp.getChaincodeActionResponseReadWriteSetInfo(); //See blockwalker below how to transverse this assertNotNull(readWriteSetInfo); assertTrue(readWriteSetInfo.getNsRwsetCount() > 0); ChaincodeID cid = resp.getChaincodeID(); assertNotNull(cid); final String path = cid.getPath(); if (null == CHAIN_CODE_PATH) { assertTrue(path == null || "".equals(path)); } else { assertEquals(CHAIN_CODE_PATH, path); } assertEquals(CHAIN_CODE_NAME, cid.getName()); assertEquals(CHAIN_CODE_VERSION, cid.getVersion()); //////////////////////////// // Send Transaction Transaction to orderer out("Sending chaincode transaction(move a,b,100) to orderer."); return channel.sendTransaction(successful).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS); } catch (Exception e) { out("Caught an exception while invoking chaincode"); e.printStackTrace(); fail("Failed invoking chaincode with error : " + e.getMessage()); } return null; }).thenApply(transactionEvent -> { try { waitOnFabric(0); assertTrue(transactionEvent.isValid()); // must be valid to be here. out("Finished transaction with transaction id %s", transactionEvent.getTransactionID()); testTxID = transactionEvent.getTransactionID(); // used in the channel queries later //////////////////////////// // Send Query Proposal to all peers // String expect = "" + (300 + delta); out("Now query chaincode for the value of b."); QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest(); queryByChaincodeRequest.setArgs(new String[] { "b" }); queryByChaincodeRequest.setFcn("query"); queryByChaincodeRequest.setChaincodeID(chaincodeID); Map<String, byte[]> tm2 = new HashMap<>(); tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8)); tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8)); queryByChaincodeRequest.setTransientMap(tm2); Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers()); for (ProposalResponse proposalResponse : queryProposals) { if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) { fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: " + proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified()); } else { String payload = proposalResponse.getProposalResponse().getResponse().getPayload() .toStringUtf8(); out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload); assertEquals(payload, expect); } } return null; } catch (Exception e) { out("Caught exception while running query"); e.printStackTrace(); fail("Failed during chaincode query with error : " + e.getMessage()); } return null; }).exceptionally(e -> { if (e instanceof TransactionEventException) { BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent(); if (te != null) { throw new AssertionError(format("Transaction with txid %s failed. %s", te.getTransactionID(), e.getMessage()), e); } } throw new AssertionError( format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()), e); }).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS); // Channel queries // We can only send channel queries to peers that are in the same org as the SDK user context // Get the peers from the current org being used and pick one randomly to send the queries to. // Set<Peer> peerSet = sampleOrg.getPeers(); // Peer queryPeer = peerSet.iterator().next(); // out("Using peer %s for channel queries", queryPeer.getName()); BlockchainInfo channelInfo = channel.queryBlockchainInfo(); out("Channel info for : " + channelName); out("Channel height: " + channelInfo.getHeight()); String chainCurrentHash = Hex.encodeHexString(channelInfo.getCurrentBlockHash()); String chainPreviousHash = Hex.encodeHexString(channelInfo.getPreviousBlockHash()); out("Chain current block hash: " + chainCurrentHash); out("Chainl previous block hash: " + chainPreviousHash); // Query by block number. Should return latest block, i.e. block number 2 BlockInfo returnedBlock = channel.queryBlockByNumber(channelInfo.getHeight() - 1); String previousHash = Hex.encodeHexString(returnedBlock.getPreviousHash()); out("queryBlockByNumber returned correct block with blockNumber " + returnedBlock.getBlockNumber() + " \n previous_hash " + previousHash); assertEquals(channelInfo.getHeight() - 1, returnedBlock.getBlockNumber()); assertEquals(chainPreviousHash, previousHash); // Query by block hash. Using latest block's previous hash so should return block number 1 byte[] hashQuery = returnedBlock.getPreviousHash(); returnedBlock = channel.queryBlockByHash(hashQuery); out("queryBlockByHash returned block with blockNumber " + returnedBlock.getBlockNumber()); assertEquals(channelInfo.getHeight() - 2, returnedBlock.getBlockNumber()); // Query block by TxID. Since it's the last TxID, should be block 2 returnedBlock = channel.queryBlockByTransactionID(testTxID); out("queryBlockByTxID returned block with blockNumber " + returnedBlock.getBlockNumber()); assertEquals(channelInfo.getHeight() - 1, returnedBlock.getBlockNumber()); // query transaction by ID TransactionInfo txInfo = channel.queryTransactionByID(testTxID); out("QueryTransactionByID returned TransactionInfo: txID " + txInfo.getTransactionID() + "\n validation code " + txInfo.getValidationCode().getNumber()); if (chaincodeEventListenerHandle != null) { channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle); //Should be two. One event in chaincode and two notification for each of the two event hubs final int numberEventsExpected = channel.getEventHubs().size() + channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).size(); //just make sure we get the notifications. for (int i = 15; i > 0; --i) { if (chaincodeEvents.size() == numberEventsExpected) { break; } else { Thread.sleep(90); // wait for the events. } } assertEquals(numberEventsExpected, chaincodeEvents.size()); for (ChaincodeEventCapture chaincodeEventCapture : chaincodeEvents) { assertEquals(chaincodeEventListenerHandle, chaincodeEventCapture.handle); assertEquals(testTxID, chaincodeEventCapture.chaincodeEvent.getTxId()); assertEquals(EXPECTED_EVENT_NAME, chaincodeEventCapture.chaincodeEvent.getEventName()); assertTrue( Arrays.equals(EXPECTED_EVENT_DATA, chaincodeEventCapture.chaincodeEvent.getPayload())); assertEquals(CHAIN_CODE_NAME, chaincodeEventCapture.chaincodeEvent.getChaincodeId()); BlockEvent blockEvent = chaincodeEventCapture.blockEvent; assertEquals(channelName, blockEvent.getChannelId()); // assertTrue(channel.getEventHubs().contains(blockEvent.getEventHub())); } } else { assertTrue(chaincodeEvents.isEmpty()); } out("Running for Channel %s done", channelName); } catch (Exception e) { out("Caught an exception running channel %s", channel.getName()); e.printStackTrace(); fail("Test failed with error : " + e.getMessage()); } }