Esempio n. 1
0
 protected DCServerFactory.ResultCode sendEmail(
     String frEmail, String toEmail, String subj, String body) {
   if (StringTools.isBlank(frEmail)) {
     Print.logError("'From' Email address not specified");
     return DCServerFactory.ResultCode.TRANSMIT_FAIL;
   } else if (StringTools.isBlank(toEmail) || !CommandPacketHandler.validateAddress(toEmail)) {
     Print.logError("'To' SMS Email address invalid, or not specified");
     return DCServerFactory.ResultCode.TRANSMIT_FAIL;
   } else if (StringTools.isBlank(subj) && StringTools.isBlank(body)) {
     Print.logError("Command string not specified");
     return DCServerFactory.ResultCode.INVALID_ARG;
   } else {
     try {
       Print.logInfo("SMS email: to <" + toEmail + ">");
       Print.logDebug("  From   : " + frEmail);
       Print.logDebug("  To     : " + toEmail);
       Print.logDebug("  Subject: " + subj);
       Print.logDebug("  Message: " + body);
       SendMail.send(frEmail, toEmail, null, null, subj, body, null);
       return DCServerFactory.ResultCode.SUCCESS;
     } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException
       // this will fail if JavaMail support for SendMail is not available.
       Print.logWarn("SendMail error: " + t);
       return DCServerFactory.ResultCode.TRANSMIT_FAIL;
     }
   }
 }
Esempio n. 2
0
  /* return status codes for account/device */
  public static int[] getStatusCodes(String accountID, String deviceID) throws DBException {

    /* account-id specified? */
    if (StringTools.isBlank(accountID)) {
      return new int[0];
    }

    /* device-id specified? */
    if (StringTools.isBlank(deviceID)) {
      deviceID = ALL_DEVICES;
    }

    /* select */
    // DBSelect: SELECT statucCode FROM StatusCode WHERE (accountID='acct') AND (deviceID='*') ORDER
    // BY statucCode
    DBSelect<StatusCode> dsel = new DBSelect<StatusCode>(StatusCode.getFactory());
    dsel.setSelectedFields(StatusCode.FLD_statusCode);
    DBWhere dwh = dsel.createDBWhere();
    dsel.setWhere(
        dwh.WHERE_(
            dwh.AND(
                dwh.EQ(StatusCode.FLD_accountID, accountID),
                dwh.EQ(StatusCode.FLD_deviceID, deviceID))));
    dsel.setOrderByFields(StatusCode.FLD_statusCode);

    /* get list */
    java.util.List<Integer> codeList = new Vector<Integer>();
    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = DBConnection.getDefaultConnection().execute(dsel.toString());
      rs = stmt.getResultSet();
      while (rs.next()) {
        int code = rs.getInt(StatusCode.FLD_statusCode);
        codeList.add(new Integer(code));
      }
    } catch (SQLException sqe) {
      throw new DBException("Getting StatusCode List", sqe);
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (Throwable t) {
        }
      }
      if (stmt != null) {
        try {
          stmt.close();
        } catch (Throwable t) {
        }
      }
    }

    /* return array of status codes */
    int codeListInt[] = new int[codeList.size()];
    for (int i = 0; i < codeListInt.length; i++) {
      codeListInt[i] = codeList.get(i).intValue();
    }
    return codeListInt;
  }
