Esempio n. 1
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;
  }
Esempio n. 2
0
 /** ** Returns an OrderedMap of defined primary keys ** @return map of defined primary keys */
 public Map<DBField, Object> getKeyMap() {
   Map<DBField, Object> keyMap = new OrderedMap<DBField, Object>(); // ordered key list
   if (this.dbFactory != null) {
     DBField keyField[] = this.dbFactory.getKeyFields();
     for (int i = 0; i < keyField.length; i++) {
       String key = keyField[i].getName();
       Object val = null;
       if (this.dbRecord != null) {
         // all key values will be defined
         val = this.dbRecord.getFieldValue(key);
       } else {
         // use parent keys
         DBFactoryTree parent = this.getParentNode();
         for (; (parent != null) && (val == null); parent = parent.getParentNode()) {
           DBRecord dbr = parent.getDBRecord();
           if (dbr == null) {
             // stop at the first undefined ancestor
             break;
           } else if (dbr.hasField(key)) {
             // try getting key value from ancestor
             DBField parFld = dbr.getField(key);
             if ((parFld != null) && parFld.isPrimaryKey()) {
               // primary key fields only
               val = dbr.getFieldValue(key);
             }
           }
         }
       }
       // save key DBField and value
       if (val != null) {
         keyMap.put(keyField[i], val);
       } else {
         keyMap.put(keyField[i], null);
       }
     }
   }
   return keyMap;
 }
Esempio n. 3
0
public class GroupList extends UserRecord<GroupList> {

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // SQL table definition below

  /* table name */
  public static final String _TABLE_NAME = "GroupList";

  public static String TABLE_NAME() {
    return DBProvider._translateTableName(_TABLE_NAME);
  }

  /* field definition */
  public static final String FLD_userID = User.FLD_userID;
  public static final String FLD_groupID = DeviceGroup.FLD_groupID;
  private static DBField FieldInfo[] = {
    // GroupList fields
    newField_accountID(true),
    newField_userID(true),
    new DBField(FLD_groupID, String.class, DBField.TYPE_GROUP_ID(), "Device Group ID", "key=true"),
    // Common fields
    // newField_lastUpdateTime(),
    // newField_lastUpdateUser(true),
    newField_creationTime(),
  };

  /* key class */
  public static class Key extends UserKey<GroupList> {
    public Key() {
      super();
    }

    public Key(String accountId, String userId, String groupId) {
      super.setFieldValue(FLD_accountID, ((accountId != null) ? accountId.toLowerCase() : ""));
      super.setFieldValue(FLD_userID, ((userId != null) ? userId.toLowerCase() : ""));
      super.setFieldValue(FLD_groupID, ((groupId != null) ? groupId.toLowerCase() : ""));
    }

    public DBFactory<GroupList> getFactory() {
      return GroupList.getFactory();
    }
  }

  /* factory constructor */
  private static DBFactory<GroupList> factory = null;

  public static DBFactory<GroupList> getFactory() {
    if (factory == null) {
      factory =
          DBFactory.createDBFactory(
              GroupList.TABLE_NAME(),
              GroupList.FieldInfo,
              DBFactory.KeyType.PRIMARY,
              GroupList.class,
              GroupList.Key.class,
              true /*editable*/,
              true /*viewable*/);
      factory.addParentTable(Account.TABLE_NAME());
      factory.addParentTable(User.TABLE_NAME());
      factory.addParentTable(DeviceGroup.TABLE_NAME());
    }
    return factory;
  }

  /* Bean instance */
  public GroupList() {
    super();
  }

  /* database record */
  public GroupList(GroupList.Key key) {
    super(key);
  }

  // ------------------------------------------------------------------------

  /* table description */
  public static String getTableDescription(Locale loc) {
    I18N i18n = I18N.getI18N(GroupList.class, loc);
    return i18n.getString(
        "GroupList.description",
        "This table defines " + "the authorized Groups that can be accessed by a given User.");
  }

  // SQL table definition above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // Bean access fields below

  public String getGroupID() {
    String v = (String) this.getFieldValue(FLD_groupID);
    return StringTools.trim(v);
  }

  private void setGroupID(String v) {
    this.setFieldValue(FLD_groupID, StringTools.trim(v));
  }

