Пример #1
0
  /* start UDP listener */
  private ServerSocketThread _startUDP(int port) throws Throwable {
    ServerSocketThread sst = null;

    /* create server socket */
    try {
      sst = new ServerSocketThread(ServerSocketThread.createDatagramSocket(port));
    } catch (Throwable t) { // trap any server exception
      Print.logException("ServerSocket error", t);
      throw t;
    }

    /* initialize */
    sst.setTextPackets(Constants.ASCII_PACKETS);
    sst.setBackspaceChar(null); // no backspaces allowed
    sst.setLineTerminatorChar(Constants.ASCII_LINE_TERMINATOR);
    sst.setIgnoreChar(Constants.ASCII_IGNORE_CHARS);
    sst.setMaximumPacketLength(Constants.MAX_PACKET_LENGTH);
    sst.setMinimumPacketLength(Constants.MIN_PACKET_LENGTH);
    sst.setIdleTimeout(TrackServer.udpTimeout_idle);
    sst.setPacketTimeout(TrackServer.udpTimeout_packet);
    sst.setSessionTimeout(TrackServer.udpTimeout_session);
    sst.setTerminateOnTimeout(Constants.TERMINATE_ON_TIMEOUT);
    sst.setClientPacketHandlerClass(TrackClientPacketHandler.class);

    /* start thread */
    Print.logInfo(
        "Starting UDP listener thread on port "
            + port
            + " [timeout="
            + sst.getSessionTimeout()
            + "ms] ...");
    sst.start();
    this.udpThread.add(sst);
    return sst;
  }
Пример #2
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));
 }
Пример #3
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;
  }
Пример #4
0
 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;
 }
Пример #5
0
 private static void usage() {
   Print.logInfo("Usage:");
   Print.logInfo("  java ... " + StatusCode.class.getName() + " {options}");
   Print.logInfo("Options:");
   Print.logInfo("  -account=<id>   Account ID owning StatusCode");
   Print.logInfo("  -device=<id>    Device ID owning StatusCode (use '/' for ALL)");
   Print.logInfo("  -code=<id>      StatusCode to create/delete/edit");
   Print.logInfo("  -create         Create a new StatusCode");
   Print.logInfo("  -edit           To edit an existing StatusCode");
   Print.logInfo("  -delete         Delete specified StatusCode");
   System.exit(1);
 }
Пример #6
0
  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;
  }
Пример #7
0
  /* 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!");
    }
  }
Пример #8
0
 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;
     }
   }
 }
Пример #9
0
  /* start TCP listener */
  private void _startTCP(int port) throws Throwable {
    ServerSocketThread sst = null;

    /* create server socket */
    try {
      sst = new ServerSocketThread(port);
    } catch (Throwable t) { // trap any server exception
      Print.logException("ServerSocket error", t);
      throw t;
    }

    /* initialize */
    sst.setTextPackets(Constants.ASCII_PACKETS);
    sst.setBackspaceChar(null); // no backspaces allowed
    sst.setLineTerminatorChar(Constants.ASCII_LINE_TERMINATOR);
    sst.setIgnoreChar(Constants.ASCII_IGNORE_CHARS);
    sst.setMaximumPacketLength(Constants.MAX_PACKET_LENGTH);
    sst.setMinimumPacketLength(Constants.MIN_PACKET_LENGTH);
    sst.setIdleTimeout(TrackServer.tcpTimeout_idle); // time between packets
    sst.setPacketTimeout(
        TrackServer.tcpTimeout_packet); // time from start of packet to packet completion
    sst.setSessionTimeout(TrackServer.tcpTimeout_session); // time for entire session
    sst.setTerminateOnTimeout(Constants.TERMINATE_ON_TIMEOUT);
    sst.setClientPacketHandlerClass(TrackClientPacketHandler.class);
    sst.setLingerTimeoutSec(Constants.LINGER_ON_CLOSE_SEC);

    /* start thread */
    Print.logInfo(
        "Starting TCP listener thread on port "
            + port
            + " [timeout="
            + sst.getSessionTimeout()
            + "ms] ...");
    sst.start();
    this.tcpThread.add(sst);
  }