Esempio n. 3
0
 /* validate the syntax of the specified list of multiple email addresses */
 public static boolean validateAddresses(String addrs, boolean acceptSMS) {
   if (StringTools.isBlank(addrs)) {
     // blank is ok in this case
     return true;
   } else if (acceptSMS) {
     // allow "sms:123456789" format
     String addrArry[] = StringTools.parseStringArray(addrs, ',');
     if (addrArry.length == 0) {
       return false;
     }
     for (int i = 0; i < addrArry.length; i++) {
       String em = addrArry[i].trim();
       if (StringTools.isBlank(em)) {
         // individual addresses not allowed
         return false;
       } else if (SMSOutboundGateway.StartsWithSMS(em)) {
         // TODO: for now, accept as-is
       } else if (!validateAddress(em)) {
         return false;
       }
     }
     return true;
   } else {
     // true email addresses only
     try {
       return SendMail.validateAddresses(addrs);
     } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException
       // this will fail if JavaMail support for SendMail is not available.
       Print.logError("*** SendMail error: " + t);
       return false;
     }
   }
 }
  /** ** Reads/returns the specified CompileTime template file */
  private static String readTemplate(File tf, String pkgName) {

    /* read template data */
    byte templData[] = FileTools.readFile(tf);
    if (templData == null) {
      Print.errPrintln("\nUnable to read Input/Template file: " + tf);
      return null;
    } else if (templData.length == 0) {
      Print.errPrintln("\nInput/Template file is empty: " + tf);
      return null;
    }

    /* return template String */
    String templateText = StringTools.toStringValue(templData);
    if (!StringTools.isBlank(pkgName) && !StringTools.isBlank(templateText)) {
      String lines[] = StringTools.split(templateText, '\n', false);
      for (int i = 0; i < lines.length; i++) {
        if (lines[i].trim().startsWith(JAVA_PACKAGE_)) {
          lines[i] = CompiletimeVars.packageLine(pkgName);
          return StringTools.join(lines, '\n') + "\n";
        }
      }
      StringBuffer sb = new StringBuffer();
      sb.append(CompiletimeVars.packageLine(pkgName)).append("\n");
      sb.append(templateText);
      return sb.toString();
    } else {
      return templateText;
    }
  }
Esempio n. 5
0
  /* return the DBSelect statement for the specified account/group */
  protected static DBSelect _getUserListSelect(String acctId, String groupId) {

    /* empty/null account */
    if (StringTools.isBlank(acctId)) {
      return null;
    }

    /* empty/null user */
    if (StringTools.isBlank(groupId)) {
      return null;
    }

    /* get select */
    // DBSelect: SELECT * FROM GroupList WHERE ((accountID='acct') and (groupID='group')) ORDER BY
    // userID
    DBSelect<GroupList> dsel = new DBSelect<GroupList>(GroupList.getFactory());
    dsel.setSelectedFields(GroupList.FLD_userID);
    DBWhere dwh = dsel.createDBWhere();
    dsel.setWhere(
        dwh.WHERE_(
            dwh.AND(
                dwh.EQ(GroupList.FLD_accountID, acctId), dwh.EQ(GroupList.FLD_groupID, groupId))));
    dsel.setOrderByFields(GroupList.FLD_userID);
    return dsel;
  }
Esempio n. 6
0
 /** ** Decodes an RTP encoded argument */
 public static RTProperties parseRTP(String rtpArg) {
   if (!StringTools.isBlank(rtpArg)) {
     String s = _des64(rtpArg);
     if (!StringTools.isBlank(s)) {
       return new RTProperties(s);
     }
   }
   return null;
 }
Esempio n. 7
0
  /* return StatusCode */
  public static StatusCode findStatusCode(String accountID, String deviceID, int statusCode) {

    /* check account status codes */
    if (!StringTools.isBlank(accountID)) {

      // first, try account/device
      if (!StringTools.isBlank(deviceID)) {
        try {
          StatusCode.Key codeKey = new StatusCode.Key(accountID, deviceID, statusCode);
          if (codeKey.exists()) { // may throw DBException
            StatusCode code = codeKey.getDBRecord(true);
            if (code != null) { // should not be null
              return code;
            }
          }
        } catch (DBException dbe) {
          // ignore error
        }
      }

      // next, try just the account
      try {
        StatusCode.Key codeKey = new StatusCode.Key(accountID, statusCode);
        if (codeKey.exists()) { // may throw DBException
          StatusCode code = codeKey.getDBRecord(true);
          if (code != null) { // should not be null
            return code;
          }
        }
      } catch (DBException dbe) {
        // ignore error
      }
    }

    /* check global status codes */
    String sysAdmin = AccountRecord.getSystemAdminAccountID();
    if (!StringTools.isBlank(sysAdmin)) {
      try {
        StatusCode.Key codeKey = new StatusCode.Key(sysAdmin, statusCode);
        if (codeKey.exists()) { // may throw DBException
          StatusCode code = codeKey.getDBRecord(true);
          if (code != null) { // should not be null
            return code;
          }
        }
      } catch (DBException dbe) {
        // ignore error
      }
    }

    /* icon selector not found */
    return null;
  }
