Ejemplo n.º 1
0
 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;
     }
   }
 }
Ejemplo n.º 2
0
  /* 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;
  }
Ejemplo n.º 3
0
  // [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;
  }
Ejemplo n.º 4
0
 /* 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;
     }
   }
 }
Ejemplo n.º 5
0
  /* 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;
  }
Ejemplo n.º 6
0
  /**
   * ** 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;
  }
Ejemplo n.º 7
0
 public static String XmlFilter(boolean isSoapReq, String value) {
   if ((value == null)
       || value.equals("")) { // do not use StringTools.isBlank (spaces are significant)
     return "";
   } else if (StringTools.isAlphaNumeric(value, XML_CHARS)) {
     return value; // return all significant spaces
   } else {
     String v = StringTools.replace(value, "\n", "\\n");
     return XMLTools.CDATA(isSoapReq, v);
   }
 }
Ejemplo n.º 8
0
  /* 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;
  }
Ejemplo n.º 9
0
 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);
 }
Ejemplo n.º 10
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;
  }
Ejemplo n.º 11
0
  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();
  }
Ejemplo n.º 12
0
 /**
  * ** Writes the specified line to the specified socket's output stream ** @param socket The
  * socket which's output stream to write to ** @param val The line to write to the socket output
  * stream. A newline is ** appended if it does not already end with one. ** @throws IOException if
  * an error occurs
  */
 protected static void socketWriteLine(Socket socket, String val) throws IOException {
   if (val != null) {
     String lineTerm = ClientSocketThread.getLineTerminator();
     String v = val.endsWith(lineTerm) ? val : (val + lineTerm);
     ClientSocketThread.socketWriteBytes(socket, StringTools.getBytes(v), 0, -1);
   }
 }
Ejemplo n.º 13
0
  public void addDataSet(Color color, String legend, Data data[]) throws Exception {

    /* init */
    this._initChart();

    /* dataset color/legend/markers */
    String hexColor = ColorTools.toHexString(color, false);
    this.addDatasetColor(hexColor);
    this.addDatasetLegend(legend);
    this.addShapeMarker("d," + hexColor + "," + this.dataSetCount + ",-1,7,1");

    /* data */
    StringBuffer xv = new StringBuffer();
    StringBuffer yv = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
      GetScaledExtendedEncodedValue(yv, data[i].getTempC(), this.minTempC, this.maxTempC);
      GetScaledExtendedEncodedValue(xv, data[i].getTimestamp(), this.minDateTS, this.maxDateTS);
    }
    if (StringTools.isBlank(this.chd)) {
      this.chd = "e:";
    } else {
      this.chd += ",";
    }
    this.chd += xv.toString() + "," + yv.toString();

    /* count data set */
    this.dataSetCount++;
  }
Ejemplo n.º 14
0
 public GoogleSig getSignature() {
   if (!this.signature_init) {
     this.signature_init = true;
     String key = this.getAuthorization();
     if (!StringTools.isBlank(key) && key.startsWith(CLIENT_ID_PREFIX)) {
       String sigKey = this.getProperties().getString(PROP_signatureKey, "");
       if (!StringTools.isBlank(sigKey)) {
         Print.logWarn("Setting SignatureKey: " + sigKey);
         this.signature = new GoogleSig(sigKey);
       } else {
         Print.logWarn("No signatureKey ...");
       }
     }
   }
   return this.signature;
 }
Ejemplo n.º 15
0
 /* 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;
   }
 }
Ejemplo n.º 16
0
 private String getAddressReverseGeocodeURL(GeoPoint gp) {
   //  -
   // http://nominatim.openstreetmap.org/reverse?format=xml&addressdetails=1&zoom=18&lat=46.17330&lon=21.29370
   StringBuffer sb = new StringBuffer();
   RTProperties rtp = this.getProperties();
   String url = rtp.getString(PROP_reverseURL, null);
   if (!StringTools.isBlank(url)) {
     sb.append(url);
   } else {
     String host = rtp.getString(PROP_hostName, HOST_PRIMARY);
     sb.append("http://");
     sb.append(host);
     if (host.indexOf("mapquest") >= 0) {
       sb.append("/nominatim/v1/reverse?");
     } else {
       sb.append("/reverse?");
     }
   }
   sb.append("format=xml&");
   sb.append("limit=1&");
   // sb.append("osm_type=W&");
   sb.append("addressdetails=").append(rtp.getString(PROP_addressdetails, "1")).append("&"); // 0,1
   sb.append("zoom=").append(rtp.getString(PROP_zoom, "18")).append("&"); // 0..18
   sb.append("email=").append(this.getEmail()).append("&"); // required, per usage policy
   sb.append("lat=").append(gp.getLatitudeString(GeoPoint.SFORMAT_DEC_5, null)).append("&");
   sb.append("lon=").append(gp.getLongitudeString(GeoPoint.SFORMAT_DEC_5, null));
   return sb.toString();
 }
Ejemplo n.º 17
0
  /* 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;
  }
Ejemplo n.º 18
0
 public void setGeozoneID(String gzid) {
   if (!StringTools.isBlank(gzid)) {
     this.fieldValues.setString(EventData.FLD_geozoneID, gzid);
   } else {
     this.fieldValues.removeProperty(EventData.FLD_geozoneID);
   }
 }
Ejemplo n.º 19
0
  /* 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;
    }
  }
Ejemplo n.º 20
0
  /* 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
  }
Ejemplo n.º 21
0
 private String getEmail() {
   RTProperties rtp = this.getProperties();
   String email = rtp.getString(PROP_email, null);
   if (StringTools.isBlank(email)) {
     email = SendMail.getUserFromEmailAddress();
   }
   return email;
 }
Ejemplo n.º 22
0
  /** ** 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();
  }
Ejemplo n.º 23
0
 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));
 }
Ejemplo n.º 24
0
 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);
     }
   }
 }
Ejemplo n.º 25
0
  /** ** Gets the SMSoutboubdGateway for the specified name */
  public static SMSOutboundGateway GetSMSGateway(String name) {

    /* get handler */
    if (StringTools.isBlank(name)) {
      return null;
    } else {
      return SmsGatewayHandlerMap.get(name.toLowerCase());
    }
  }
