List of usage examples for java.util Vector addElement
public synchronized void addElement(E obj)
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
@SuppressWarnings("unchecked") protected Object buildSingleDataBaseObjectFromXML(Element dbImport, String dbTable, String parentName, long parentId, int id, boolean recursion) { Object dbObject = new Object(); try {//from w w w .j a v a2 s. co m DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); //String lowerdbTable = lowerFirstChar(dbTable); String primaryKey = parentInfo.getPrimaryKeyName(); Vector collectionIds = new Vector(20); Vector collectionNames = new Vector(20); // make the agent and the element Object agent = parentInfo.getClassObj().newInstance(); Map<String, Object> agentMap = new HashMap<String, Object>(); Element dbElement = dbImport; Iterator i = dbElement.elementIterator(); do {// do for each element in the record Element element = (Element) i.next(); // Object value = findTypeSequential(element, dbTable, parentId, parentName );//the // parent is itself, just a dummy variable Object value = findTypeDataBaseParent(element, dbTable, parentId, parentName);// the // parent // is // itself, // just // a // dummy // variable if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ { agentMap.put(element.getName(), value); } // ignore many-to-many for now else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ {// RECURSE if (recursion) { // get assoicated ids List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$ + primaryKey + " = \"" + id + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // get collection info and still dont add it if (!temp_collection_ids.isEmpty()) { // get child dbName String childDbName = getDbName(temp_collection_ids); collectionNames.addElement(childDbName); for (int index = 0; index < temp_collection_ids.size(); index++) { collectionIds.addElement(temp_collection_ids.get(index)); } } } } else // else, dont add it { // if it is an id, just ignore. otherwise print out error if (!element.getName().equals(primaryKey)) { log.debug("did not add " + element.getName() + " to the element " //$NON-NLS-1$ //$NON-NLS-2$ + dbTable); } } } while (i.hasNext()); // populate BeanUtils.populate(agent, agentMap); // save it then gets its id (assigned by Hibernate) this.session.save(agent); // if there was a collection, then recurse if (!collectionIds.isEmpty()) { long newParentId = new Long(session.getIdentifier(agent).toString()).longValue(); sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId); } dbObject = agent; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } return dbObject; }
From source file:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java
private Vector<String> getFaultyNodes() { if (DEBUG_OFFLINE_MODE) { return DEBUG_offline_getFaultyNodes(); }//from w w w .jav a 2 s. c o m Vector<String> retVec = new Vector<String>(); // direct for test http://uberdust.cti.gr/rest/sendCommand/destination/urn:wisebed:ctitestbed:0x42f/payload/7f,69,70,1,$1,1 HttpClient httpClient = new DefaultHttpClient(); try { //logger.debug("Accessing Admin Status for faulty nodes: http://uberdust.cti.gr/rest/testbed/1/adminstatus"); HttpGet httpUberdustFaultyNodesGet = new HttpGet("http://uberdust.cti.gr/rest/testbed/1/adminstatus"); HttpResponse httpUberdustFaultyNodesGet_Response = httpClient.execute(httpUberdustFaultyNodesGet); int httpUberdustFaultyNodesGetResponse_StatusCode = httpUberdustFaultyNodesGet_Response.getStatusLine() .getStatusCode(); HttpEntity httpUberdustFaultyNodesGetResponse_ResponseEntity = httpUberdustFaultyNodesGet_Response .getEntity(); if (httpUberdustFaultyNodesGetResponse_ResponseEntity != null) { String responseBodyStr = EntityUtils.toString(httpUberdustFaultyNodesGetResponse_ResponseEntity); if (httpUberdustFaultyNodesGetResponse_StatusCode != 200) { // responseBody will have the error response logger.debug("--------ERROR Response: " + httpUberdustFaultyNodesGetResponse_StatusCode + "------------------------------"); logger.debug(responseBodyStr); logger.debug("----------------------------------------"); } else { String[] faultyNodeUrnsLinesInUberdust = responseBodyStr.split("\\r?\\n"); int totalfaultyNodeUrnsLinesInUberdust = faultyNodeUrnsLinesInUberdust.length; for (String afaultyNodeUrnLineInUberdust : faultyNodeUrnsLinesInUberdust) { String[] afaultyNodeUrnTokens = afaultyNodeUrnLineInUberdust.split("\\t"); // [0] has the urn if (afaultyNodeUrnTokens != null && afaultyNodeUrnTokens.length > 0 && !afaultyNodeUrnTokens[0].isEmpty()) { retVec.addElement(afaultyNodeUrnTokens[0]); // logger.debug("Adding faulty node:: "+afaultyNodeUrnTokens[0]); } } } } } catch (Exception e) { logger.debug(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(); } return retVec; }
From source file:org.apache.webdav.lib.WebdavResource.java
/** * Execute OPTIONS method for the given http URL. * * @param httpURL the http URL.//from w w w. j a v a2 s . co m * @return the allowed methods and capabilities. * @exception HttpException * @exception IOException */ public Enumeration optionsMethod(HttpURL httpURL) throws HttpException, IOException { HttpClient client = getSessionInstance(httpURL, true); OptionsMethod method = new OptionsMethod(httpURL.getEscapedPath()); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); generateAdditionalHeaders(method); client.executeMethod(method); Vector options = new Vector(); int statusCode = method.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { // check if the specific method is possbile Enumeration allowedMethods = method.getAllowedMethods(); while (allowedMethods.hasMoreElements()) { options.addElement(allowedMethods.nextElement()); } // check WebDAV capabilities. Enumeration davCapabilities = method.getDavCapabilities(); while (davCapabilities.hasMoreElements()) { options.addElement(davCapabilities.nextElement()); } Enumeration responses = method.getResponses(); if (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); Enumeration workspaces = response.getWorkspaces(); String sResult = ""; while (workspaces.hasMoreElements()) { sResult += workspaces.nextElement().toString(); } Enumeration histories = response.getHistories(); while (histories.hasMoreElements()) { sResult += histories.nextElement().toString(); } // Set status code for this resource. if ((thisResource == true) && (response.getStatusCode() > 0)) setStatusCode(response.getStatusCode()); thisResource = false; options.addElement(sResult); } } return options.elements(); }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
@SuppressWarnings("unchecked") protected void sequentialXMLImportRecordSet(Element dbImport, String dbTable, String parentName, long parentId) { try {/*ww w .j a va 2 s .c o m*/ String id = new String(); DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); // get the records List records = dbImport.selectNodes("//" + dbTable); //$NON-NLS-1$ //String lowerdbTable = lowerFirstChar(dbTable); DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); String primaryKey = info.getPrimaryKeyName(); List ids = dbImport.selectNodes("//" + primaryKey); //$NON-NLS-1$ if (records.size() < 1) { log.debug("Cannot import. Given database type:" + dbTable //$NON-NLS-1$ + " does not exsist in import file"); //$NON-NLS-1$ } else { // loop for each record for (int k = 0; k < records.size(); k++) { Vector collectionIds = new Vector(20); Vector collectionNames = new Vector(20); // keep this id to compare against it's collection Element idElement = (Element) ids.get(k); id = idElement.getStringValue(); // make the agent and the element Object agent = parentInfo.getClassObj().newInstance(); Map<String, Object> agentMap = new HashMap<String, Object>(); Element dbElement = (Element) records.get(k); Iterator i = dbElement.elementIterator(); do {// do for each element in the record Element element = (Element) i.next(); Object value = findTypeRecordSet(element, dbTable, parentId, parentName);// the // parent // is // itself, // just // a // dummy // variable if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ { agentMap.put(element.getName(), value); } // ignore many-to-many for now else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ {// RECURSE // get assoicated ids List temp_collection_ids = element .selectNodes("//" + dbTable + "[" + primaryKey + " = \"" + id //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ // get collection info and still dont add it if (!temp_collection_ids.isEmpty()) { // get child dbName String childDbName = getDbName(temp_collection_ids); collectionNames.addElement(childDbName); for (int index = 0; index < temp_collection_ids.size(); index++) { collectionIds.addElement(temp_collection_ids.get(index)); } } } else // else, dont add it { // if it is an id, just ignore. otherwise print out error if (!element.getName().equals(primaryKey)) { log.debug("did not add " + element.getName() //$NON-NLS-1$ + " to the element " + dbTable); //$NON-NLS-1$ } } } while (i.hasNext()); // populate and save BeanUtils.populate(agent, agentMap); this.session.save(agent); // if there was a collection, then recurse if (!collectionIds.isEmpty()) { long newParentId = new Long(session.getIdentifier(agent).toString()).longValue(); // import all children sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId); } } } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } }
From source file:com.adito.agent.client.ProxyUtil.java
/** * Attempt to proxy settings from Internet Explorer. * //from w ww . ja v a 2s . c o m * @return internet explorer proxy settings * @throws IOException if IE settings could not be obtained for some reason */ public static BrowserProxySettings lookupIEProxySettings() throws IOException { try { Vector addresses = new Vector(); Vector proxies = new Vector(); String proxyServerValue = null; String proxyOveride = null; /* Only use jRegistry if on Windows, running 1.3 or up Java * and NOT Windows Vista with JDK6.0 (because of jvm crash) */ if (Utils.isSupportedJRE("+1.3") && Utils.isSupportedPlatform( "Windows") /*&& !(Utils.isSupportedOSVersion("+6.0") && Utils.isSupportedJRE("+1.6"))*/) { /* * We can use jRegistryKey API to lookup IE settings in the * registry */ // RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER, // "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); //$NON-NLS-1$ String proxyEnable = WinRegistry.getRegistryValue("user", "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", "0"); if (proxyEnable != null) { //$NON-NLS-1$ /* * We have ProxyEnable so check to see if we are using a * proxy */ if (proxyEnable.equals("1")) { //$NON-NLS-1$ //$NON-NLS-2$ proxyServerValue = WinRegistry.getRegistryValue("user", "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null); if (proxyServerValue != null) { //$NON-NLS-1$ /** * We have some proxy settings. The values will be * in the format "server.proxy.net:8888" or */ proxyOveride = WinRegistry.getRegistryValue("user", "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null); } } else { } } } else { if (System.getProperty("java.vendor").startsWith("Microsoft")) { //$NON-NLS-1$ //$NON-NLS-2$ try { Class clazz = Class.forName("com.ms.lang.RegKey"); //$NON-NLS-1$ int userRoot = clazz.getField("USER_ROOT").getInt(null); //$NON-NLS-1$ int keyOpenAll = clazz.getField("KEYOPEN_ALL").getInt(null); //$NON-NLS-1$ // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.lookingForRoot")); //$NON-NLS-1$ // #endif Object rootKey = clazz.getMethod("getRootKey", new Class[] { int.class }).invoke(null, //$NON-NLS-1$ new Object[] { new Integer(userRoot) }); // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.getIERegistryKey")); //$NON-NLS-1$ // #endif Object key = clazz.getConstructor(new Class[] { clazz, String.class, int.class }) .newInstance(new Object[] { rootKey, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", //$NON-NLS-1$ new Integer(keyOpenAll) }); // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.checkingIfProxyEnabled")); //$NON-NLS-1$ // #endif if (((Integer) (clazz.getMethod("getIntValue", new Class[] { String.class }).invoke(key, //$NON-NLS-1$ new Object[] { "ProxyEnable" }))).intValue() == 1) { //$NON-NLS-1$ // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.gettingProxyServerList")); //$NON-NLS-1$ // #endif proxyServerValue = (String) (clazz.getMethod("getStringValue", //$NON-NLS-1$ new Class[] { String.class, String.class }) .invoke(key, new Object[] { "ProxyServer", "" })); //$NON-NLS-1$ //$NON-NLS-2$ // #ifdef DEBUG log.info(Messages.getString("ProxyUtil.gettingProxyOverides")); //$NON-NLS-1$ // #endif proxyOveride = (String) (clazz .getMethod("getStringValue", new Class[] { String.class, String.class }) //$NON-NLS-1$ .invoke(key, new Object[] { "ProxyOverride", "" })); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (Throwable t) { t.printStackTrace(); } } else { // #ifdef DEBUG log.info(MessageFormat.format(Messages.getString("ProxyUtil.unsupportedJavaRuntime"), //$NON-NLS-1$ new Object[] { System.getProperty("java.version"), //$NON-NLS-1$ System.getProperty("java.vendor") })); //$NON-NLS-1$ // #endif } } ProxyInfo p; if (proxyServerValue != null && proxyServerValue.indexOf(';') > -1) { /** * Format is multiple * "ftp=ftp.com:4444;gopher=gopher.com:3333;http=198.162.1.119:8888;https=https.com:2222;socks=socks.com:1111" */ StringTokenizer tokens = new StringTokenizer(proxyServerValue, ";"); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { p = createProxyInfo(tokens.nextToken(), "IE Proxy Settings"); //$NON-NLS-1$ proxies.addElement(p); } } else if (proxyServerValue != null) { /** * Format is single "http=server.proxy.net:8888" or * "server.proxy.net:8888" */ p = createProxyInfo(proxyServerValue, "IE Proxy Settings"); //$NON-NLS-1$ proxies.addElement(p); } BrowserProxySettings bps = new BrowserProxySettings(); bps.setBrowser("Internet Explorer"); //$NON-NLS-1$ bps.setProxies(new ProxyInfo[proxies.size()]); proxies.copyInto(bps.getProxies()); if (proxyOveride != null) { StringTokenizer tokens = new StringTokenizer(proxyOveride, ";"); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { addresses.addElement(tokens.nextToken()); } } bps.setBypassAddr(new String[addresses.size()]); addresses.copyInto(bps.getBypassAddr()); return bps; } catch (Throwable t) { t.printStackTrace(); throw new IOException(MessageFormat.format(Messages.getString("ProxyUtil.failedToLookupIEProxies"), //$NON-NLS-1$ new Object[] { t.getMessage() })); } }
From source file:com.github.maven_nar.cpptasks.CCTask.java
protected LinkerConfiguration collectExplicitObjectFiles(final Vector<File> objectFiles, final Vector<File> sysObjectFiles, final VersionInfo versionInfo) { ///*from w w w. j a va 2 s . c om*/ // find the first eligible linker // // ProcessorConfiguration linkerConfig = null; LinkerDef selectedLinkerDef = null; Linker selectedLinker = null; final Hashtable<String, File> sysLibraries = new Hashtable<>(); final TargetDef targetPlatform = getTargetPlatform(); FileVisitor objCollector = null; FileVisitor sysLibraryCollector = null; for (int i = 0; i < this._linkers.size(); i++) { final LinkerDef currentLinkerDef = this._linkers.elementAt(i); if (currentLinkerDef.isActive()) { selectedLinkerDef = currentLinkerDef; selectedLinker = currentLinkerDef.getProcessor().getLinker(this.linkType); // // skip the linker if it doesn't know how to // produce the specified link type if (selectedLinker != null) { linkerConfig = currentLinkerDef.createConfiguration(this, this.linkType, this.linkerDef, targetPlatform, versionInfo); if (linkerConfig != null) { // // create collectors for object files // and system libraries objCollector = new ObjectFileCollector(selectedLinker, objectFiles); sysLibraryCollector = new SystemLibraryCollector(selectedLinker, sysLibraries); // // if the <linker> has embedded <fileset>'s // (such as linker specific libraries) // add them as object files. // if (currentLinkerDef.hasFileSets()) { currentLinkerDef.visitFiles(objCollector); } // // user libraries are just a specialized form // of an object fileset selectedLinkerDef.visitUserLibraries(selectedLinker, objCollector); } break; } } } if (linkerConfig == null) { linkerConfig = this.linkerDef.createConfiguration(this, this.linkType, null, targetPlatform, versionInfo); selectedLinker = this.linkerDef.getProcessor().getLinker(this.linkType); objCollector = new ObjectFileCollector(selectedLinker, objectFiles); sysLibraryCollector = new SystemLibraryCollector(selectedLinker, sysLibraries); } // // unless there was a <linker> element that // explicitly did not inherit files from // containing <cc> element if (selectedLinkerDef == null || selectedLinkerDef.getInherit()) { this.linkerDef.visitUserLibraries(selectedLinker, objCollector); this.linkerDef.visitSystemLibraries(selectedLinker, sysLibraryCollector); } // // if there was a <syslibset> in a nested <linker> // evaluate it last so it takes priority over // identically named libs from <cc> element // if (selectedLinkerDef != null) { // // add any system libraries to the hashtable // done in reverse order so the earliest // on the classpath takes priority selectedLinkerDef.visitSystemLibraries(selectedLinker, sysLibraryCollector); } // // copy over any system libraries to the // object files vector // final Enumeration<File> sysLibEnum = sysLibraries.elements(); while (sysLibEnum.hasMoreElements()) { sysObjectFiles.addElement(sysLibEnum.nextElement()); } return (LinkerConfiguration) linkerConfig; }
From source file:org.apache.webdav.lib.WebdavResource.java
/** * Execute PROPFIND method for the given path and properties. * Get list of given WebDAV properties on the given resource. * * @param path the server relative path of the resource to request * @param properties the WebDAV properties to find. * @return Enumeration list of WebDAV properties on a resource. * @exception HttpException/* ww w. j a v a2 s . co m*/ * @exception IOException */ public Enumeration propfindMethod(String path, Vector properties) throws HttpException, IOException { setClient(); // Default depth=0, type=by_name PropFindMethod method = new PropFindMethod(URIUtil.encodePath(path), DepthSupport.DEPTH_0, properties.elements()); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); generateAdditionalHeaders(method); int status = client.executeMethod(method); // Also accept OK sent by buggy servers. if (status != HttpStatus.SC_MULTI_STATUS && status != HttpStatus.SC_OK) { HttpException ex = new HttpException(); ex.setReasonCode(status); throw ex; } // It contains the results. Vector results = new Vector(); Enumeration responses = method.getResponses(); if (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); String href = response.getHref(); // Set status code for this resource. if ((thisResource == true) && (response.getStatusCode() > 0)) setStatusCode(response.getStatusCode()); thisResource = false; Enumeration responseProperties = method.getResponseProperties(href); while (responseProperties.hasMoreElements()) { Property property = (Property) responseProperties.nextElement(); results.addElement(property.getPropertyAsString()); } } return results.elements(); }
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); }/*w w w . j a va2 s .c om*/ } }*/ 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:edu.ku.brc.dbsupport.ImportExportDB.java
@SuppressWarnings("unchecked") protected void sequentialDatabaseImport(Element dbImport, String dbTable, String parentName, long parentId, boolean recursion) { try {// w ww.j a v a2s .com String id = new String(); DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); // get the records List records = dbImport.selectNodes("//" + dbTable); //$NON-NLS-1$ DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); String primaryKey = info.getPrimaryKeyName(); List ids = dbImport.selectNodes("//" + primaryKey); //$NON-NLS-1$ if (records.size() < 1) { log.debug("Cannot import. Given database type:" + dbTable //$NON-NLS-1$ + " does not exsist in import file"); //$NON-NLS-1$ } else { // loop for each record for (int k = 0; k < records.size(); k++) { Vector collectionIds = new Vector(20); Vector collectionNames = new Vector(20); // keep this id to compare against it's collection Element idElement = (Element) ids.get(k); id = idElement.getStringValue(); // make the agent and the element Object agent = parentInfo.getClassObj().newInstance(); HashMap<String, Object> agentMap = new HashMap<String, Object>(); Element dbElement = (Element) records.get(k); Iterator i = dbElement.elementIterator(); do {// do for each element in the record Element element = (Element) i.next(); // Object value = findTypeSequential(element, dbTable, parentId, parentName // );//the parent is itself, just a dummy variable Object value = findTypeDataBase(element, dbTable, parentId, parentName);// the // parent // is // itself, // just // a // dummy // variable if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ { agentMap.put(element.getName(), value); } // ignore many-to-many for now else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ {// RECURSE if (recursion) { // get assoicated ids List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$ + primaryKey + " = \"" + id + "\"]/" + element.getName() //$NON-NLS-1$ //$NON-NLS-2$ + "/*"); //$NON-NLS-1$ // get collection info and still dont add it if (!temp_collection_ids.isEmpty()) { // get child dbName String childDbName = getDbName(temp_collection_ids); collectionNames.addElement(childDbName); for (int index = 0; index < temp_collection_ids.size(); index++) { collectionIds.addElement(temp_collection_ids.get(index)); } } } } else // else, dont add it { // if it is an id, just ignore. otherwise print out error if (!element.getName().equals(primaryKey)) { log.debug("did not add " + element.getName() //$NON-NLS-1$ + " to the element " + dbTable); //$NON-NLS-1$ } } } while (i.hasNext()); // populate and save BeanUtils.populate(agent, agentMap); this.session.save(agent); // if there was a collection, then recurse /* * if(!collectionIds.isEmpty()) { long newParentId = new * Long(session.getIdentifier(agent).toString()).longValue(); //import all * children sequentialXMLImportRecursion(collectionNames, collectionIds, * dbTable, newParentId); } */ } } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } }
From source file: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) *//* w w w .j a v a 2 s . c om*/ // 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; }