Esempio n. 8
0
  /* return list of all Devices within the specified DeviceGroup (NOT SCALABLE BEYOND A FEW HUNDRED GROUPS) */
  public static java.util.List<String> getUsersForGroup(String acctId, String groupId)
      throws DBException {

    /* valid account/groupId? */
    if (StringTools.isBlank(acctId)) {
      return null;
    } else if (StringTools.isBlank(groupId)) {
      return null;
    }

    /* get db selector */
    DBSelect dsel = GroupList._getUserListSelect(acctId, groupId);
    if (dsel == null) {
      return null;
    }

    /* read users for group */
    java.util.List<String> usrList = new Vector<String>();
    DBConnection dbc = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      dbc = DBConnection.getDefaultConnection();
      stmt = dbc.execute(dsel.toString());
      rs = stmt.getResultSet();
      while (rs.next()) {
        String usrId = rs.getString(GroupList.FLD_userID);
        usrList.add(usrId);
      }
    } catch (SQLException sqe) {
      throw new DBException("Get Group GroupeList", sqe);
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (Throwable t) {
        }
      }
      if (stmt != null) {
        try {
          stmt.close();
        } catch (Throwable t) {
        }
      }
      DBConnection.release(dbc);
    }

    /* return list */
    return usrList;
  }
Esempio n. 9
0
  /* set Role access level */
  public static boolean deleteAccessLevel(Role role, String aclId) throws DBException {

    /* role specified? */
    if (role == null) {
      return false; // quietly ignore
    }
    String acctId = role.getAccountID();
    String roleId = role.getRoleID();

    /* acl-id specified? */
    if (StringTools.isBlank(aclId)) {
      return false; // quietly ignore
    }

    /* already deleted? */
    boolean aclExists = RoleAcl.exists(acctId, roleId, aclId);
    if (!aclExists) {
      return false;
    }

    /* delete */
    RoleAcl.Key aclKey = new RoleAcl.Key(acctId, roleId, aclId);
    aclKey.delete(true); // also delete dependencies
    return true;
  }
Esempio n. 10
0
 /**
  * ** Adds an argument to the URI ** @param key The key name of the argument to add ** @param
  * value The value of the new key ** @param encode True if <code>value</code> shoudl be hex
  * encoded ** @param obfuscate True if <code>value</code> should be obfuscated ** @return This
  * URIArg, with the argument added
  */
 protected URIArg _addArg(String key, String value, boolean encode, boolean obfuscate) {
   if (!StringTools.isBlank(key)) {
     String val = encode ? this.encodeArg(value, obfuscate) : value;
     this.getKeyValList().add(new KeyVal(key, val));
   }
   return this;
 }
Esempio n. 11
0
 /** ** Scrambles String */
 public static String _ens64(String d) {
   if (!StringTools.isBlank(d)) {
     return Base64.encode(StringTools.getBytes(d), getBase64Alphabet(), Base64Pad);
   } else {
     return "";
   }
 }
Esempio n. 12
0
  /* get/create device list entry */
  public static GroupList getGroupList(User user, String groupID, boolean createOK)
      throws DBException {
    // does not return null, if 'createOK' is true

    /* User specified? */
    if (user == null) {
      throw new DBException("User not specified.");
    }
    String accountID = user.getAccountID();
    String userID = user.getUserID();

    /* group exists? */
    if (StringTools.isBlank(groupID)) {
      throw new DBException("DeviceGroup ID not specified.");
    } else if (!DeviceGroup.exists(accountID, groupID)) {
      throw new DBException("DeviceGroup does not exist: " + accountID + "/" + groupID);
    }

    /* create/save record */
    GroupList.Key grpListKey = new GroupList.Key(accountID, userID, groupID);
    if (grpListKey.exists()) { // may throw DBException
      // already exists
      GroupList listItem = grpListKey.getDBRecord(true);
      listItem.setUser(user);
      return listItem;
    } else if (createOK) {
      GroupList listItem = grpListKey.getDBRecord();
      listItem.setCreationDefaultValues();
      listItem.setUser(user);
      return listItem;
    } else {
      // record doesn't exist, and caller doesn't want us to create it
      return null;
    }
  }