Ejemplo n.º 26
0
  /* 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;
    }
  }
Ejemplo n.º 27
0
  /* write JS to stream */
  public void writeJavaScript(PrintWriter out, RequestProperties reqState) throws IOException {

    /* prefetch map "Loading" image */
    if (this.getProperties().getBoolean(PROP_MAP_LOADING, false)) {
      String mapLoadingImageURI = this.getProperties().getString(PROP_MAP_LOADING_IMAGE, null);
      if (!StringTools.isBlank(mapLoadingImageURI)) {
        out.write("<link rel=\"prefetch\" href=\"" + mapLoadingImageURI + "\">\n");
      }
    }

    /* JSMap variables */
    JavaScriptTools.writeStartJavaScript(out);
    this.writeJSVariables(out, reqState);
    JavaScriptTools.writeEndJavaScript(out);

    /* Subclass JavaScript includes */
    // links to MapProvider support are written by the subclass here
    this.writeJSIncludes(out, reqState);

    /* JSMap Custom included JavaScript */
    String jsMapURLs[] =
        StringTools.parseStringArray(this.getProperties().getString(PROP_javascript_src, ""), '\n');
    this.writeJSIncludes(out, reqState, jsMapURLs);

    /* JSMap Custom inline JavaScript */
    String jsMapInline =
        StringTools.trim(this.getProperties().getString(PROP_javascript_inline, null));
    if (!StringTools.isBlank(jsMapInline)) {
      JavaScriptTools.writeStartJavaScript(out);
      out.write("// --- Inline Javascript [" + this.getName() + "]\n");
      out.write(jsMapInline);
      out.write("\n");
      JavaScriptTools.writeEndJavaScript(out);
    }

    /* event CSV parsing code */
    JavaScriptTools.writeStartJavaScript(out);
    out.write(EventUtil.getInstance().getParseMapEventJS(reqState.isFleet(), reqState.getLocale()));
    JavaScriptTools.writeEndJavaScript(out);
  }
 public static String getErrorDescription(int errCode) {
   switch (errCode) {
     case NAK_OK:
       return "OK";
     case NAK_ID_INVALID:
       return "Invalid unique ID";
     case NAK_ACCOUNT_INVALID:
       return "Invalid account ID";
     case NAK_ACCOUNT_INACTIVE:
       return "Account inactive";
     case NAK_ACCOUNT_ERROR:
       return "Account error";
     case NAK_DEVICE_INVALID:
       return "Invalid device ID";
     case NAK_DEVICE_INACTIVE:
       return "Device inactive";
     case NAK_DEVICE_ERROR:
       return "Device error";
     case NAK_EXCESSIVE_CONNECTIONS:
       return "Excessive connections";
     case NAK_PACKET_HEADER:
       return "Invalid packet header";
     case NAK_PACKET_TYPE:
       return "Invalid packet type";
     case NAK_PACKET_LENGTH:
       return "Invalid packet length";
     case NAK_PACKET_PAYLOAD:
       return "Invalid packet payload";
     case NAK_PACKET_ENCODING:
       return "Unsupported packet encoding";
     case NAK_PACKET_CHECKSUM:
       return "Invalid packet checksum";
     case NAK_BLOCK_CHECKSUM:
       return "Invalid block checksum";
     case NAK_PROTOCOL_ERROR:
       return "Protocol error";
     case NAK_FORMAT_DEFINITION_INVALID:
       return "Invalid custom format definition";
     case NAK_FORMAT_NOT_SUPPORTED:
       return "Custom formats not supported";
     case NAK_FORMAT_NOT_RECOGNIZED:
       return "Custom format not recognized";
     case NAK_EXCESSIVE_EVENTS:
       return "Excessive events";
     case NAK_DUPLICATE_EVENT:
       return "Duplicate event";
     case NAK_EVENT_ERROR:
       return "Event error";
     default:
       return "Unknown [" + StringTools.toHexString(errCode, 16) + "]";
   }
 }
Ejemplo n.º 29
0
 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();
 }
Ejemplo n.º 30
0
 /* validate the syntax of the specified single email address */
 public static boolean validateAddress(String addr) {
   if (StringTools.isBlank(addr)) {
     // blanks not alowed here
     return false; // fail quickly
   } else {
     try {
       return SendMail.validateAddress(addr);
     } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException
       // this will fail if JavaMail support for SendMail is not available.
       Print.logWarn("SendMail error: " + t);
       return false;
     }
   }
 }