protected DCServerFactory.ResultCode sendEmail( String frEmail, String toEmail, String subj, String body) { if (StringTools.isBlank(frEmail)) { Print.logError("'From' Email address not specified"); return DCServerFactory.ResultCode.TRANSMIT_FAIL; } else if (StringTools.isBlank(toEmail) || !CommandPacketHandler.validateAddress(toEmail)) { Print.logError("'To' SMS Email address invalid, or not specified"); return DCServerFactory.ResultCode.TRANSMIT_FAIL; } else if (StringTools.isBlank(subj) && StringTools.isBlank(body)) { Print.logError("Command string not specified"); return DCServerFactory.ResultCode.INVALID_ARG; } else { try { Print.logInfo("SMS email: to <" + toEmail + ">"); Print.logDebug(" From : " + frEmail); Print.logDebug(" To : " + toEmail); Print.logDebug(" Subject: " + subj); Print.logDebug(" Message: " + body); SendMail.send(frEmail, toEmail, null, null, subj, body, null); return DCServerFactory.ResultCode.SUCCESS; } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException // this will fail if JavaMail support for SendMail is not available. Print.logWarn("SendMail error: " + t); return DCServerFactory.ResultCode.TRANSMIT_FAIL; } } }
/** * ** Gets a virtual DBRecord from the specified remote service ** @param servReq The remote web * service ** @return The virtual DBRecord (cannot be saved or reloaded) */ @SuppressWarnings("unchecked") public gDBR getVirtualDBRecord(final ServiceRequest servReq) throws DBException { String CMD_dbget = DBFactory.CMD_dbget; String TAG_Response = servReq.getTagResponse(); String TAG_Record = DBFactory.TAG_Record; String ATTR_command = servReq.getAttrCommand(); String ATTR_result = servReq.getAttrResult(); /* send request / get response */ Document xmlDoc = null; try { xmlDoc = servReq.sendRequest( CMD_dbget, new ServiceRequest.RequestBody() { public StringBuffer appendRequestBody(StringBuffer sb, int indent) { return DBRecordKey.this.toRequestXML(sb, indent); } }); } catch (IOException ioe) { Print.logException("Error", ioe); throw new DBException("Request read error", ioe); } /* parse 'GTSResponse' */ Element gtsResponse = xmlDoc.getDocumentElement(); if (!gtsResponse.getTagName().equalsIgnoreCase(TAG_Response)) { Print.logError("Request XML does not start with '%s'", TAG_Response); throw new DBException("Response XML does not begin eith '" + TAG_Response + "'"); } /* request command/argument */ String cmd = StringTools.trim(gtsResponse.getAttribute(ATTR_command)); String result = StringTools.trim(gtsResponse.getAttribute(ATTR_result)); if (StringTools.isBlank(result)) { result = StringTools.trim(gtsResponse.getAttribute("type")); } if (!result.equalsIgnoreCase("success")) { Print.logError("Response indicates failure"); throw new DBException("Response does not indicate 'success'"); } /* Record */ NodeList rcdList = XMLTools.getChildElements(gtsResponse, TAG_Record); if (rcdList.getLength() <= 0) { Print.logError("No 'Record' tags"); throw new DBException("GTSResponse does not contain any 'Record' tags"); } Element rcdElem = (Element) rcdList.item(0); /* return DBRecord */ gDBR dbr = (gDBR) DBFactory.parseXML_DBRecord(rcdElem); dbr.setVirtual(true); return dbr; }
/** * ** Returns true if the parent records in their respective parent tables exist. ** @return True * if the parent records exist. */ public boolean parentsExist() throws DBException { DBFactory<gDBR> dbFact = this.getFactory(); DBFieldValues myFldVals = this.getFieldValues(); java.util.List<String> parentList = dbFact.getParentTables(); for (String parentTable : parentList) { /* get parent table DBFactory */ Print.logInfo("[%s] Parent table: %s", this.getTableName(), parentTable); DBFactory parentFact = DBFactory.getFactoryByName(parentTable); if (parentFact == null) { Print.logError("Unexpected error finding parent table: " + parentTable); return false; } /* create parent record key with fields from this key */ DBRecordKey parentKey = parentFact.createKey(); // an empty key DBField parentKeyFlds[] = parentFact.getKeyFields(); for (DBField pkf : parentKeyFlds) { String pfn = pkf.getName(); /* get this DBField */ DBField myKeyFld = this.getField(pfn); if (myKeyFld == null) { Print.logError("Unexpected error finding field: [" + this.getTableName() + "] " + pfn); return false; } /* get parent key field value */ Object pkv = myFldVals.getFieldValue(pfn); if (pkv == null) { Print.logError("Unexpected error finding parent field: [" + parentTable + "] " + pfn); return false; } if (myKeyFld.isDefaultValue(pkv)) { Print.logInfo("This key contains a global value, skipping parent check: " + parentTable); parentKey = null; break; } parentKey.setFieldValue(pfn, pkv); } /* check parent existence */ if ((parentKey != null) && !parentKey.exists()) { Print.logError("Parent record does not exist: [" + parentTable + "] " + parentKey); return false; } } return true; }
protected boolean _setDevice(Device device, String ipAddress, int clientPort) { /* valid device? */ if (device == null) { return false; } /* validate ID address */ DataTransport dataXPort = device.getDataTransport(); if ((ipAddress != null) && !dataXPort.isValidIPAddress(ipAddress)) { Print.logError( "Invalid IPAddr: " + device.getAccountID() + "/" + device.getDeviceID() + " Found=" + ipAddress + " Expect=" + dataXPort.getIpAddressValid()); return false; } /* update device */ this.device = device; this.dataXPort = dataXPort; this.dataXPort.setIpAddressCurrent(ipAddress); // FLD_ipAddressCurrent this.dataXPort.setRemotePortCurrent(clientPort); // FLD_remotePortCurrent this.dataXPort.setDeviceCode(this.getDeviceCode()); // FLD_deviceCode this.device.setLastTotalConnectTime(DateTime.getCurrentTimeSec()); // FLD_lastTotalConnectTime /* ok */ return true; }
/* validate the syntax of the specified list of multiple email addresses */ public static boolean validateAddresses(String addrs, boolean acceptSMS) { if (StringTools.isBlank(addrs)) { // blank is ok in this case return true; } else if (acceptSMS) { // allow "sms:123456789" format String addrArry[] = StringTools.parseStringArray(addrs, ','); if (addrArry.length == 0) { return false; } for (int i = 0; i < addrArry.length; i++) { String em = addrArry[i].trim(); if (StringTools.isBlank(em)) { // individual addresses not allowed return false; } else if (SMSOutboundGateway.StartsWithSMS(em)) { // TODO: for now, accept as-is } else if (!validateAddress(em)) { return false; } } return true; } else { // true email addresses only try { return SendMail.validateAddresses(addrs); } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException // this will fail if JavaMail support for SendMail is not available. Print.logError("*** SendMail error: " + t); return false; } } }
public void run() { StringBuffer data = new StringBuffer(); Print.logDebug("Client:InputThread started"); while (true) { data.setLength(0); boolean timeout = false; try { if (this.readTimeout > 0L) { this.socket.setSoTimeout((int) this.readTimeout); } ClientSocketThread.socketReadLine(this.socket, -1, data); } catch (InterruptedIOException ee) { // SocketTimeoutException ee) { // error("Read interrupted (timeout) ..."); if (getRunStatus() != THREAD_RUNNING) { break; } timeout = true; // continue; } catch (Throwable t) { Print.logError("Client:InputThread - " + t); t.printStackTrace(); break; } if (!timeout || (data.length() > 0)) { ClientSocketThread.this.handleMessage(data.toString()); } } synchronized (this.threadLock) { this.isRunning = false; Print.logDebug("Client:InputThread stopped"); this.threadLock.notify(); } }
/** ** Main entry point for testing/debugging ** @param argv Comand-line arguments */ public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); String host = RTConfig.getString(ARG_HOST, null); int port = RTConfig.getInt(ARG_PORT, 0); /* send data */ if (RTConfig.hasProperty(ARG_SEND)) { if (StringTools.isBlank(host)) { Print.logError("Target host not specified"); usage(); } if (port <= 0) { Print.logError("Target port not specified"); usage(); } String dataStr = RTConfig.getString(ARG_SEND, "hello"); byte data[] = dataStr.startsWith("0x") ? StringTools.parseHex(dataStr, null) : dataStr.getBytes(); ClientSocketThread cst = new ClientSocketThread(host, port); try { cst.openSocket(); cst.socketWriteBytes(data); } catch (Throwable t) { Print.logException("Error", t); } finally { cst.closeSocket(); } System.exit(0); } /* receive data */ if (RTConfig.hasProperty(ARG_RECEIVE)) { if (port <= 0) { Print.logError("Target port not specified"); usage(); } if (!StringTools.isBlank(host)) { Print.logWarn("Specified 'host' will be ignored"); } Print.logError("Receive not yet implemented ..."); System.exit(99); } /* show usage */ usage(); }
/* private constructor */ private TrackServer(int tcpPorts[], int udpPorts[], int commandPort) throws Throwable { int listeners = 0; // Start TCP listeners if (!ListTools.isEmpty(tcpPorts)) { for (int i = 0; i < tcpPorts.length; i++) { int port = tcpPorts[i]; if (ServerSocketThread.isValidPort(port)) { try { this._startTCP(port); listeners++; } catch (java.net.BindException be) { Print.logError("TCP: Error binding to port: %d", port); } } else { throw new Exception("TCP: Invalid port number: " + port); } } } // Start UDP listeners if (!ListTools.isEmpty(udpPorts)) { for (int i = 0; i < udpPorts.length; i++) { int port = udpPorts[i]; if (ServerSocketThread.isValidPort(port)) { try { ServerSocketThread sst = this._startUDP(port); if (this.udpSocket == null) { this.udpSocket = sst.getDatagramSocket(); } listeners++; } catch (java.net.BindException be) { Print.logError("UDP: Error binding to port: %d", port); } } else { throw new Exception("UDP: Invalid port number: " + port); } } } /* do we have any active listeners? */ if (listeners <= 0) { Print.logWarn("No active device communication listeners!"); } }
protected Device loadDevice(String acctID, String devID) { if (StringTools.isBlank(acctID)) { return this.loadDevice(devID); // load ad ModemID } else { try { Account account = Account.getAccount(acctID); if (account == null) { Print.logError("Account-ID not found: " + acctID); return null; } else { Device dev = Transport.loadDeviceByTransportID(account, devID); return dev; } } catch (DBException dbe) { Print.logError("Error getting Device: " + acctID + "/" + devID + " [" + dbe + "]"); return null; } } }
private Document GetXMLDocument(String url) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputStream input = HTMLTools.inputStream_GET(url, 5000); InputStreamReader reader = new InputStreamReader(input, ENCODING_UTF8); InputSource inSrc = new InputSource(reader); inSrc.setEncoding(ENCODING_UTF8); return db.parse(inSrc); } catch (ParserConfigurationException pce) { Print.logError("Parse error: " + pce); return null; } catch (SAXException se) { Print.logError("Parse error: " + se); return null; } catch (IOException ioe) { Print.logError("IO error: " + ioe); return null; } }
/** * ** Invokes all listeners with an assciated command ** @param r a string that may specify a * command (possibly one ** of several) associated with the event */ protected void invokeListeners(String r) { if (this.actionListeners != null) { for (Iterator i = this.actionListeners.iterator(); i.hasNext(); ) { ActionListener al = (ActionListener) i.next(); ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, r); try { al.actionPerformed(ae); } catch (Throwable t) { Print.logError("Exception: " + t.getMessage()); } } } }
/** * ** Sets the DBRecord for this node ** @param record The DBRecord to set ** @return True if the * DBRecord was successfully set, false otherwise */ public boolean setDBRecord(DBRecord<?> record) { /* pre-checks */ this.dbRecord = null; if (record == null) { return false; } else if (!this.hasDBFactory()) { // TODO: we probably could just retrieve the DBFactory from the DBRecord Print.logError("DBFactory is not defined!"); return false; } /* check DBFactory */ DBFactory<?> rcdFact = DBRecord.getFactory(record); if (!this.getDBFactory().equals(rcdFact)) { Print.logError("Invalid DBFactory for specified DBRecord!"); return false; } /* set DBRecord */ this.dbRecord = record; return true; }
public final User getUser() { if (this.user == null) { String userID = this.getUserID(); Print.logDebug("[Optimize] Retrieving User record: " + userID); try { this.user = User.getUser(this.getAccount(), userID); // 'this.asset' may still be null if the asset was not found } catch (DBException dbe) { // may be caused by "java.net.ConnectException: Connection refused: connect" Print.logError("User not found: " + this.getAccountID() + "/" + userID); this.user = null; } } return this.user; }
public void run() { String command = null; Print.logInfo("Client:OutputThread started"); while (true) { /* wait for commands */ synchronized (this.cmdList) { while ((this.cmdList.size() <= 0) && (getRunStatus() == THREAD_RUNNING)) { try { this.cmdList.wait(5000L); } catch (Throwable t) { /*ignore*/ } } if (getRunStatus() != THREAD_RUNNING) { break; } command = this.cmdList.remove(0).toString(); } /* send commands */ try { ClientSocketThread.socketWriteLine(this.socket, command); } catch (Throwable t) { Print.logError("Client:OutputThread - " + t); t.printStackTrace(); break; } } if (getRunStatus() == THREAD_RUNNING) { Print.logWarn("Client:OutputThread stopped due to error"); } else { Print.logInfo("Client:OutputThread stopped"); } synchronized (this.threadLock) { this.isRunning = false; Print.logInfo("Client:OutputThread stopped"); this.threadLock.notify(); } }
/** * ** Traverses the DBFactory dependency tree, creating a DBFactoryTree ** @param level The * current tree level ** @param dbFact The current DBFactory to add ** @param parentNode The * parent node to which a new DBFactoryNode child will be added ** @param addedTables A set of * table names added to the current DBFactoryTree * */ private static void _traverseDBFactoryTree( int level, DBFactory<? extends DBRecord> dbFact, DBFactoryTree parentNode, Set<String> addedTables) { /* no DBFactory? */ if (dbFact == null) { Print.logError("Null DBFactory!"); return; } String utableName = dbFact.getUntranslatedTableName(); /* already added? */ if (addedTables.contains(utableName)) { return; } addedTables.add(utableName); /* add this node */ // Print.logInfo(StringTools.replicateString(" ",level) + dbFact.getUntranslatedTableName()); DBFactoryTree dbFactNode = new DBFactoryTree(level, parentNode, dbFact); parentNode.addChild(dbFactNode); /* find dependent children */ DBFactory<? extends DBRecord> childFact[] = dbFact.getChildFactories(); for (int i = 0; i < childFact.length; i++) { int index = childFact[i].getParentTables().indexOf(utableName); if (level == index) { DBFactoryTree._traverseDBFactoryTree(level + 1, childFact[i], dbFactNode, addedTables); } else if (!addedTables.contains(childFact[i].getUntranslatedTableName())) { Print.logWarn( "Skipping table in heiarchy: " + utableName + " ==> " + childFact[i].getUntranslatedTableName()); } } }
public static void main(String args[]) { DBConfig.cmdLineInit(args, true); // main String acctID = RTConfig.getString(ARG_ACCOUNT, ""); String roleID = RTConfig.getString(ARG_ROLE, ""); String aclID = RTConfig.getString(ARG_ACL, ""); /* account-id specified? */ if ((acctID == null) || acctID.equals("")) { Print.logError("Account-ID not specified."); usage(); } /* get account */ Account acct = null; try { acct = Account.getAccount(acctID); // may return DBException if (acct == null) { Print.logError("Account-ID does not exist: " + acctID); usage(); } } catch (DBException dbe) { Print.logException("Error loading Account: " + acctID, dbe); // dbe.printException(); System.exit(99); } /* role-id specified? */ if ((roleID == null) || roleID.equals("")) { Print.logError("Role-ID not specified."); usage(); } /* get role */ Role role = null; try { role = Role.getRole(acct, roleID); // may return DBException if (role == null) { Print.logError("Role-ID does not exist: " + acctID + "/" + roleID); usage(); } } catch (DBException dbe) { Print.logException("Error loading Role: " + acctID + "/" + roleID, dbe); // dbe.printException(); System.exit(99); } /* RoleAcl exists? */ boolean aclExists = false; if ((aclID != null) && !aclID.equals("")) { try { aclExists = RoleAcl.exists(acctID, roleID, aclID); } catch (DBException dbe) { Print.logError( "Error determining if RoleAcl exists: " + acctID + "/" + roleID + "/" + aclID); System.exit(99); } } /* option count */ int opts = 0; /* list */ if (RTConfig.getBoolean(ARG_LIST, false)) { opts++; try { String aclList[] = role.getAclsForRole(); for (int i = 0; i < aclList.length; i++) { AccessLevel level = RoleAcl.getAccessLevel(role, aclList[i], AccessLevel.NONE); Print.sysPrintln(" " + aclList[i] + " ==> " + level); } } catch (DBException dbe) { Print.logError("Error getting Acl list: " + dbe); System.exit(99); } System.exit(0); } /* delete */ if (RTConfig.getBoolean(ARG_DELETE, false) && !acctID.equals("") && !roleID.equals("")) { opts++; if (!aclExists) { Print.logWarn("RoleAcl does not exist: " + acctID + "/" + roleID + "/" + aclID); Print.logWarn("Continuing with delete process ..."); } try { RoleAcl.Key aclKey = new RoleAcl.Key(acctID, roleID, aclID); aclKey.delete(true); // also delete dependencies Print.logInfo("RoleAcl deleted: " + acctID + "/" + roleID + "/" + aclID); } catch (DBException dbe) { Print.logError("Error deleting RoleAcl: " + acctID + "/" + roleID + "/" + aclID); dbe.printException(); System.exit(99); } System.exit(0); } /* create */ if (RTConfig.getBoolean(ARG_CREATE, false)) { opts++; if (aclExists) { Print.logWarn("RoleAcl already exists: " + acctID + "/" + roleID + "/" + aclID); } else { try { RoleAcl.createNewRoleAcl(role, aclID); Print.logInfo("Created RoleAcl: " + acctID + "/" + roleID + "/" + aclID); aclExists = true; } catch (DBException dbe) { Print.logError("Error creating RoleAcl: " + acctID + "/" + roleID + "/" + aclID); dbe.printException(); System.exit(99); } } } /* set */ if (RTConfig.hasProperty(ARG_SET)) { opts++; AccessLevel aclLevel = EnumTools.getValueOf(AccessLevel.class, RTConfig.getInt(ARG_SET, -1)); try { RoleAcl.setAccessLevel(role, aclID, aclLevel); Print.logInfo( "Set RoleAcl '" + acctID + "/" + roleID + "/" + aclID + "' to level " + aclLevel); } catch (DBException dbe) { Print.logError("Error setting RoleAcl: " + acctID + "/" + roleID + "/" + aclID); dbe.printException(); System.exit(99); } System.exit(0); } /* edit */ if (RTConfig.getBoolean(ARG_EDIT, false)) { opts++; if (!aclExists) { Print.logError("RoleAcl does not exist: " + acctID + "/" + roleID + "/" + aclID); } else { try { RoleAcl roleAcl = RoleAcl.getRoleAcl(role, aclID, false); // may throw DBException DBEdit editor = new DBEdit(roleAcl); editor.edit(); // may throw IOException } catch (IOException ioe) { if (ioe instanceof EOFException) { Print.logError("End of input"); } else { Print.logError("IO Error"); } } catch (DBException dbe) { Print.logError("Error editing RoleAcl: " + acctID + "/" + roleID + "/" + aclID); dbe.printException(); } } System.exit(0); } /* no options specified */ if (opts == 0) { Print.logWarn("Missing options ..."); usage(); } }
public static void main(String args[]) { DBConfig.cmdLineInit(args, true); // main String acctID = RTConfig.getString(ARG_ACCOUNT, ""); String strID = RTConfig.getString(ARG_STRING, ""); /* account-id specified? */ if (StringTools.isBlank(acctID)) { Print.logError("Account-ID not specified."); usage(); } /* get account */ Account acct = null; try { acct = Account.getAccount(acctID); // may throw DBException if (acct == null) { Print.logError("Account-ID does not exist: " + acctID); usage(); } } catch (DBException dbe) { Print.logException("Error loading Account: " + acctID, dbe); // dbe.printException(); System.exit(99); } /* string-id specified? */ if ((strID == null) || strID.equals("")) { Print.logError("String-ID not specified."); usage(); } /* string exists? */ boolean stringExists = false; try { stringExists = AccountString.exists(acctID, strID); } catch (DBException dbe) { Print.logError("Error determining if AccountString exists: " + _fmtStrID(acctID, strID)); System.exit(99); } /* option count */ int opts = 0; /* delete */ if (RTConfig.getBoolean(ARG_DELETE, false) && !acctID.equals("") && !strID.equals("")) { opts++; if (!stringExists) { Print.logWarn("AccountString does not exist: " + _fmtStrID(acctID, strID)); Print.logWarn("Continuing with delete process ..."); } try { AccountString.Key strKey = new AccountString.Key(acctID, strID); strKey.delete(true); // also delete dependencies Print.logInfo("AccountString deleted: " + _fmtStrID(acctID, strID)); stringExists = false; } catch (DBException dbe) { Print.logError("Error deleting AccountString: " + _fmtStrID(acctID, strID)); dbe.printException(); System.exit(99); } System.exit(0); } /* create */ if (RTConfig.getBoolean(ARG_CREATE, false)) { opts++; if (stringExists) { Print.logWarn("AccountString already exists: " + _fmtStrID(acctID, strID)); } else { try { AccountString.createNewAccountString(acct, strID); Print.logInfo("Created AccountString: " + _fmtStrID(acctID, strID)); stringExists = true; } catch (DBException dbe) { Print.logError("Error creating AccountString: " + _fmtStrID(acctID, strID)); dbe.printException(); System.exit(99); } } } /* edit */ if (RTConfig.getBoolean(ARG_EDIT, false)) { opts++; if (!stringExists) { Print.logError("AccountString does not exist: " + _fmtStrID(acctID, strID)); } else { try { AccountString str = AccountString.getAccountString(acct, strID, false); // may throw DBException DBEdit editor = new DBEdit(str); editor.edit(true); // may throw IOException } catch (IOException ioe) { if (ioe instanceof EOFException) { Print.logError("End of input"); } else { Print.logError("IO Error"); } } catch (DBException dbe) { Print.logError("Error editing AccountString: " + _fmtStrID(acctID, strID)); dbe.printException(); } } System.exit(0); } /* no options specified */ if (opts == 0) { Print.logWarn("Missing options ..."); usage(); } }
public static void main(String argv[]) { DBConfig.cmdLineInit(argv, true); // main String accountID = RTConfig.getString(ARG_ACCOUNT, ""); String deviceID = RTConfig.getString(ARG_DEVICE, ""); int statusCode = RTConfig.getInt(ARG_CODE, 0); boolean anyCode = true; // RTConfig.hasProperty(ARG_ECODE); /* account-id specified? */ if (StringTools.isBlank(accountID)) { Print.logError("Account-ID not specified."); usage(); } /* get account */ Account account = null; try { account = Account.getAccount(accountID); // may throw DBException if (account == null) { Print.logError("Account-ID does not exist: " + accountID); usage(); } } catch (DBException dbe) { Print.logException("Error loading Account: " + accountID, dbe); // dbe.printException(); System.exit(99); } /* device-id specified? */ if (StringTools.isBlank(deviceID) || deviceID.startsWith("/")) { deviceID = ALL_DEVICES; } /* check device existance */ if (!deviceID.equals(ALL_DEVICES)) { try { Device device = Device.getDevice(account, deviceID); // may throw DBException if (device == null) { Print.logError("Device-ID does not exist: " + accountID + " / " + deviceID); usage(); } } catch (DBException dbe) { Print.logException("Error loading Device: " + accountID + " / " + deviceID, dbe); System.exit(99); } } /* status-code specified? */ if ((statusCode > 0) && !anyCode && !StatusCodes.IsValid(statusCode, account.getPrivateLabel())) { Print.logError("Invalid Status Code specified."); usage(); } /* statusCode specified? */ if (statusCode <= 0) { Print.logError("StatusCode not specified."); usage(); } /* statusCode exists? */ boolean statusCodeExists = false; try { statusCodeExists = StatusCode.exists(accountID, deviceID, statusCode); } catch (DBException dbe) { Print.logError( "Error determining if StatusCode exists: " + accountID + "/" + deviceID + "/" + statusCode); System.exit(99); } /* option count */ int opts = 0; /* delete */ if (RTConfig.getBoolean(ARG_DELETE, false)) { opts++; if (!statusCodeExists) { Print.logWarn( "StatusCode does not exist: " + accountID + "/" + deviceID + "/" + statusCode); Print.logWarn("Continuing with delete process ..."); } try { StatusCode.Key scKey = new StatusCode.Key(accountID, deviceID, statusCode); scKey.delete(true); // also delete dependencies (if any) Print.logInfo("StatusCode deleted: " + accountID + "/" + deviceID + "/" + statusCode); statusCodeExists = false; } catch (DBException dbe) { Print.logError( "Error deleting StatusCode: " + accountID + "/" + deviceID + "/" + statusCode); dbe.printException(); System.exit(99); } System.exit(0); } /* create */ if (RTConfig.getBoolean(ARG_CREATE, false)) { opts++; if (statusCodeExists) { Print.logWarn( "StatusCode already exists: " + accountID + "/" + deviceID + "/" + statusCode); } else { try { StatusCode.createNewStatusCode(account, deviceID, statusCode); Print.logInfo("Created StatusCode: " + accountID + "/" + deviceID + "/" + statusCode); statusCodeExists = true; } catch (DBException dbe) { Print.logError( "Error creating StatusCode: " + accountID + "/" + deviceID + "/" + statusCode); dbe.printException(); System.exit(99); } } } /* edit */ if (RTConfig.getBoolean(ARG_EDIT, false)) { opts++; if (!statusCodeExists) { Print.logError( "StatusCode does not exist: " + accountID + "/" + deviceID + "/" + statusCode); } else { try { StatusCode sc = StatusCode.getStatusCode(account, deviceID, statusCode); // may throw DBException DBEdit editor = new DBEdit(sc); editor.edit(); // may throw IOException } catch (IOException ioe) { if (ioe instanceof EOFException) { Print.logError("End of input"); } else { Print.logError("IO Error"); } } catch (DBException dbe) { Print.logError( "Error editing StatusCode: " + accountID + "/" + deviceID + "/" + statusCode); dbe.printException(); } } System.exit(0); } /* list */ if (RTConfig.hasProperty(ARG_LIST)) { opts++; String listType = RTConfig.getString(ARG_LIST, null); // TODO: complete ... } /* no options specified */ if (opts == 0) { Print.logWarn("Missing options ..."); usage(); } }
/** * ** Returns true if the specified key attribute exists in the table ** @param altIndexName The * alternate index name, or null to use the primary index ** @param whereKeyType The partial key * match type ** @return True if the specified key attribute exists in the table, false otherwise */ protected boolean _exists(String altIndexName, int whereKeyType) throws SQLException, DBException { /* key fields */ boolean usePrimaryKey = StringTools.isBlank(altIndexName); DBField kfld[] = usePrimaryKey ? this.getKeyFields() : this.getAltKeyFields(altIndexName); if (ListTools.isEmpty(kfld)) { throw new DBException("No keys found!"); } /* check last key for "auto_increment" */ if (whereKeyType == DBWhere.KEY_FULL) { DBField lastField = kfld[kfld.length - 1]; if (lastField.isAutoIncrement() && !this.getFieldValues().hasFieldValue(lastField.getName())) { // full key requested and last key is auto_increment, which is missing return false; } } // DBSelect: SELECT <Keys> FROM <TableName> <KeyWhere> String firstKey = kfld[0].getName(); DBSelect<gDBR> dsel = new DBSelect<gDBR>(this.getFactory()); dsel.setSelectedFields(firstKey); dsel.setWhere(this._getWhereClause(altIndexName, whereKeyType)); /* get keyed record */ DBConnection dbc = null; Statement stmt = null; ResultSet rs = null; boolean exists = false; try { dbc = DBConnection.getDefaultConnection(); stmt = dbc.execute(dsel.toString()); // may throw DBException rs = stmt.getResultSet(); exists = rs.next(); } catch (SQLException sqe) { if (sqe.getErrorCode() == DBFactory.SQLERR_TABLE_NOTLOCKED) { // MySQL: This case has been seen on rare occasions. Not sure what causes it. Print.logError("SQL Lock Error: " + sqe); Print.logError("Hackery! Forcing lock on table: " + this.getTableName()); if (DBProvider.lockTableForRead(this.getTableName(), true)) { // may throw DBException stmt = dbc.execute(dsel.toString()); // may throw SQLException, DBException rs = stmt.getResultSet(); // SQLException exists = rs.next(); // SQLException DBProvider.unlockTables(); // DBException } } else { throw sqe; } } finally { if (rs != null) { try { rs.close(); } catch (Throwable t) { } } if (stmt != null) { try { stmt.close(); } catch (Throwable t) { } } DBConnection.release(dbc); } return exists; }
/* return reverse-geocode using nearest address */ public ReverseGeocode getAddressReverseGeocode(GeoPoint gp, String localeStr, boolean cache) { /* check for failover mode */ if (this.isReverseGeocodeFailoverMode()) { ReverseGeocodeProvider frgp = this.getFailoverReverseGeocodeProvider(); return frgp.getReverseGeocode(gp, localeStr, cache); } /* URL */ String url = this.getAddressReverseGeocodeURL(gp, localeStr); Print.logDebug("Google RG URL: " + url); // byte xmlBytes[] = HTMLTools.readPage(url); /* create XML document */ Document xmlDoc = GetXMLDocument(url, this.getReverseGeocodeTimeout()); if (xmlDoc == null) { return null; } /* vars */ String errCode = null; String address = null; /* parse "xml" */ Element kml = xmlDoc.getDocumentElement(); if (kml.getTagName().equalsIgnoreCase(TAG_kml)) { NodeList ResponseList = XMLTools.getChildElements(kml, TAG_Response); for (int g = 0; (g < ResponseList.getLength()); g++) { Element response = (Element) ResponseList.item(g); NodeList responseNodes = response.getChildNodes(); for (int n = 0; n < responseNodes.getLength(); n++) { Node responseNode = responseNodes.item(n); if (!(responseNode instanceof Element)) { continue; } Element responseElem = (Element) responseNode; String responseNodeName = responseElem.getNodeName(); if (responseNodeName.equalsIgnoreCase(TAG_name)) { // <name>40.479581,-117.773438</name> } else if (responseNodeName.equalsIgnoreCase(TAG_Status)) { // <Status> ... </Status> NodeList statusNodes = responseElem.getChildNodes(); for (int st = 0; st < statusNodes.getLength(); st++) { Node statusNode = statusNodes.item(st); if (!(statusNode instanceof Element)) { continue; } Element statusElem = (Element) statusNode; String statusNodeName = statusElem.getNodeName(); if (statusNodeName.equalsIgnoreCase(TAG_code)) { errCode = StringTools.trim(GoogleGeocodeV2.GetNodeText(statusElem)); // expect "200" break; // we only care about the 'code' } } } else if (responseNodeName.equalsIgnoreCase(TAG_Placemark)) { // <Placemark> ... </Placemark> String id = responseElem.getAttribute(ATTR_id); if ((id != null) && id.equals("p1")) { NodeList placemarkNodes = responseElem.getChildNodes(); for (int pm = 0; pm < placemarkNodes.getLength(); pm++) { Node placemarkNode = placemarkNodes.item(pm); if (!(placemarkNode instanceof Element)) { continue; } Element placemarkElem = (Element) placemarkNode; String placemarkNodeName = placemarkElem.getNodeName(); if (placemarkNodeName.equalsIgnoreCase(TAG_address)) { address = GoogleGeocodeV2.GetNodeText(placemarkElem); break; // we only care about the 'address' } } } else { // Print.logInfo("Skipping Placemark ID = %s", id); } } } } } /* create address */ if (FAILOVER_DEBUG) { errCode = "620"; } else if (!StringTools.isBlank(address)) { // address found ReverseGeocode rg = new ReverseGeocode(); rg.setFullAddress(address); return rg; } /* check for Google reverse-geocode limit exceeded */ if ((errCode != null) && errCode.equals("620")) { Print.logError("!!!! Google Reverse-Geocode Limit Exceeded [Error 620] !!!!"); if (this.hasFailoverReverseGeocodeProvider()) { this.startReverseGeocodeFailoverMode(); ReverseGeocodeProvider frgp = this.getFailoverReverseGeocodeProvider(); Print.logWarn("Failing over to '" + frgp.getName() + "'"); return frgp.getReverseGeocode(gp, localeStr, cache); } } /* no reverse-geocode available */ return null; }
// http://code.google.com/apis/maps/documentation/geocoding/index.html public GeoPoint getGeocode(String address, String country) { /* URL */ String url = this.getGeoPointGeocodeURL(address, country); Print.logDebug("Google GC URL: " + url); /* create XML document */ Document xmlDoc = GetXMLDocument(url, this.getGeocodeTimeout()); if (xmlDoc == null) { return null; } /* vars */ String errCode = null; GeoPoint geoPoint = null; /* parse "xml" */ Element kml = xmlDoc.getDocumentElement(); if (kml.getTagName().equalsIgnoreCase(TAG_kml)) { NodeList ResponseList = XMLTools.getChildElements(kml, TAG_Response); for (int g = 0; (g < ResponseList.getLength()); g++) { Element response = (Element) ResponseList.item(g); NodeList responseNodes = response.getChildNodes(); for (int n = 0; n < responseNodes.getLength(); n++) { Node responseNode = responseNodes.item(n); if (!(responseNode instanceof Element)) { continue; } Element responseElem = (Element) responseNode; String responseNodeName = responseElem.getNodeName(); if (responseNodeName.equalsIgnoreCase(TAG_name)) { // <name>1600 Amphitheatre Parkway, Mountain View, CA</name> } else if (responseNodeName.equalsIgnoreCase(TAG_Status)) { // <Status> ... </Status> NodeList statusNodes = responseElem.getChildNodes(); for (int st = 0; st < statusNodes.getLength(); st++) { Node statusNode = statusNodes.item(st); if (!(statusNode instanceof Element)) { continue; } Element statusElem = (Element) statusNode; String statusNodeName = statusElem.getNodeName(); if (statusNodeName.equalsIgnoreCase(TAG_code)) { errCode = StringTools.trim(GoogleGeocodeV2.GetNodeText(statusElem)); // expect "200" break; // we only care about the 'code' } } } else if (responseNodeName.equalsIgnoreCase(TAG_Placemark)) { // <Placemark> ... </Placemark> String id = responseElem.getAttribute(ATTR_id); if ((id != null) && id.equals("p1")) { NodeList placemarkNodes = responseElem.getChildNodes(); for (int pm = 0; (geoPoint == null) && (pm < placemarkNodes.getLength()); pm++) { Node placemarkNode = placemarkNodes.item(pm); if (!(placemarkNode instanceof Element)) { continue; } Element placemarkElem = (Element) placemarkNode; String placemarkNodeName = placemarkElem.getNodeName(); if (placemarkNodeName.equalsIgnoreCase(TAG_Point)) { NodeList pointNodes = placemarkElem.getChildNodes(); for (int ptn = 0; (geoPoint == null) && (ptn < pointNodes.getLength()); ptn++) { Node pointNode = pointNodes.item(ptn); if (!(pointNode instanceof Element)) { continue; } Element pointElem = (Element) pointNode; String pointNodeName = pointElem.getNodeName(); if (pointNodeName.equalsIgnoreCase(TAG_coordinates)) { String ll[] = StringTools.split(GoogleGeocodeV2.GetNodeText(pointElem), ','); if (ll.length >= 2) { double lon = StringTools.parseDouble(ll[0], 0.0); // longitude is first double lat = StringTools.parseDouble(ll[1], 0.0); if (GeoPoint.isValid(lat, lon)) { geoPoint = new GeoPoint(lat, lon); break; // we only care about the 'GeoPoint' } } } } } } } else { // Print.logInfo("Skipping Placemark ID = %s", id); } } } } } /* create address */ if (geoPoint != null) { // GeoPoint found return geoPoint; } /* check for Google reverse-geocode limit exceeded */ if ((errCode != null) && errCode.equals("620")) { Print.logError("!!!! Google Reverse-Geocode Limit Exceeded [Error 620] !!!!"); } /* no reverse-geocode available */ return null; }