Esempio n. 13
0
 public GoogleSig getSignature() {
   if (!this.signature_init) {
     this.signature_init = true;
     String key = this.getAuthorization();
     if (!StringTools.isBlank(key) && key.startsWith(CLIENT_ID_PREFIX)) {
       String sigKey = this.getProperties().getString(PROP_signatureKey, "");
       if (!StringTools.isBlank(sigKey)) {
         Print.logWarn("Setting SignatureKey: " + sigKey);
         this.signature = new GoogleSig(sigKey);
       } else {
         Print.logWarn("No signatureKey ...");
       }
     }
   }
   return this.signature;
 }
Esempio n. 14
0
 /**
  * ** Returns an I18N.Text instance used for lazy localization.<br>
  * ** (use in XML loaders to avoid expression matches when auto-updating
  * 'LocalStrings_XX.properties') ** @param pkg The package name ** @param key The localization key
  * ** @param dft The default localized text ** @param showError If true, a stacktrace will be
  * display if the key is invalid. ** @return An I18N.Text instance used for lazy localization
  */
 public static I18N.Text parseText(String pkg, String key, String dft, boolean showError) {
   if (dft == null) {
     Print.logStackTrace("Default value is null!");
     return new I18N.Text(pkg, key, "");
   } else if (!StringTools.isBlank(key)) {
     return new I18N.Text(pkg, key, dft);
   } else if (!StringTools.startsWithIgnoreCase(dft, I18N_KEY_STARTE)
       && !StringTools.startsWithIgnoreCase(dft, I18N_KEY_STARTC)) {
     if (showError) {
       Print.logStackTrace(
           "Invalid/missing key definition!\n"
               + "Package: "
               + pkg
               + "\n"
               + "Key    : "
               + key
               + "\n"
               + "Default: "
               + dft);
     }
     return new I18N.Text(pkg, null, dft);
   } else {
     int ks = I18N_KEY_STARTE.length();
     int ke = dft.indexOf(I18N_KEY_END, ks);
     if (ke < ks) {
       return new I18N.Text(pkg, null, dft); // ']' is missing, return string as-is
     }
     String k = dft.substring(ks, ke).trim();
     String v = dft.substring(ke + I18N_KEY_END.length()).trim();
     return new I18N.Text(pkg, k, v);
   }
 }
Esempio n. 15
0
 /* encode "type=<type> ..." into long value */
 public static long EncodeFault(String faultProps) {
   if (!StringTools.isBlank(faultProps)) {
     return DTOBDFault.EncodeFault(new RTProperties(faultProps));
   } else {
     return 0L;
   }
 }
Esempio n. 16
0
 public void setGeozoneID(String gzid) {
   if (!StringTools.isBlank(gzid)) {
     this.fieldValues.setString(EventData.FLD_geozoneID, gzid);
   } else {
     this.fieldValues.removeProperty(EventData.FLD_geozoneID);
   }
 }
Esempio n. 17
0
  public void addDataSet(Color color, String legend, Data data[]) throws Exception {

    /* init */
    this._initChart();

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

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

    /* count data set */
    this.dataSetCount++;
  }
Esempio n. 18
0
  /* set Role access level */
  public static void setAccessLevel(Role role, String aclId, AccessLevel level) throws DBException {

    /* role specified? */
    if (role == null) {
      throw new DBException("Role not specified.");
    }
    String acctId = role.getAccountID();
    String roleId = role.getRoleID();

    /* acl-id specified? */
    if (StringTools.isBlank(aclId)) {
      throw new DBException("Acl-ID not specified.");
    }

    /* get/create role */
    RoleAcl roleAcl = null;
    RoleAcl.Key aclKey = new RoleAcl.Key(acctId, roleId, aclId);
    if (aclKey.exists()) { // may throw DBException
      roleAcl = RoleAcl.getRoleAcl(role, aclId); // may throw DBException
    } else {
      roleAcl = aclKey.getDBRecord();
      roleAcl.setRole(role);
    }

    /* set access level */
    int levelInt = (level != null) ? level.getIntValue() : AccessLevel.NONE.getIntValue();
    roleAcl.setAccessLevel(levelInt);

    /* save */
    roleAcl.save(); // may throw DBException
  }
