/* return the DBSelect statement for the specified account/group */ protected static DBSelect _getUserListSelect(String acctId, String groupId) { /* empty/null account */ if (StringTools.isBlank(acctId)) { return null; } /* empty/null user */ if (StringTools.isBlank(groupId)) { return null; } /* get select */ // DBSelect: SELECT * FROM GroupList WHERE ((accountID='acct') and (groupID='group')) ORDER BY // userID DBSelect<GroupList> dsel = new DBSelect<GroupList>(GroupList.getFactory()); dsel.setSelectedFields(GroupList.FLD_userID); DBWhere dwh = dsel.createDBWhere(); dsel.setWhere( dwh.WHERE_( dwh.AND( dwh.EQ(GroupList.FLD_accountID, acctId), dwh.EQ(GroupList.FLD_groupID, groupId)))); dsel.setOrderByFields(GroupList.FLD_userID); return dsel; }
// [System][Manufacturer][SubSystem][Problem] eg. "P0071" Powertrain // References: // http://www.obd-codes.com/trouble_codes/ // http://obdcon.sourceforge.net/2010/06/obd-ii-pids/ public static long EncodeFault_OBDII(String dtcStr) { long faultCode = TYPE_OBDII; /* trim */ dtcStr = StringTools.trim(dtcStr); if (dtcStr.indexOf(",") >= 0) { dtcStr = dtcStr.substring(0, dtcStr.indexOf(",")).trim(); } if (dtcStr.equals("")) { return faultCode; } /* check length */ if (dtcStr.length() == 4) { dtcStr = "U" + dtcStr; // unknown } else if (dtcStr.length() != 5) { return faultCode; } /* active */ faultCode |= EncodeActive(true); // [ACTIVE_MASK] 0x0100000000000000 /* encode system cjaracter (ie. "Powertrain") */ faultCode |= EncodeSystem(dtcStr.charAt(0)); // [MID_MASK] 0x00FFFFFF00000000 /* encode manufacturer specific and subsystem */ int mfgCode = StringTools.parseInt(dtcStr.substring(1, 2), 0); int spid = (mfgCode != 0) ? 0x8000 : 0; int subSys = StringTools.parseInt(dtcStr.substring(2, 5), 0); spid |= (subSys & 0xFFF); faultCode |= EncodeSPID(spid); // [SPID_MASK] 0x00000000FFFF0000 /* return fault code */ return faultCode; }
/* return status codes for account/device */ public static int[] getStatusCodes(String accountID, String deviceID) throws DBException { /* account-id specified? */ if (StringTools.isBlank(accountID)) { return new int[0]; } /* device-id specified? */ if (StringTools.isBlank(deviceID)) { deviceID = ALL_DEVICES; } /* select */ // DBSelect: SELECT statucCode FROM StatusCode WHERE (accountID='acct') AND (deviceID='*') ORDER // BY statucCode DBSelect<StatusCode> dsel = new DBSelect<StatusCode>(StatusCode.getFactory()); dsel.setSelectedFields(StatusCode.FLD_statusCode); DBWhere dwh = dsel.createDBWhere(); dsel.setWhere( dwh.WHERE_( dwh.AND( dwh.EQ(StatusCode.FLD_accountID, accountID), dwh.EQ(StatusCode.FLD_deviceID, deviceID)))); dsel.setOrderByFields(StatusCode.FLD_statusCode); /* get list */ java.util.List<Integer> codeList = new Vector<Integer>(); Statement stmt = null; ResultSet rs = null; try { stmt = DBConnection.getDefaultConnection().execute(dsel.toString()); rs = stmt.getResultSet(); while (rs.next()) { int code = rs.getInt(StatusCode.FLD_statusCode); codeList.add(new Integer(code)); } } catch (SQLException sqe) { throw new DBException("Getting StatusCode List", sqe); } finally { if (rs != null) { try { rs.close(); } catch (Throwable t) { } } if (stmt != null) { try { stmt.close(); } catch (Throwable t) { } } } /* return array of status codes */ int codeListInt[] = new int[codeList.size()]; for (int i = 0; i < codeListInt.length; i++) { codeListInt[i] = codeList.get(i).intValue(); } return codeListInt; }
/** * ** 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; }
/* return StatusCode */ public static StatusCode findStatusCode(String accountID, String deviceID, int statusCode) { /* check account status codes */ if (!StringTools.isBlank(accountID)) { // first, try account/device if (!StringTools.isBlank(deviceID)) { try { StatusCode.Key codeKey = new StatusCode.Key(accountID, deviceID, statusCode); if (codeKey.exists()) { // may throw DBException StatusCode code = codeKey.getDBRecord(true); if (code != null) { // should not be null return code; } } } catch (DBException dbe) { // ignore error } } // next, try just the account try { StatusCode.Key codeKey = new StatusCode.Key(accountID, statusCode); if (codeKey.exists()) { // may throw DBException StatusCode code = codeKey.getDBRecord(true); if (code != null) { // should not be null return code; } } } catch (DBException dbe) { // ignore error } } /* check global status codes */ String sysAdmin = AccountRecord.getSystemAdminAccountID(); if (!StringTools.isBlank(sysAdmin)) { try { StatusCode.Key codeKey = new StatusCode.Key(sysAdmin, statusCode); if (codeKey.exists()) { // may throw DBException StatusCode code = codeKey.getDBRecord(true); if (code != null) { // should not be null return code; } } } catch (DBException dbe) { // ignore error } } /* icon selector not found */ return null; }
public Field(String s) { String f[] = StringTools.parseString(s, FIELD_VALUE_SEPARATOR); if ((f.length > 0) && (f[0].length() > 0) && Character.isLetter(f[0].charAt(0))) { this.isHiRes = (f.length > 0) ? f[0].equalsIgnoreCase("H") : false; this.type = (f.length > 1) ? StringTools.parseInt(f[1], -1) : -1; } else { this.type = (f.length > 0) ? StringTools.parseInt(f[0], -1) : -1; this.isHiRes = (f.length > 1) ? f[1].equalsIgnoreCase("H") : false; } this.index = (f.length > 2) ? StringTools.parseInt(f[2], 0) : 0; this.length = (f.length > 3) ? StringTools.parseInt(f[3], 0) : 0; this.isValid = (f.length == 4) && (this.type >= 0) && (this.index >= 0) && (this.length > 0); }
/* return list of all Devices within the specified DeviceGroup (NOT SCALABLE BEYOND A FEW HUNDRED GROUPS) */ public static java.util.List<String> getUsersForGroup(String acctId, String groupId) throws DBException { /* valid account/groupId? */ if (StringTools.isBlank(acctId)) { return null; } else if (StringTools.isBlank(groupId)) { return null; } /* get db selector */ DBSelect dsel = GroupList._getUserListSelect(acctId, groupId); if (dsel == null) { return null; } /* read users for group */ java.util.List<String> usrList = new Vector<String>(); DBConnection dbc = null; Statement stmt = null; ResultSet rs = null; try { dbc = DBConnection.getDefaultConnection(); stmt = dbc.execute(dsel.toString()); rs = stmt.getResultSet(); while (rs.next()) { String usrId = rs.getString(GroupList.FLD_userID); usrList.add(usrId); } } catch (SQLException sqe) { throw new DBException("Get Group GroupeList", sqe); } finally { if (rs != null) { try { rs.close(); } catch (Throwable t) { } } if (stmt != null) { try { stmt.close(); } catch (Throwable t) { } } DBConnection.release(dbc); } /* return list */ return usrList; }
public String toString() { StringBuffer sb = new StringBuffer(); /* standard event fields */ int sc = this.getStatusCode(); sb.append("Event values:\n"); sb.append(" DeviceID : " + this.getAccountID() + "/" + this.getDeviceID() + "\n"); sb.append(" UniqueID : " + this.getUniqueID() + "\n"); sb.append( " Fixtime : " + this.getTimestamp() + " [" + new DateTime(this.getTimestamp()) + "]\n"); sb.append( " StatusCode: [" + StatusCodes.GetHex(sc) + "] " + StatusCodes.GetDescription(sc, null)); sb.append(" GPS : " + this.getGeoPoint() + " [age " + this.getGpsAge() + " sec]\n"); sb.append( " SpeedKPH : " + StringTools.format(this.getSpeedKPH(), "0.0") + " [" + this.getHeading() + "]\n"); /* remaining event fields (not already displayed) */ OrderedSet<?> fldn = new OrderedSet<Object>(this.fieldValues.getPropertyKeys()); fldn.remove(EventData.FLD_timestamp); fldn.remove(EventData.FLD_statusCode); fldn.remove(EventData.FLD_latitude); fldn.remove(EventData.FLD_longitude); fldn.remove(EventData.FLD_gpsAge); fldn.remove(EventData.FLD_speedKPH); fldn.remove(EventData.FLD_heading); for (Object k : fldn) { Object v = this.fieldValues.getProperty(k, "?"); sb.append(" "); sb.append(StringTools.leftAlign(k.toString(), 10)).append(": "); sb.append(v.toString()).append("\n"); } /* alternate fields */ if (this.otherValues != null) { for (String k : this.otherValues.keySet()) { String v = StringTools.trim(this.otherValues.get(k)); sb.append(" "); sb.append(StringTools.leftAlign(k, 10)).append(": "); sb.append(v).append("\n"); } } /* return string */ return sb.toString(); }
public void setGeozoneID(String gzid) { if (!StringTools.isBlank(gzid)) { this.fieldValues.setString(EventData.FLD_geozoneID, gzid); } else { this.fieldValues.removeProperty(EventData.FLD_geozoneID); } }
/* set Role access level */ public static void setAccessLevel(Role role, String aclId, AccessLevel level) throws DBException { /* role specified? */ if (role == null) { throw new DBException("Role not specified."); } String acctId = role.getAccountID(); String roleId = role.getRoleID(); /* acl-id specified? */ if (StringTools.isBlank(aclId)) { throw new DBException("Acl-ID not specified."); } /* get/create role */ RoleAcl roleAcl = null; RoleAcl.Key aclKey = new RoleAcl.Key(acctId, roleId, aclId); if (aclKey.exists()) { // may throw DBException roleAcl = RoleAcl.getRoleAcl(role, aclId); // may throw DBException } else { roleAcl = aclKey.getDBRecord(); roleAcl.setRole(role); } /* set access level */ int levelInt = (level != null) ? level.getIntValue() : AccessLevel.NONE.getIntValue(); roleAcl.setAccessLevel(levelInt); /* save */ roleAcl.save(); // may throw DBException }
/* get/create device list entry */ public static GroupList getGroupList(User user, String groupID, boolean createOK) throws DBException { // does not return null, if 'createOK' is true /* User specified? */ if (user == null) { throw new DBException("User not specified."); } String accountID = user.getAccountID(); String userID = user.getUserID(); /* group exists? */ if (StringTools.isBlank(groupID)) { throw new DBException("DeviceGroup ID not specified."); } else if (!DeviceGroup.exists(accountID, groupID)) { throw new DBException("DeviceGroup does not exist: " + accountID + "/" + groupID); } /* create/save record */ GroupList.Key grpListKey = new GroupList.Key(accountID, userID, groupID); if (grpListKey.exists()) { // may throw DBException // already exists GroupList listItem = grpListKey.getDBRecord(true); listItem.setUser(user); return listItem; } else if (createOK) { GroupList listItem = grpListKey.getDBRecord(); listItem.setCreationDefaultValues(); listItem.setUser(user); return listItem; } else { // record doesn't exist, and caller doesn't want us to create it return null; } }
/* set Role access level */ public static boolean deleteAccessLevel(Role role, String aclId) throws DBException { /* role specified? */ if (role == null) { return false; // quietly ignore } String acctId = role.getAccountID(); String roleId = role.getRoleID(); /* acl-id specified? */ if (StringTools.isBlank(aclId)) { return false; // quietly ignore } /* already deleted? */ boolean aclExists = RoleAcl.exists(acctId, roleId, aclId); if (!aclExists) { return false; } /* delete */ RoleAcl.Key aclKey = new RoleAcl.Key(acctId, roleId, aclId); aclKey.delete(true); // also delete dependencies return true; }
/* encode "type=<type> ..." into long value */ public static long EncodeFault(String faultProps) { if (!StringTools.isBlank(faultProps)) { return DTOBDFault.EncodeFault(new RTProperties(faultProps)); } else { return 0L; } }
public void setFieldValue(String fldName, Object fldVal) { if (!StringTools.isBlank(fldName) && (fldVal != null)) { if (USE_ALTERNATE_FIELD_MAP) { this.getAlternateFieldMap().put(fldName, fldVal); } else { this.fieldValues.setProperty(fldName, fldVal); } } }
public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); InitJ1587DescriptionProvider(); RTProperties cmdLineProps = RTConfig.getCommandLineProperties(); long fault = EncodeFault(cmdLineProps); Print.sysPrintln("Fault : " + fault + " [0x" + StringTools.toHexString(fault) + "]"); Print.sysPrintln("String: " + GetPropertyString(fault)); Print.sysPrintln("Desc : " + GetFaultDescription(fault, null)); }
/* Return specified StatusCode, create if specified */ private static StatusCode _getStatusCode( String accountID, Account account, String deviceID, int code, boolean createOK) throws DBException { // does not return null if 'createOK' is true /* account-id specified? */ if (StringTools.isBlank(accountID)) { if (account == null) { throw new DBException("Account not specified."); } else { accountID = account.getAccountID(); } } else if ((account != null) && !account.getAccountID().equals(accountID)) { throw new DBException("Account does not match specified AccountID."); } /* device-id specified? */ if (StringTools.isBlank(deviceID)) { // throw new DBException("Device-ID not specified."); deviceID = ALL_DEVICES; } /* get/create entity */ StatusCode.Key scKey = new StatusCode.Key(accountID, deviceID, code); if (scKey.exists()) { // may throw DBException StatusCode sc = scKey.getDBRecord(true); if (account != null) { sc.setAccount(account); } return sc; } else if (createOK) { StatusCode sc = scKey.getDBRecord(); if (account != null) { sc.setAccount(account); } sc.setCreationDefaultValues(); return sc; // not yet saved! } else { // record doesn't exist, and caller doesn't want us to create it return null; } }
public static String GetPropertyString_OBDII(String dtcStr) { StringBuffer sb = new StringBuffer(); sb.append(PROP_TYPE[0]).append("=").append(NAME_OBDII); sb.append(" "); if (!StringTools.isBlank(dtcStr)) { sb.append(PROP_MIL[0]).append("=").append("1"); sb.append(" "); sb.append(PROP_DTC[0]).append("=").append(dtcStr); } else { sb.append(PROP_MIL[0]).append("=").append("0"); } return sb.toString(); }
/* Return status code description (used by RuleInfo, RequestProperties) */ public static String getDescription( String accountID, int statusCode, BasicPrivateLabel pl, String dftDesc) { /* custom code (record) */ StatusCode code = StatusCode.findStatusCode(accountID, null, statusCode); if (code != null) { return code.getDescription(); } /* default */ if (!StringTools.isBlank(dftDesc)) { return dftDesc; } else { return StatusCodes.GetDescription(statusCode, pl); } }
/* Return status code description */ public static String getDescription( Device device, int statusCode, BasicPrivateLabel bpl, String dftDesc) { /* device code */ if (device != null) { StatusCode code = device.getStatusCode(statusCode); if (code != null) { return code.getDescription(); } } /* default */ if (!StringTools.isBlank(dftDesc)) { return dftDesc; } else { return StatusCodes.GetDescription(statusCode, bpl); } }
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; } } }
/* return Role access level */ public static AccessLevel getAccessLevel(Role role, String aclId, AccessLevel dftAccess) { if (role == null) { return dftAccess; } else if (StringTools.isBlank(aclId)) { return dftAccess; } else { try { RoleAcl roleAcl = RoleAcl.getRoleAcl(role, aclId); // may throw DBException if (roleAcl != null) { return RoleAcl.getAccessLevel(roleAcl); } else { return dftAccess; } } catch (DBException dbe) { // error occurred return AccessLevel.NONE; } } }
/* Return specified role ACL, create if specified */ public static RoleAcl getRoleAcl(Role role, String aclId, boolean create) throws DBException { // does not return null /* role specified? */ if (role == null) { throw new DBNotFoundException("Role not specified."); } String acctId = role.getAccountID(); String roleId = role.getRoleID(); /* acl-id specified? */ if (StringTools.isBlank(aclId)) { throw new DBNotFoundException("Acl-ID not specified."); } /* get/create role */ RoleAcl roleAcl = null; RoleAcl.Key aclKey = new RoleAcl.Key(acctId, roleId, aclId); if (!aclKey.exists()) { // may throw DBException if (create) { roleAcl = aclKey.getDBRecord(); roleAcl.setRole(role); roleAcl.setCreationDefaultValues(); return roleAcl; // not yet saved! } else { throw new DBNotFoundException("Acl-ID does not exists '" + aclKey + "'"); } } else if (create) { // we've been asked to create the Acl, and it already exists throw new DBAlreadyExistsException("Acl-ID already exists '" + aclKey + "'"); } else { roleAcl = RoleAcl.getRoleAcl(role, aclId); // may throw DBException if (roleAcl == null) { throw new DBException("Unable to read existing Role-ID '" + aclKey + "'"); } return roleAcl; } }
/* create a new StatusCode */ public static StatusCode createNewStatusCode(Account account, String deviceID, int code) throws DBException { /* invalid account */ if (account == null) { throw new DBException("Invalid/Null Account specified"); } /* invalid code */ if ((code < 0) || (code > 0xFFFF)) { throw new DBException("Invalid StatusCode specified"); } /* default to 'ALL' devices */ if (StringTools.isBlank(deviceID)) { deviceID = ALL_DEVICES; } /* create status code */ StatusCode sc = StatusCode.getStatusCode(account, deviceID, code, true); // does not return null sc.save(); return sc; }
/** * ** Encodes this DBRecordKey into XML ** @param sb The StringBuffer to which the DBRecord XML is * writen ** @param indent The number of spaces to indent ** @param sequence An optional record * sequence number ** @param soapXML True for SOAP XML ** @return The StringBuffer */ public StringBuffer toXML(StringBuffer sb, int indent, int sequence, boolean soapXML) { if (sb == null) { sb = new StringBuffer(); } String prefix = StringTools.replicateString(" ", indent); DBRecordKey<gDBR> recKey = this; String tableName = recKey.getTableName(); DBField fld[] = recKey.getKeyFields(); // KEY fields DBFieldValues fldVals = recKey.getFieldValues(); String PFX1 = XMLTools.PREFIX(soapXML, indent); sb.append(PFX1); sb.append( XMLTools.startTAG( soapXML, DBFactory.TAG_RecordKey, XMLTools.ATTR(DBFactory.ATTR_table, tableName) + ((sequence > 0) ? XMLTools.ATTR(DBFactory.ATTR_sequence, sequence) : ""), false, true)); DBFactory.writeXML_DBFields(sb, 2 * indent, fld, fldVals, soapXML); sb.append(PFX1); sb.append(XMLTools.endTAG(soapXML, DBFactory.TAG_RecordKey, true)); return sb; }
public boolean insertEventData() { /* valid device? */ if (this.device == null) { return false; } /* debug message */ if (RTConfig.isDebugMode()) { Print.logDebug("Inserting EventData ...\n" + this.toString()); } /* EventData key */ String acctID = this.device.getAccountID(); String devID = this.device.getDeviceID(); long fixtime = this.getTimestamp(); int statusCode = this.getStatusCode(); EventData.Key evKey = new EventData.Key(acctID, devID, fixtime, statusCode); EventData evdb = evKey.getDBRecord(); /* set EventData field values */ if (USE_EVENTDATA_SETVALUE) { for (Object fldn : this.fieldValues.getPropertyKeys()) { if (fldn.equals(EventData.FLD_timestamp)) { continue; // already set above } else if (fldn.equals(EventData.FLD_statusCode)) { continue; // already set above } Object fldv = this.fieldValues.getProperty(fldn, null); if (fldv != null) { evdb.setValue((String) fldn, fldv); // attempts to use "setter" methods } } } else { if (this.hasLatitude()) { evdb.setLatitude(this.getLatitude()); } if (this.hasLongitude()) { evdb.setLongitude(this.getLongitude()); } if (this.hasGpsAge()) { evdb.setGpsAge(this.getGpsAge()); } if (this.hasHDOP()) { evdb.setHDOP(this.getHDOP()); } if (this.hasSatelliteCount()) { evdb.setSatelliteCount(this.getSatelliteCount()); } if (this.hasSpeedKPH()) { evdb.setSpeedKPH(this.getSpeedKPH()); } if (this.hasHeading()) { evdb.setHeading(this.getHeading()); } if (this.hasAltitude()) { evdb.setAltitude(this.getAltitude()); } if (this.hasInputMask()) { evdb.setInputMask(this.getInputMask()); } if (this.hasBatteryLevel()) { evdb.setBatteryLevel(this.getBatteryLevel()); } if (this.hasSignalStrength()) { evdb.setSignalStrength(this.getSignalStrength()); } if (this.hasOdometerKM()) { evdb.setOdometerKM(this.getOdometerKM()); } if (this.hasEngineHours()) { evdb.setEngineHours(this.getEngineHours()); } if (this.hasPtoHours()) { evdb.setPtoHours(this.getPtoHours()); } if (this.hasFuelTotal()) { evdb.setFuelTotal(this.getFuelTotal()); } if (this.hasGeozoneID()) { evdb.setGeozoneID(this.getGeozoneID()); } } /* other fields (if available) */ if (this.otherValues != null) { for (String fldn : this.otherValues.keySet()) { if (fldn.equals(EventData.FLD_timestamp)) { continue; } else if (fldn.equals(EventData.FLD_statusCode)) { continue; } Object fldv = this.otherValues.get(fldn); if (fldv != null) { evdb.setValue(fldn, fldv); // attempts to use "setter" methods } } } /* insert event */ // this will display an error if it was unable to store the event Print.logInfo( "Event : [0x" + StringTools.toHexString(statusCode, 16) + "] " + StatusCodes.GetDescription(statusCode, null)); this.device.insertEventData( evdb); // FLD_lastValidLatitude,FLD_lastValidLongitude,FLD_lastGPSTimestamp,FLD_lastOdometerKM this.eventTotalCount++; return true; }
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(); } }
private void setGroupID(String v) { this.setFieldValue(FLD_groupID, StringTools.trim(v)); }
public String getGroupID() { String v = (String) this.getFieldValue(FLD_groupID); return StringTools.trim(v); }
/** * ** 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 the 'WHERE' clause for this key [CHECK] ** @param altIndexName The alternate index * name. If null or blank, uses ** primary keys instead ** @param whereKeyType The where key type. * One of the constants from DBWhere ** @return The 'WHERE' clause for this key */ protected String _getWhereClause( String altIndexName, int whereKeyType) // boolean fullKeyRequired) throws DBException { /* key fields */ boolean usePrimaryKey = StringTools.isBlank(altIndexName); DBField keyFlds[] = usePrimaryKey ? this.getKeyFields() : this.getAltKeyFields(altIndexName); if (ListTools.isEmpty(keyFlds)) { throw new DBException("No keys found!"); } /* WHERE */ DBWhere dwh = new DBWhere(this.getFactory()); DBFieldValues fldVals = this.getFieldValues(); int keyCnt = 0; boolean hasPartialKey = false; for (int i = 0; i < keyFlds.length; i++) { String fldName = keyFlds[i].getName(); if (fldVals.hasFieldValue(fldName)) { if (!hasPartialKey || (whereKeyType == DBWhere.KEY_PARTIAL_ALL)) { String fev = dwh.EQ(fldName, fldVals.getFieldValueAsString(fldName)); if (keyCnt > 0) { dwh.append(dwh.AND_(fev)); } else { dwh.append(fev); } keyCnt++; } else { // whereKeyType == DBWhere.KEY_PARTIAL_FIRST, and we found a subsequent key String m = "Additional partial key in 'WHERE' clause! [" + this.getTableName() + "." + fldName + "]"; // throw new DBException(m); // TODO: Print.logWarn("******************************************************************"); Print.logWarn(m); // Print.logWarn(StringTools.join(keyFlds,",")); // Print.logStackTrace(m); Print.logWarn("******************************************************************"); } } else if ((i == 0) && (whereKeyType != DBWhere.KEY_PARTIAL_ALL_EMPTY)) { // // missing first key if (keyFlds[i].isAutoIncrement()) { // first key is an "auto_increment" and it is not present // assume that we are expecting the DB server to create this value for us, thus the key // dow not exist // However, there is nothing we can do about this here. String m = "First key field for 'WHERE' clause is 'auto_increment' and field is not present [" + this.getTableName() + "." + fldName + "]"; throw new DBException(m); } else { String m = "Missing first key field for 'WHERE' clause! [" + this.getTableName() + "." + fldName + "]"; throw new DBException(m); } } else if (whereKeyType == DBWhere.KEY_FULL) { // missing a key when all keys are required String m = "Missing key for 'WHERE' clause! [" + this.getTableName() + "." + fldName + "]"; throw new DBException(m); } else { // only a portion of the key has been specified. // This is a common occurance deleting an Account/Device with sub-dependencies // Print.logWarn("Key field not specified: " + this.getTableName() + "." + fldName); hasPartialKey = true; } } return (keyCnt > 1) ? dwh.WHERE(dwh.toString()) : dwh.WHERE_(dwh.toString()); }