  // Bean access fields above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  public String toString() {
    return this.getAccountID() + "/" + this.getUserID() + "/" + this.getGroupID();
  }

  // ------------------------------------------------------------------------

  /* overridden to set default values */
  public void setCreationDefaultValues() {
    // super.setRuntimeDefaultValues();
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  public static boolean exists(String acctID, String userID, String groupID)
      throws DBException // if error occurs while testing existance
      {
    if ((acctID != null) && (userID != null) && (groupID != null)) {
      GroupList.Key grpListKey = new GroupList.Key(acctID, userID, groupID);
      return grpListKey.exists();
    }
    return false;
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  /* 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;
    }
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  /* 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;
  }

  /* 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;
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

}
Esempio n. 4
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;
  }
Esempio n. 5
0
 /* create a new "accountID" key field definition */
 protected static DBField newField_userID(boolean key) {
   return new DBField(
       FLD_userID, String.class, DBField.TYPE_USER_ID(), "User ID", (key ? "key=true" : "edit=2"));
 }
Esempio n. 6
0
public class StatusCode extends DeviceRecord<StatusCode> {

  // ------------------------------------------------------------------------

  public static final String ALL_DEVICES = "*";

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // SQL table definition below

  /* table name */
  public static final String _TABLE_NAME = "StatusCode";

  public static String TABLE_NAME() {
    return DBProvider.translateTableName(_TABLE_NAME);
  }

  /* field definition */
  public static final String FLD_statusCode = "statusCode";
  public static final String FLD_statusName = "statusName";
  public static final String FLD_iconSelector = "iconSelector";
  public static final String FLD_iconName = "iconName";
  private static DBField FieldInfo[] = {
    // StatusCode fields
    newField_accountID(true),
    newField_deviceID(true),
    new DBField(
        FLD_statusCode,
        Integer.TYPE,
        DBField.TYPE_UINT32,
        "Status Code",
        "key=true editor=statusCode format=X2"),
    new DBField(FLD_statusName, String.class, DBField.TYPE_STRING(18), "Status Name", "edit=2"),
    new DBField(
        FLD_iconSelector,
        String.class,
        DBField.TYPE_STRING(128),
        "Icon Selector",
        "edit=2 editor=ruleSelector"),
    new DBField(FLD_iconName, String.class, DBField.TYPE_STRING(24), "Icon Name", "edit=2"),
    // Common fields
    newField_description(),
    newField_lastUpdateTime(),
    newField_creationTime(),
  };

  /* key class */
  public static class Key extends DeviceKey<StatusCode> {
    public Key() {
      super();
    }

    public Key(String accountId, int statusCode) {
      this(accountId, ALL_DEVICES, statusCode);
    }

    public Key(String accountId, String deviceId, int statusCode) {
      super.setFieldValue(FLD_accountID, ((accountId != null) ? accountId.toLowerCase() : ""));
      super.setFieldValue(FLD_deviceID, ((deviceId != null) ? deviceId.toLowerCase() : ""));
      super.setFieldValue(FLD_statusCode, statusCode);
    }

    public DBFactory<StatusCode> getFactory() {
      return StatusCode.getFactory();
    }
  }

  /* factory constructor */
  private static DBFactory<StatusCode> factory = null;

  public static DBFactory<StatusCode> getFactory() {
    if (factory == null) {
      factory =
          DBFactory.createDBFactory(
              StatusCode.TABLE_NAME(),
              StatusCode.FieldInfo,
              DBFactory.KeyType.PRIMARY,
              StatusCode.class,
              StatusCode.Key.class,
              true /*editable*/,
              true /*viewable*/);
      factory.addParentTable(Account.TABLE_NAME());
      factory.addParentTable(Device.TABLE_NAME());
      factory.setFieldDefaultValue(FLD_deviceID, ALL_DEVICES);
    }
    return factory;
  }

  /* Bean instance */
  public StatusCode() {
    super();
  }

  /* database record */
  public StatusCode(StatusCode.Key key) {
    super(key);
  }

  // ------------------------------------------------------------------------

  /* table description */
  public static String getTableDescription(Locale loc) {
    I18N i18n = I18N.getI18N(StatusCode.class, loc);
    return i18n.getString(
        "StatusCode.description",
        "This table defines " + "Device specific StatusCode descriptions.");
  }

  // SQL table definition above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // Bean access fields below

  public int getStatusCode() {
    Integer v = (Integer) this.getFieldValue(FLD_statusCode);
    return (v != null) ? v.intValue() : 0;
  }

  public void setStatusCode(int v) {
    this.setFieldValue(FLD_statusCode, v);
  }

  // ------------------------------------------------------------------------

  public String getStatusName() {
    String v = (String) this.getFieldValue(FLD_statusName);
    return StringTools.trim(v);
  }

  public void setStatusName(String v) {
    this.setFieldValue(FLD_statusName, StringTools.trim(v));
  }

  // ------------------------------------------------------------------------

  public String getIconSelector() {
    String v = (String) this.getFieldValue(FLD_iconSelector);
    return StringTools.trim(v);
  }

  public void setIconSelector(String v) {
    this.setFieldValue(FLD_iconSelector, StringTools.trim(v));
  }

  // ------------------------------------------------------------------------

  public String getIconName() {
    String v = (String) this.getFieldValue(FLD_iconName);
    return StringTools.trim(v);
  }

  public void setIconName(String v) {
    this.setFieldValue(FLD_iconName, StringTools.trim(v));
  }

  // Bean access fields above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append(this.getAccountID());
    sb.append("/");
    sb.append(this.getDeviceID());
    sb.append(" ");
    sb.append(this.getStatusCode());
    sb.append("[");
    sb.append(this.getDescription());
    sb.append("]");
    return sb.toString();
  }

  // ------------------------------------------------------------------------

  /* overridden to set default values */
  public void setCreationDefaultValues() {
    BasicPrivateLabel privateLabel = Account.getPrivateLabel(this.getAccount());
    StatusCodes.Code code = StatusCodes.GetCode(this.getStatusCode(), privateLabel);
    this.setStatusName((code != null) ? code.getName() : "");
    this.setDescription((code != null) ? code.getDescription(null) : "");
    this.setIconSelector("");
    // super.setRuntimeDefaultValues();
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  /* 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;
  }

  // ------------------------------------------------------------------------

  /* 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);
    }
  }

  /* 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 icon selector */
  public static String getIconSelector(Device device, int statusCode, BasicPrivateLabel pl) {

    /* device code */
    if (device != null) {
      StatusCode code = device.getStatusCode(statusCode);
      if (code != null) {
        return code.getIconSelector();
      }
    }

    /* default */
    return "";
  }

  // ------------------------------------------------------------------------

  /* return icon name */
  public static String getIconName(Device device, int statusCode, BasicPrivateLabel pl) {

    /* device code */
    if (device != null) {
      StatusCode code = device.getStatusCode(statusCode);
      if (code != null) {
        return code.getIconName();
      }
    }

    /* default */
    return StatusCodes.GetIconName(statusCode, pl);
  }

  // ------------------------------------------------------------------------

  /* return true if StatusCode exists */
  public static boolean exists(String accountID, String deviceID, int code)
      throws DBException // if error occurs while testing existance
      {
    if ((accountID != null) && (deviceID != null)) {
      StatusCode.Key scKey = new StatusCode.Key(accountID, deviceID, code);
      return scKey.exists();
    }
    return false;
  }

  // ------------------------------------------------------------------------

  /* Return specified StatusCode (or null if non-existant) */
  public static StatusCode getStatusCode(String accountID, String deviceID, int code)
      throws DBException {
    return StatusCode._getStatusCode(accountID, null, deviceID, code, false);
  }

  /* Return specified StatusCode (or null if non-existant) */
  public static StatusCode getStatusCode(Account account, String deviceID, int code)
      throws DBException {
    return StatusCode._getStatusCode(null, account, deviceID, code, false);
  }

  /* Return specified StatusCode, create if specified */
  public static StatusCode getStatusCode(
      Account account, String deviceID, int code, boolean createOK) throws DBException {
    return StatusCode._getStatusCode(null, account, deviceID, code, createOK);
  }

  /* 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;
    }
  }

  // ------------------------------------------------------------------------

  /* 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;
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  /* 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;
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // Main admin entry point below

  private static final String ARG_ACCOUNT[] = new String[] {"account", "acct"};
  private static final String ARG_DEVICE[] = new String[] {"device", "dev"};
  private static final String ARG_CODE[] = new String[] {"status", "code", "ecode"};
  private static final String ARG_ECODE[] = new String[] {"ecode"};
  private static final String ARG_DELETE[] = new String[] {"delete"};
  private static final String ARG_CREATE[] = new String[] {"create"};
  private static final String ARG_EDIT[] = new String[] {"edit", "ed"};
  private static final String ARG_LIST[] = new String[] {"list"};

  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);
  }

  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();
    }
  }
}
Esempio n. 7
0
public class AccountString extends AccountRecord<AccountString> {

  // ------------------------------------------------------------------------

  public static final String ID_ACCOUNT = "account"; // "Account", "Company", ...
  public static final String ID_USER = "******"; // "User", "Associate", ...
  public static final String ID_DEVICE = "device"; // "Device", "Tractor", "Taxi", ...
  public static final String ID_DEVICE_NEW_DESCRIPTION = "deviceDesc"; // "New Device"
  public static final String ID_DEVICE_GROUP =
      "deviceGroup"; // "Device Group", "Group", "Fleet", "Crowd", ...
  public static final String ID_ENTITY = "entity"; // "Entity", "Trailer", ...
  public static final String ID_PING_DEVICE =
      "pingDevice"; // "Ping Device", "Locate {0}", "Locate Now", ...
  public static final String ID_ADDRESS = "address"; // "Address", "Landmark", ...

  public static final String ID_KEYS[] =
      new String[] {
        ID_ACCOUNT,
        ID_USER,
        ID_DEVICE,
        ID_DEVICE_NEW_DESCRIPTION,
        ID_DEVICE_GROUP,
        ID_ENTITY,
        ID_PING_DEVICE,
        ID_ADDRESS
      };

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // SQL table definition below

  /* table name */
  private static final String _TABLE_NAME = "AccountString";

  public static String TABLE_NAME() {
    return DBProvider._translateTableName(_TABLE_NAME);
  }

  /* field definition */
  public static final String FLD_stringID = "stringID";
  public static final String FLD_singularTitle = "singularTitle";
  public static final String FLD_pluralTitle = "pluralTitle";
  private static DBField FieldInfo[] = {
    // String fields:
    newField_accountID(true),
    new DBField(
        FLD_stringID,
        String.class,
        DBField.TYPE_ID(),
        "String ID",
        "key=true editor=accountString"),
    new DBField(
        FLD_singularTitle, String.class, DBField.TYPE_STRING(64), "Singular Title", "edit=2"),
    new DBField(FLD_pluralTitle, String.class, DBField.TYPE_STRING(64), "Plural Title", "edit=2"),
    // Common fields
    newField_description(),
    newField_lastUpdateTime(),
    newField_creationTime(),
  };

  /* key class */
  public static class Key extends AccountKey<AccountString> {
    public Key() {
      super();
    }

    public Key(String acctId, String strKey) {
      super.setFieldValue(FLD_accountID, ((acctId != null) ? acctId.toLowerCase() : ""));
      super.setFieldValue(FLD_stringID, ((strKey != null) ? strKey.toLowerCase() : ""));
    }

    public DBFactory<AccountString> getFactory() {
      return AccountString.getFactory();
    }
  }

  /* factory constructor */
  private static DBFactory<AccountString> factory = null;

  public static DBFactory<AccountString> getFactory() {
    if (factory == null) {
      factory =
          DBFactory.createDBFactory(
              AccountString.TABLE_NAME(),
              AccountString.FieldInfo,
              DBFactory.KeyType.PRIMARY,
              AccountString.class,
              AccountString.Key.class,
              true /*editable*/,
              true /*viewable*/);
      factory.addParentTable(Account.TABLE_NAME());
    }
    return factory;
  }

  /* Bean instance */
  public AccountString() {
    super();
  }

  /* database record */
  public AccountString(AccountString.Key key) {
    super(key);
  }

  // ------------------------------------------------------------------------

  /* table description */
  public static String getTableDescription(Locale loc) {
    I18N i18n = I18N.getI18N(AccountString.class, loc);
    return i18n.getString(
        "AccountString.description",
        "This table defines " + "Account specific customized String key/values.");
  }

  // SQL table definition above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // Bean access fields below

  /* return the String ID for this record */
  public String getStringID() {
    String v = (String) this.getFieldValue(FLD_stringID);
    return StringTools.trim(v);
  }

  /* set the String ID for this record */
  private void setStringID(String v) {
    this.setFieldValue(FLD_stringID, StringTools.trim(v));
  }

  // ------------------------------------------------------------------------

  /* return the singular title */
  public String getSingularTitle() {
    String v = (String) this.getFieldValue(FLD_singularTitle);
    return StringTools.trim(v);
  }

  /* return true if singular title is defined */
  public boolean hasSingularTitle() {
    return !this.getSingularTitle().equals("");
  }

  /* set the singular title */
  public void setSingularTitle(String v) {
    this.setFieldValue(FLD_singularTitle, StringTools.trim(v));
  }

  // ------------------------------------------------------------------------

  /* return the plural title */
  public String getPluralTitle() {
    String v = (String) this.getFieldValue(FLD_pluralTitle);
    return StringTools.trim(v);
  }

  /* return true if plural title is defined */
  public boolean hasPluralTitle() {
    return !this.getPluralTitle().equals("");
  }

  /* set the plural title */
  public void setPluralTitle(String v) {
    this.setFieldValue(FLD_pluralTitle, StringTools.trim(v));
  }

  // Bean access fields above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  /* overridden to set default values */
  public void setCreationDefaultValues() {
    this.setDescription("String");
    this.setSingularTitle("singular");
    this.setPluralTitle("plural");
    // super.setRuntimeDefaultValues();
  }

  // ------------------------------------------------------------------------

  /* return the AccountID/StringID */
  public String toString() {
    return this.getAccountID() + "/" + this.getStringID();
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  public static boolean exists(String acctID, String strID)
      throws DBException // if error occurs while testing existance
      {
    if ((acctID != null) && (strID != null)) {
      AccountString.Key strKey = new AccountString.Key(acctID, strID);
      return strKey.exists();
    }
    return false;
  }

  // ------------------------------------------------------------------------

  /* update title string */
  public static void updateAccountString(
      Account account, String stringID, String description, String singular, String plural)
      throws DBException {

    /* valid account? */
    if (account == null) {
      throw new DBException("Account not specified.");
    }

    /* delete? */
    // delete if both singular/plural values are empty/null
    if (((singular == null) || singular.equals("")) && ((plural == null) || plural.equals(""))) {
      String acctID = account.getAccountID();
      AccountString.Key key = new AccountString.Key(acctID, stringID);
      key.delete(true); // also delete dependencies (if any)
      return;
    }

    /* get/create AccountString */
    AccountString str = AccountString.getAccountString(account, stringID);
    if (str == null) {
      str = AccountString.getAccountString(account, stringID, true);
    }

    /* insert/update */
    str.setDescription(description);
    str.setSingularTitle(singular);
    str.setPluralTitle((plural != null) ? plural : singular);
    str.save();
  }

  // ------------------------------------------------------------------------

  /* get string */
  public static AccountString getAccountString(Account account, String strID) throws DBException {
    if ((account != null) && (strID != null)) {
      String acctID = account.getAccountID();
      AccountString.Key key = new AccountString.Key(acctID, strID);
      if (key.exists()) {
        AccountString str = key.getDBRecord(true);
        str.setAccount(account);
        return str;
      } else {
        // AccountString does not exist
        return null;
      }
    } else {
      return null; // just say it doesn't exist
    }
  }

  /* get the singular/plural strings in an array that can be used directly by "i18n.getStr...(...)" */
  public static String[] getStringsArray(Account account, String strID, String dft[]) {

    /* get values */
    try {
      AccountString str = AccountString.getAccountString(account, strID);
      if (str != null) {
        String s = str.getSingularTitle();
        String p = str.getPluralTitle();
        if ((dft != null) && (dft.length >= 2)) {
          if (s.equals("")) {
            s = dft[0];
          }
          if (p.equals("")) {
            p = dft[1];
          }
        }
        return new String[] {
          s, // singular
          p // plural
        };
      }
    } catch (DBException dbe) {
      // ignore
    }

    /* return default */
    return dft; // not found
  }

  // ------------------------------------------------------------------------

  /* get account string */
  // Note: does NOT return null
  public static AccountString getAccountString(Account account, String strID, boolean create)
      throws DBException {

    /* account-id specified? */
    if (account == null) {
      throw new DBNotFoundException("Account not specified.");
    }
    String acctID = account.getAccountID();

    /* string-id specified? */
    if ((strID == null) || strID.equals("")) {
      throw new DBNotFoundException("String-ID not specified for account: " + acctID);
    }

    /* get/create */
    AccountString str = null;
    AccountString.Key strKey = new AccountString.Key(acctID, strID);
    if (!strKey.exists()) {
      if (create) {
        str = strKey.getDBRecord();
        str.setAccount(account);
        str.setCreationDefaultValues();
        return str; // not yet saved!
      } else {
        throw new DBNotFoundException("String-ID does not exists: " + strKey);
      }
    } else if (create) {
      // we've been asked to create the AccountString, and it already exists
      throw new DBAlreadyExistsException("String-ID already exists '" + strKey + "'");
    } else {
      str = AccountString.getAccountString(account, strID);
      if (str == null) {
        throw new DBException("Unable to read existing String-ID: " + strKey);
      }
      return str;
    }
  }

  /* create string */
  public static AccountString createNewAccountString(Account account, String strID)
      throws DBException {
    if ((account != null) && (strID != null) && !strID.equals("")) {
      AccountString str =
          AccountString.getAccountString(account, strID, true); // does not return null
      str.save();
      return str;
    } else {
      throw new DBException("Invalid Account/StringID specified");
    }
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // Main admin entry point below

  private static final String ARG_ACCOUNT[] = new String[] {"account", "acct"};
  private static final String ARG_STRING[] = new String[] {"string", "str"};
  private static final String ARG_CREATE[] = new String[] {"create"};
  private static final String ARG_EDIT[] = new String[] {"edit", "ed"};
  private static final String ARG_DELETE[] = new String[] {"delete"};

  private static String _fmtStrID(String acctID, String strID) {
    return acctID + "/" + strID;
  }

  private static void usage() {
    Print.logInfo("Usage:");
    Print.logInfo("  java ... " + AccountString.class.getName() + " {options}");
    Print.logInfo("Common Options:");
    Print.logInfo("  -account=<id>   Acount ID which owns AccountString");
    Print.logInfo("  -string=<id>    String ID to create/edit");
    Print.logInfo("  -create         Create a new AccountString");
    Print.logInfo("  -edit           Edit an existing (or newly created) AccountString");
    Print.logInfo("  -delete         Delete specified AccountString");
    System.exit(1);
  }

  public static void main(String args[]) {
    DBConfig.cmdLineInit(args, true); // main
    String acctID = RTConfig.getString(ARG_ACCOUNT, "");
    String strID = RTConfig.getString(ARG_STRING, "");

    /* account-id specified? */
    if (StringTools.isBlank(acctID)) {
      Print.logError("Account-ID not specified.");
      usage();
    }

    /* get account */
    Account acct = null;
    try {
      acct = Account.getAccount(acctID); // may throw DBException
      if (acct == null) {
        Print.logError("Account-ID does not exist: " + acctID);
        usage();
      }
    } catch (DBException dbe) {
      Print.logException("Error loading Account: " + acctID, dbe);
      // dbe.printException();
      System.exit(99);
    }

    /* string-id specified? */
    if ((strID == null) || strID.equals("")) {
      Print.logError("String-ID not specified.");
      usage();
    }

    /* string exists? */
    boolean stringExists = false;
    try {
      stringExists = AccountString.exists(acctID, strID);
    } catch (DBException dbe) {
      Print.logError("Error determining if AccountString exists: " + _fmtStrID(acctID, strID));
      System.exit(99);
    }

    /* option count */
    int opts = 0;

    /* delete */
    if (RTConfig.getBoolean(ARG_DELETE, false) && !acctID.equals("") && !strID.equals("")) {
      opts++;
      if (!stringExists) {
        Print.logWarn("AccountString does not exist: " + _fmtStrID(acctID, strID));
        Print.logWarn("Continuing with delete process ...");
      }
      try {
        AccountString.Key strKey = new AccountString.Key(acctID, strID);
        strKey.delete(true); // also delete dependencies
        Print.logInfo("AccountString deleted: " + _fmtStrID(acctID, strID));
        stringExists = false;
      } catch (DBException dbe) {
        Print.logError("Error deleting AccountString: " + _fmtStrID(acctID, strID));
        dbe.printException();
        System.exit(99);
      }
      System.exit(0);
    }

    /* create */
    if (RTConfig.getBoolean(ARG_CREATE, false)) {
      opts++;
      if (stringExists) {
        Print.logWarn("AccountString already exists: " + _fmtStrID(acctID, strID));
      } else {
        try {
          AccountString.createNewAccountString(acct, strID);
          Print.logInfo("Created AccountString: " + _fmtStrID(acctID, strID));
          stringExists = true;
        } catch (DBException dbe) {
          Print.logError("Error creating AccountString: " + _fmtStrID(acctID, strID));
          dbe.printException();
          System.exit(99);
        }
      }
    }

    /* edit */
    if (RTConfig.getBoolean(ARG_EDIT, false)) {
      opts++;
      if (!stringExists) {
        Print.logError("AccountString does not exist: " + _fmtStrID(acctID, strID));
      } else {
        try {
          AccountString str =
              AccountString.getAccountString(acct, strID, false); // may throw DBException
          DBEdit editor = new DBEdit(str);
          editor.edit(true); // may throw IOException
        } catch (IOException ioe) {
          if (ioe instanceof EOFException) {
            Print.logError("End of input");
          } else {
            Print.logError("IO Error");
          }
        } catch (DBException dbe) {
          Print.logError("Error editing AccountString: " + _fmtStrID(acctID, strID));
          dbe.printException();
        }
      }
      System.exit(0);
    }

    /* no options specified */
    if (opts == 0) {
      Print.logWarn("Missing options ...");
      usage();
    }
  }

  // ------------------------------------------------------------------------

}
Esempio n. 8
0
public class RoleAcl extends RoleRecord<RoleAcl> {

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // SQL table definition below

  /* table name */
  public static final String _TABLE_NAME = "RoleAcl";

  public static String TABLE_NAME() {
    return DBProvider.translateTableName(_TABLE_NAME);
  }

  /* field definition */
  public static final String FLD_aclID = "aclID";
  public static final String FLD_accessLevel = "accessLevel";
  private static DBField FieldInfo[] = {
    // RoleAcl fields
    newField_accountID(true),
    newField_roleID(true),
    new DBField(FLD_aclID, String.class, DBField.TYPE_STRING(64), "ACL ID", "key=true"),
    new DBField(
        FLD_accessLevel,
        Integer.TYPE,
        DBField.TYPE_UINT16,
        "Access Level",
        "edit=2 enum=AclEntry$AccessLevel"),
    // Common fields
    newField_description(),
    newField_lastUpdateTime(),
    newField_creationTime(),
  };

  /* key class */
  public static class Key extends RoleKey<RoleAcl> {
    public Key() {
      super();
    }

    public Key(String acctId, String roleId, String aclId) {
      super.setFieldValue(FLD_accountID, ((acctId != null) ? acctId.toLowerCase() : ""));
      super.setFieldValue(FLD_roleID, ((roleId != null) ? roleId.toLowerCase() : ""));
      super.setFieldValue(FLD_aclID, ((aclId != null) ? aclId.toLowerCase() : ""));
    }

    public DBFactory<RoleAcl> getFactory() {
      return RoleAcl.getFactory();
    }
  }

  /* factory constructor */
  private static DBFactory<RoleAcl> factory = null;

  public static DBFactory<RoleAcl> getFactory() {
    if (factory == null) {
      EnumTools.registerEnumClass(AccessLevel.class);
      factory =
          DBFactory.createDBFactory(
              RoleAcl.TABLE_NAME(),
              RoleAcl.FieldInfo,
              DBFactory.KeyType.PRIMARY,
              RoleAcl.class,
              RoleAcl.Key.class,
              true /*editable*/,
              true /*viewable*/);
      factory.addParentTable(Account.TABLE_NAME());
      factory.addParentTable(Role.TABLE_NAME());
    }
    return factory;
  }

  /* Bean instance */
  public RoleAcl() {
    super();
  }

  /* database record */
  public RoleAcl(RoleAcl.Key key) {
    super(key);
  }

  // ------------------------------------------------------------------------

  /* table description */
  public static String getTableDescription(Locale loc) {
    I18N i18n = I18N.getI18N(RoleAcl.class, loc);
    return i18n.getString(
        "RoleAcl.description", "This table defines " + "Role specific Access Control permissions.");
  }

  // SQL table definition above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // Bean access fields below

  public String getAclID() {
    String v = (String) this.getFieldValue(FLD_aclID);
    return StringTools.trim(v);
  }

  private void setAclID(String v) {
    this.setFieldValue(FLD_aclID, StringTools.trim(v));
  }

  // ------------------------------------------------------------------------

  public int getAccessLevel() {
    Integer v = (Integer) this.getFieldValue(FLD_accessLevel);
    return (v != null) ? v.intValue() : 0;
  }

  public void setAccessLevel(int v) {
    this.setFieldValue(FLD_accessLevel, EnumTools.getValueOf(AccessLevel.class, v).getIntValue());
  }

  public void setAccessLevel(String v) {
    this.setFieldValue(FLD_accessLevel, EnumTools.getValueOf(AccessLevel.class, v).getIntValue());
  }

  public boolean hasReadAccess() {
    return AclEntry.okRead(this.getAccessLevel());
  }

  public boolean hasWriteAccess() {
    return AclEntry.okWrite(this.getAccessLevel());
  }

  public boolean hasAllAccess() {
    // This can be implied to mean 'read all' access if no writing is allowed for this ACL
    return AclEntry.okAll(this.getAccessLevel());
  }

  // Bean access fields above
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  public String toString() {
    return this.getAccountID() + "/" + this.getRoleID() + "/" + this.getAclID();
  }

  // ------------------------------------------------------------------------

  /* overridden to set default values */
  public void setCreationDefaultValues() {
    // super.setRuntimeDefaultValues();
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------

  // ------------------------------------------------------------------------
  // The following is an optimization for holding the Role record while
  // processing this RoleAcl.  Use with caution.

  // ------------------------------------------------------------------------

  /* return true if the specified role ACL exists */
  public static boolean exists(String acctID, String roleID, String aclID)
      throws DBException // if error occurs while testing existance
      {
    if ((acctID != null) && (roleID != null) && (aclID != null)) {
      RoleAcl.Key aclKey = new RoleAcl.Key(acctID, roleID, aclID);
      return aclKey.exists();
    }
    return false;
  }

  // ------------------------------------------------------------------------

  /* return Role access level */
  public static AccessLevel getAccessLevel(RoleAcl ra) {
    return (ra != null)
        ? EnumTools.getValueOf(AccessLevel.class, ra.getAccessLevel())
        : EnumTools.getDefault(AccessLevel.class);
  }

  /* 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;
      }
    }
  }

  /* 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
  }

  /* 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;
  }

  // ------------------------------------------------------------------------

  /* Return specified role */
  public static RoleAcl getRoleAcl(Role role, String aclId) throws DBException {
    if ((role != null) && (aclId != null)) {
      RoleAcl.Key aclKey = new RoleAcl.Key(role.getAccountID(), role.getRoleID(), aclId);
      if (aclKey.exists()) {
        RoleAcl roleAcl = aclKey.getDBRecord(true);
        roleAcl.setRole(role);
        return roleAcl;
      } else {
        return null;
      }
    } else {
      throw new DBException("Role or AclID is null");
    }
  }

  /* 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 specified role.  Return null if acl already exists */
  public static RoleAcl createNewRoleAcl(Role role, String aclID) throws DBException {
    RoleAcl roleAcl = RoleAcl.getRoleAcl(role, aclID, true);
    if (roleAcl != null) {
      roleAcl.save();
    }
    return roleAcl;
  }

  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // ------------------------------------------------------------------------
  // Main admin entry point below

  private static final String ARG_ACCOUNT[] = new String[] {"account", "acct"};
  private static final String ARG_ROLE[] = new String[] {"role"};
  private static final String ARG_LIST[] = new String[] {"list"};
  private static final String ARG_ACL[] = new String[] {"acl"};
  private static final String ARG_SET[] = new String[] {"set"};
  private static final String ARG_CREATE[] = new String[] {"create", "cr"};
  private static final String ARG_EDIT[] = new String[] {"edit", "ed"};
  private static final String ARG_DELETE[] = new String[] {"delete", "purge"};

  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);
  }

  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();
    }
  }

  // ------------------------------------------------------------------------

}