Esempio n. 19
0
 /** ** Descrambles String */
 public static String _des64(String e) {
   if (!StringTools.isBlank(e)) {
     byte b[] = Base64.decode(e, getBase64Alphabet(), Base64Pad);
     return StringTools.toStringValue(b, ' ');
   } else {
     return "";
   }
 }
Esempio n. 20
0
  /** ** Main entry point for testing/debugging ** @param argv Comand-line arguments */
  public static void main(String argv[]) {
    RTConfig.setCommandLineArgs(argv);
    String host = RTConfig.getString(ARG_HOST, null);
    int port = RTConfig.getInt(ARG_PORT, 0);

    /* send data */
    if (RTConfig.hasProperty(ARG_SEND)) {
      if (StringTools.isBlank(host)) {
        Print.logError("Target host not specified");
        usage();
      }
      if (port <= 0) {
        Print.logError("Target port not specified");
        usage();
      }
      String dataStr = RTConfig.getString(ARG_SEND, "hello");
      byte data[] =
          dataStr.startsWith("0x") ? StringTools.parseHex(dataStr, null) : dataStr.getBytes();
      ClientSocketThread cst = new ClientSocketThread(host, port);
      try {
        cst.openSocket();
        cst.socketWriteBytes(data);
      } catch (Throwable t) {
        Print.logException("Error", t);
      } finally {
        cst.closeSocket();
      }
      System.exit(0);
    }

    /* receive data */
    if (RTConfig.hasProperty(ARG_RECEIVE)) {
      if (port <= 0) {
        Print.logError("Target port not specified");
        usage();
      }
      if (!StringTools.isBlank(host)) {
        Print.logWarn("Specified 'host' will be ignored");
      }
      Print.logError("Receive not yet implemented ...");
      System.exit(99);
    }

    /* show usage */
    usage();
  }
Esempio n. 21
0
 /**
  * ** Adds an argument to the URI ** @param key The key name of the argument to add ** @param rtp
  * The RTP encoded values of the new key ** @return This URIArg, with the argument added
  */
 public URIArg addArg(String key, RTProperties rtp) {
   String r = (rtp != null) ? rtp.toString() : null;
   if (!StringTools.isBlank(r)) {
     return this._addArg(key, URIArg.encodeRTP(rtp), false /*encode*/, false /*obfuscate*/);
   } else {
     return this.addArg(key, "");
   }
 }
 /** ** Returns a "package" line for the specified package name */
 private static String packageLine(String pkgName) {
   if (StringTools.isBlank(pkgName)) {
     return "// no package";
   } else if (pkgName.startsWith(JAVA_PACKAGE_)) {
     return pkgName + ";";
   } else {
     return JAVA_PACKAGE_ + pkgName + ";";
   }
 }
Esempio n. 23
0
 public String toString() {
   String locStr = RTConfig.getString(RTKey.SESSION_LOCALE, null);
   if (StringTools.isBlank(locStr)) {
     return this.getDefault();
   } else {
     Locale loc = I18N.getLocale(locStr);
     return this.toString(loc);
   }
 }
Esempio n. 24
0
 public void setFieldValue(String fldName, Object fldVal) {
   if (!StringTools.isBlank(fldName) && (fldVal != null)) {
     if (USE_ALTERNATE_FIELD_MAP) {
       this.getAlternateFieldMap().put(fldName, fldVal);
     } else {
       this.fieldValues.setProperty(fldName, fldVal);
     }
   }
 }
Esempio n. 25
0
  /** ** Gets the SMSoutboubdGateway for the specified name */
  public static SMSOutboundGateway GetSMSGateway(String name) {

    /* get handler */
    if (StringTools.isBlank(name)) {
      return null;
    } else {
      return SmsGatewayHandlerMap.get(name.toLowerCase());
    }
  }
Esempio n. 26
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;
  }