Пример #10
0
 public boolean updateDevice() {
   if (this.device != null) {
     /* save device changes */
     try {
       // TODO: check "this.device" vs "this.dataXPort"
       this.device.updateChangedEventFields();
       return true;
     } catch (DBException dbe) {
       Print.logException(
           "Unable to update Device: " + this.getAccountID() + "/" + this.getDeviceID(), dbe);
     } finally {
       //
     }
   }
   return false;
 }
Пример #11
0
  /**
   * ** 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;
  }
Пример #12
0
 public static boolean InitJ1587DescriptionProvider() {
   if (!j1587DidInit) {
     j1587DidInit = true;
     try {
       j1587GetDescription =
           new MethodAction(
               PACKAGE_EXTRA_DBTOOLS_ + "J1587", "GetJ1587Description", Properties.class);
       j1587DescProvider =
           new DTOBDFault.J1587DescriptionProvider() {
             public Properties getJ1587Descriptions(long fault) {
               if (DTOBDFault.IsJ1708(fault)) {
                 int mid = DTOBDFault.DecodeSystem(fault); // MID
                 boolean isSid = DTOBDFault.IsJ1708_SID(fault);
                 int pidSid = DTOBDFault.DecodePidSid(fault); // PID|SID "128/[s]123/1"
                 int fmi = DTOBDFault.DecodeFMI(fault); // FMI
                 Properties p = new Properties();
                 p.setProperty("MID", String.valueOf(mid));
                 p.setProperty((isSid ? "SID" : "PID"), String.valueOf(pidSid));
                 p.setProperty("FMI", String.valueOf(fmi));
                 try {
                   return (Properties) j1587GetDescription.invoke(p);
                 } catch (Throwable th) {
                   return null;
                 }
               } else {
                 return null;
               }
             }
           };
       Print.logDebug("J1587 Description Provider installed ...");
     } catch (Throwable th) {
       // Print.logException("J1587 Description Provider NOT installed!", th);
     }
   }
   return (j1587DescProvider != null);
 }
Пример #13
0
  /**
   * ** Gets the DBRecord associated with this key ** @param reload If the record should be reloaded
   * before it is returned ** @return The DBRecord associated with this key
   */
  public gDBR getDBRecord(boolean reload) {
    // returns null if there is an error

    /* create record */
    if (this.record == null) {
      try {
        this.record = DBRecord._createDBRecord(this);
      } catch (DBException dbe) {
        // Implementation error (this should never occur)
        // an NPE will likely follow
        Print.logStackTrace("Implementation error - cant' create DB record", dbe);
        return null;
      }
    }

    /* reload */
    if (reload) {
      // 'reload' is ignored if key does not exist
      this.record.reload();
    }

    /* return record (never null) */
    return this.record;
  }
Пример #14
0
  /**
   * ** 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());
  }
Пример #15
0
  /**
   * ** 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;
  }
Пример #16
0
  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();
    }
  }
Пример #17
0
  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();
    }
  }
Пример #18
0
  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;
  }
Пример #19
0
 private static void usage() {
   Print.logInfo("Usage:");
   Print.logInfo("  java ... " + RoleAcl.class.getName() + " {options}");
   Print.logInfo("Common Options:");
   Print.logInfo("  -account=<id>   Acount ID which owns Role");
   Print.logInfo("  -role=<id>      Role ID which owns RoleAcl");
   Print.logInfo("  -list           List Acls for Role");
   Print.logInfo("  -acl=<id>       Role ID to create/edit");
   Print.logInfo("  -set=<val>      RoleAcl value (create if necessary)");
   Print.logInfo("  -create         Create a new RoleAcl");
   Print.logInfo("  -edit           Edit an existing (or newly created) RoleAcl");
   Print.logInfo("  -delete         Delete specified RoleAcl");
   System.exit(1);
 }