Esempio n. 27
0
  /* Return specified StatusCode, create if specified */
  private static StatusCode _getStatusCode(
      String accountID, Account account, String deviceID, int code, boolean createOK)
      throws DBException {
    // does not return null if 'createOK' is true

    /* account-id specified? */
    if (StringTools.isBlank(accountID)) {
      if (account == null) {
        throw new DBException("Account not specified.");
      } else {
        accountID = account.getAccountID();
      }
    } else if ((account != null) && !account.getAccountID().equals(accountID)) {
      throw new DBException("Account does not match specified AccountID.");
    }

    /* device-id specified? */
    if (StringTools.isBlank(deviceID)) {
      // throw new DBException("Device-ID not specified.");
      deviceID = ALL_DEVICES;
    }

    /* get/create entity */
    StatusCode.Key scKey = new StatusCode.Key(accountID, deviceID, code);
    if (scKey.exists()) { // may throw DBException
      StatusCode sc = scKey.getDBRecord(true);
      if (account != null) {
        sc.setAccount(account);
      }
      return sc;
    } else if (createOK) {
      StatusCode sc = scKey.getDBRecord();
      if (account != null) {
        sc.setAccount(account);
      }
      sc.setCreationDefaultValues();
      return sc; // not yet saved!
    } else {
      // record doesn't exist, and caller doesn't want us to create it
      return null;
    }
  }
Esempio n. 28
0
 /**
  * ** Gets the Java Locale instance based on the specified locale name ** @param loc The name of
  * the Locale ** @param dft The default Locale returned ** @return The Java Locale instance
  */
 public static Locale getLocale(String loc, Locale dft) {
   String locale = !StringTools.isBlank(loc) ? loc : RTConfig.getString(RTKey.LOCALE, "");
   if (StringTools.isBlank(locale)) {
     return dft;
   } else {
     int p = locale.indexOf("_");
     try {
       if (p < 0) {
         String language = locale;
         return new Locale(language);
       } else {
         String language = locale.substring(0, p);
         String country = locale.substring(p + 1);
         return new Locale(language, country);
       }
     } catch (Throwable th) {
       return dft;
     }
   }
 }
Esempio n. 29
0
  /* write JS to stream */
  public void writeJavaScript(PrintWriter out, RequestProperties reqState) throws IOException {

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

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

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

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

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

    /* event CSV parsing code */
    JavaScriptTools.writeStartJavaScript(out);
    out.write(EventUtil.getInstance().getParseMapEventJS(reqState.isFleet(), reqState.getLocale()));
    JavaScriptTools.writeEndJavaScript(out);
  }
  /** ** Return the standard "CompileTime.java" template */
  private static String standardTemplate(String tn, String pkgName) {

    /* not a standard template specification? */
    if (!StringTools.isBlank(tn) && !tn.startsWith(TEMPLATE_)) {
      Print.errPrintln("\nNot a Standard Template specification: " + tn);
      return null;
    }

    /* set default standard template name */
    if (StringTools.isBlank(tn) || tn.equals(TEMPLATE_)) {
      tn = TEMPLATE_DEFAULT;
    }

    /* default/CompileTimestamp template */
    if (tn.equalsIgnoreCase(TEMPLATE_DEFAULT)) {
      StringBuffer sb = new StringBuffer();
      sb.append(CompiletimeVars.packageLine(pkgName)).append("\n");
      sb.append("public class CompileTime\n");
      sb.append("{\n");
      sb.append("    // %{datetime=0000/00/00 00:00:00 GMT}\n");
      sb.append(
          "    public static final String SERVICE_ACCOUNT_ID   = \"%{ServiceAccount.ID=}\";\n");
      sb.append(
          "    public static final String SERVICE_ACCOUNT_NAME = \"%{ServiceAccount.Name=}\";\n");
      sb.append(
          "    public static final String SERVICE_ACCOUNT_HASH = \"%{ServiceAccount.ID.md5}\";\n");
      sb.append(
          "    public static final String SERVICE_ACCOUNT_KEY  = \"%{ServiceAccount.Key=}\";\n");
      sb.append("    public static final long   COMPILE_TIMESTAMP    = %{timestamp=0}L;\n");
      sb.append(
          "    public static final String COMPILE_DATETIME     = \"%{date=0000/00/00} %{time=00:00:00} %{timezone=GMT}\";\n");
      sb.append("    public static final long   COMPILE_SEED         = %{random.64}L;\n");
      sb.append("}\n");
      return sb.toString();
    }

    /* standard template not found */
    Print.errPrintln("\nStandard Template name not found: " + tn);
    return null;
  }