示例#1
1
  public static String escapeBy(String str, String escChars, char escCh) {
    StringBuffer sb = null;
    int cPos, ePos, mPos;

    cPos = 0;
    while (cPos < str.length()) {
      ePos = Integer.MAX_VALUE;
      for (int i = 0; i < escChars.length(); i++) {
        mPos = str.indexOf(escChars.charAt(i), cPos);

        if (mPos == -1) continue;

        if (mPos < ePos) ePos = mPos;
      }

      if (ePos == Integer.MAX_VALUE) {
        if (sb == null) return str;

        sb.append(str.substring(cPos));
        return sb.toString();
      }

      if (sb == null) sb = new StringBuffer(str.length() * 2);

      sb.append(str.substring(cPos, ePos));
      sb.append(escCh);
      sb.append(str.charAt(ePos));

      cPos = ePos + 1;
    }

    if (sb != null) return sb.toString();

    return str;
  }
 /**
  * This is for debug only: print out training matrices in a CSV type format so that the matrices
  * can be examined in a spreadsheet program for debugging purposes.
  */
 private void WriteCSVfile(
     List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
   p("tagList.size()=" + tagList.size());
   try {
     FileWriter fw = new FileWriter(fileName + ".txt");
     PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
     // write the first title row:
     StringBuffer sb = new StringBuffer(500);
     for (int i = 0, size = colNames.size(); i < size; i++) {
       sb.append("," + colNames.get(i));
     }
     bw.println(sb.toString());
     // loop on remaining rows:
     for (int i = 0, size = buf.length; i < size; i++) {
       sb.delete(0, sb.length());
       sb.append(rowNames.get(i));
       for (int j = 0, size2 = buf[i].length; j < size2; j++) {
         sb.append("," + buf[i][j]);
       }
       bw.println(sb.toString());
     }
     bw.close();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
示例#3
1
 public Map<String, Object> checkCommunicationStatus(UpsStatus upsStatus, AlarmRule alarmRule) {
   Map<String, Object> communicationStatusMap = new HashMap<String, Object>();
   StateEnum runState = StateEnum.good;
   StringBuffer alarmContent = new StringBuffer();
   StringBuffer alarmRuleType = new StringBuffer();
   OperationType operationType = alarmRule.getOperationType();
   Integer value = alarmRule.getValue();
   Integer minValue = alarmRule.getMinValue();
   Integer maxValue = alarmRule.getMaxValue();
   runState =
       alarmRuleService.ruleCompare(
           operationType,
           Double.parseDouble(upsStatus.getCommunicationStatus() + ""),
           value,
           minValue,
           maxValue,
           alarmRule.getState());
   if (runState != StateEnum.good) {
     alarmContent.append("").append(alarmRule.getRemark()).append("、");
     alarmRuleType.append(alarmRule.getAlarmRuleType()).append("、");
   }
   communicationStatusMap.put("runState", runState);
   communicationStatusMap.put("alarmContent", alarmContent.toString());
   communicationStatusMap.put("alarmRuleType", alarmRuleType.toString());
   return communicationStatusMap;
 }
  public void update(EventBean[] fuel, EventBean[] empty) {
    // TODO Auto-generated method stub
    System.out.println(" Warning ! fuel low ");
    SpeedStream stream = (SpeedStream) fuel[0].getUnderlying();
    System.out.println("Low Fuel identified in stream :" + (stream));
    Map.Entry<String, Location> entry =
        NearestVehicleClassifier.getNearestVehicle(
            stream.getVin(), new Location(stream.getLat(), stream.getLon()));

    StringBuffer buffer = new StringBuffer(stream.toString());
    buffer.append(",");
    buffer.append("Needs Refuelling");
    buffer.append(",");
    buffer.append("Low Fuel");
    buffer.append(",");
    buffer.append("Not Notified");
    buffer.append(",");
    buffer.append(entry != null ? entry.getKey() : "No vehicles nearby");
    System.out.println(buffer.toString());
    try {
      TcpClient.sendMessage(buffer.toString());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#5
1
  /**
   * 是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
   *
   * @return boolean
   */
  public boolean isTenpaySign() {
    StringBuffer sb = new StringBuffer();
    Set es = this.parameters.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry) it.next();
      String k = (String) entry.getKey();
      String v = (String) entry.getValue();
      if (!"sign".equals(k) && null != v && !"".equals(v)) {
        sb.append(k + "=" + v + "&");
      }
    }

    sb.append("key=" + this.getKey());

    // 算出摘要
    String enc = "UTF-8";
    String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();

    String tenpaySign = this.getParameter("sign").toLowerCase();

    // debug信息
    this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:" + tenpaySign);

    return tenpaySign.equals(sign);
  }
示例#6
0
 /** Work */
 protected void doWork() {
   m_summary = new StringBuffer();
   m_errors = new StringBuffer();
   //
   int count = 0;
   int countError = 0;
   MAlert[] alerts = m_model.getAlerts(false);
   for (int i = 0; i < alerts.length; i++) {
     if (!processAlert(alerts[i])) countError++;
     count++;
   }
   //
   String summary = "Total=" + count;
   if (countError > 0) summary += ", Not processed=" + countError;
   summary += " - ";
   m_summary.insert(0, summary);
   //
   int no = m_model.deleteLog();
   m_summary.append("Logs deleted=").append(no);
   //
   MAlertProcessorLog pLog = new MAlertProcessorLog(m_model, m_summary.toString());
   pLog.setReference(
       "#"
           + String.valueOf(p_runCount)
           + " - "
           + TimeUtil.formatElapsed(new Timestamp(p_startWork)));
   pLog.setTextMsg(m_errors.toString());
   pLog.save();
 } //	doWork
示例#7
0
 static final String roman(boolean upper, int number) {
   StringBuffer buf = new StringBuffer();
   for (int pos = roman_numbers.length - 1; pos >= 0; pos -= 2) {
     int f = number / roman_numbers[pos];
     if (f != 0) {
       number = number % (f * roman_numbers[pos]);
     }
     if (f > 4 && f < 9) {
       buf.append(roman_chars[pos + 1]);
       f -= 5;
     }
     if (f == 4) {
       buf.append(roman_chars[pos]);
       buf.append(roman_chars[pos + 1]);
     } else if (f == 9) {
       buf.append(roman_chars[pos]);
       buf.append(roman_chars[pos + 2]);
     } else {
       for (; f > 0; f--) {
         buf.append(roman_chars[pos]);
       }
     }
   }
   return upper ? buf.toString().toUpperCase() : buf.toString();
 }
 /**
  * Echo the CAS server's "push" of the PGTIOU and PGTID.
  *
  * @param pgtIou - the proxy granting ticket IOU
  * @param pgtID - the proxy granting ticket (id)
  * @return the number of echoes successfully executed.
  */
 private int echoRequest(String pgtIou, String pgtID) {
   /*
    * I hate this URLs as concatenated strings.
    * This should be refactored to use a real URL class, preferably back
    * when the URLs were parsed in init().
    * However, this should work.  -awp9
    */
   int successes = 0;
   for (Iterator iter = this.echoTargets.iterator(); iter.hasNext(); ) {
     StringBuffer target = new StringBuffer();
     target.append((String) iter.next());
     if (target.indexOf("?") == -1) {
       target.append("?");
     } else {
       target.append("&");
     }
     target.append(ProxyTicketReceptor.PGT_IOU_PARAM).append("=").append(pgtIou);
     target.append("&").append(ProxyTicketReceptor.PGT_ID_PARAM).append("=").append(pgtID);
     try {
       SecureURL.retrieve(target.toString());
       successes++;
     } catch (Throwable t) {
       log.error("Failed to retrieve [" + target.toString() + "]", t);
     }
   }
   return successes;
 }
  /**
   * Cut or padd the string to the given size
   *
   * @param size the wanted length
   * @param padChar char to use for padding (must be of length()==1!)
   * @return the string with correct lenght, padded with pad if necessary
   */
  public static String forceToSizeLeft(final String str, final int size, final char padChar) {
    if (str != null && str.length() == size) {
      return str;
    }

    final StringBuffer tmp;
    if (str == null) {
      tmp = new StringBuffer(size);
    } else {
      tmp = new StringBuffer(str);
    }

    if (tmp.length() > size) {
      tmp.setLength(size);
      return tmp.toString(); // do cutting
    } else {
      final StringBuffer t2 = new StringBuffer(size);

      final int arsize = size - tmp.length();
      final char[] ar = new char[arsize];
      for (int i = 0; i < arsize; i++) {
        ar[i] = padChar;
      }
      t2.append(ar);
      t2.append(tmp);
      return t2.toString();
    }
  }
示例#10
0
  private static String parseString(CharacterIterator it) {
    char c = it.next();
    if (c == '"') {
      it.next();
      return EMPTY_STRING;
    }
    StringBuffer buffer = new StringBuffer();
    while (c != '"') {
      if (Character.isISOControl(c))
        throw error(
            "illegal iso control character: '" + Integer.toHexString(c) + "'",
            it); //$NON-NLS-1$ //$NON-NLS-2$);

      if (c == '\\') {
        c = it.next();
        switch (c) {
          case '"':
          case '\\':
          case '/':
            buffer.append(c);
            break;
          case 'b':
            buffer.append('\b');
            break;
          case 'f':
            buffer.append('\f');
            break;
          case 'n':
            buffer.append('\n');
            break;
          case 'r':
            buffer.append('\r');
            break;
          case 't':
            buffer.append('\t');
            break;
          case 'u':
            StringBuffer unicode = new StringBuffer(4);
            for (int i = 0; i < 4; i++) {
              unicode.append(it.next());
            }
            try {
              buffer.append((char) Integer.parseInt(unicode.toString(), 16));
            } catch (NumberFormatException e) {
              throw error(
                  "expected a unicode hex number but was '" + unicode.toString() + "'",
                  it); //$NON-NLS-1$ //$NON-NLS-2$););
            }
            break;
          default:
            throw error(
                "illegal escape character '" + c + "'", it); // $NON-NLS-1$ //$NON-NLS-2$););
        }
      } else buffer.append(c);

      c = it.next();
    }
    c = it.next();
    return buffer.toString();
  }
  protected static String addUnderscores(String name, boolean pluralize) {
    StringBuffer buf = new StringBuffer(name.replace('.', '_'));
    for (int i = 1; i < buf.length() - 1; i++) {
      if (Character.isLowerCase(buf.charAt(i - 1))
          && Character.isUpperCase(buf.charAt(i))
          && Character.isLowerCase(buf.charAt(i + 1))) {
        buf.insert(i++, '_');
      }
    }

    if (pluralize) {
      String[] splitTableNameFragments = buf.toString().toLowerCase().split("_");

      StringBuffer buf2 = new StringBuffer();

      for (int i = 0; i < splitTableNameFragments.length; i++) {

        if (i < (splitTableNameFragments.length - 1)) {
          buf2.append(splitTableNameFragments[i]);
          buf2.append("_");
        } else {
          buf2.append(English.plural(splitTableNameFragments[i]));
        }
      }

      return buf2.toString().toUpperCase();
    }

    return buf.toString().toUpperCase();
  }
示例#12
0
  public static String escapeBy(String str, char ch, char escCh) {
    StringBuffer sb = null;
    int cPos, ePos;

    cPos = 0;
    while (cPos < str.length()) {
      ePos = str.indexOf(ch, cPos);

      if (ePos == -1) {
        if (sb == null) return str;

        sb.append(str.substring(cPos));
        return sb.toString();
      }

      if (sb == null) sb = new StringBuffer(str.length() * 2);

      sb.append(str.substring(cPos, ePos));
      sb.append(escCh);
      sb.append(ch);

      cPos = ePos + 1;
    }

    if (sb != null) return sb.toString();

    return str;
  }
示例#13
0
  /**
   * Return an Oracle date literal with the same value as a string formatted using ISO 8601.
   *
   * <p>Convert an ISO8601 date string to one of the following results: to_date('1995-05-23',
   * 'YYYY-MM-DD') to_date('1995-05-23 09:23:59', 'YYYY-MM-DD HH24:MI:SS')
   *
   * <p>Implementation restriction: Currently, only the following subsets of ISO8601 are supported:
   * YYYY-MM-DD YYYY-MM-DDThh:mm:ss
   */
  @Override
  public String getDateLiteral(String isoDate) {
    String normalLiteral = super.getDateLiteral(isoDate);

    if (isDateOnly(isoDate)) {
      StringBuffer val = new StringBuffer();
      val.append("to_date(");
      val.append(normalLiteral);
      val.append(", 'YYYY-MM-DD')");
      return val.toString();
    } else if (isTimeOnly(isoDate)) {
      StringBuffer val = new StringBuffer();
      val.append("to_date(");
      val.append(normalLiteral);
      val.append(", 'HH24:MI:SS')");
      return val.toString();
    } else if (isDateTime(isoDate)) {
      normalLiteral = normalLiteral.substring(0, normalLiteral.lastIndexOf('.')) + "'";

      StringBuffer val = new StringBuffer(26);
      val.append("to_date(");
      val.append(normalLiteral);
      val.append(", 'YYYY-MM-DD HH24:MI:SS')");
      return val.toString();
    } else {
      return "UNSUPPORTED:" + isoDate;
    }
  }
示例#14
0
 @Override
 public Map<String, Object> checkBatteryVoltage(UpsStatus upsStatus, AlarmRule alarmRule) {
   Map<String, Object> batteryVoltageMap = new HashMap<String, Object>();
   StateEnum runState = StateEnum.good;
   StringBuffer alarmContent = new StringBuffer();
   StringBuffer alarmRuleType = new StringBuffer();
   OperationType operationType = alarmRule.getOperationType();
   Integer value = alarmRule.getValue();
   Integer minValue = alarmRule.getMinValue();
   Integer maxValue = alarmRule.getMaxValue();
   runState =
       alarmRuleService.ruleCompare(
           operationType,
           Double.parseDouble(upsStatus.getBatteryVoltage() + ""),
           value,
           minValue,
           maxValue,
           alarmRule.getState());
   if (runState == StateEnum.error) {
     alarmContent.append("").append(alarmRule.getRemark()).append("、");
     alarmRuleType.append(alarmRule.getAlarmRuleType()).append("、");
   }
   batteryVoltageMap.put("runState", runState);
   batteryVoltageMap.put("alarmContent", alarmContent.toString());
   batteryVoltageMap.put("alarmRuleType", alarmRuleType.toString());
   return batteryVoltageMap;
 }
示例#15
0
  private void executeScript(Statement statement, PrintWriter out) {
    String s = new String();
    StringBuffer sb = new StringBuffer();

    try {
      String path = getServletContext().getRealPath("/config");

      FileReader fr = new FileReader(new File(path + "/tictactoe.sql"));

      BufferedReader br = new BufferedReader(fr);

      while ((s = br.readLine()) != null) {
        sb.append(s);
      }
      br.close();

      String[] inst = sb.toString().split(";");

      for (int i = 0; i < inst.length; i++) {
        if (!inst[i].trim().equals("")) {
          statement.execute(inst[i]);
          out.println("-" + inst[i] + "<br>");
        }
      }

    } catch (Exception e) {
      out.println("*** Error : " + e.toString());
      out.println("*** ");
      out.println("*** Error : ");
      e.printStackTrace();
      out.println("################################################");
      out.println(sb.toString());
    }
  }
示例#16
0
  /**
   * @param code
   * @param parentCode
   * @param description
   * @return list of EgPartytype filtered by optional conditions
   */
  public List<EgPartytype> getPartyTypeDetailFilterBy(
      final String code, final String parentCode, final String description) {
    final StringBuffer qryStr = new StringBuffer();
    qryStr.append(
        "select distinct ptype From EgPartytype ptype where ptype.createdby is not null ");
    Query qry = getCurrentSession().createQuery(qryStr.toString());

    if (code != null && !code.equals("")) {
      qryStr.append(" and (upper(ptype.code) like :code)");
      qry = getCurrentSession().createQuery(qryStr.toString());
    }
    if (parentCode != null && !parentCode.equals("")) {
      qryStr.append(" and (upper(ptype.egPartytype.code) like :parentCode)");
      qry = getCurrentSession().createQuery(qryStr.toString());
    }
    if (description != null && !description.equals("")) {
      qryStr.append(" and (upper(ptype.description) like :description)");
      qry = getCurrentSession().createQuery(qryStr.toString());
    }

    if (code != null && !code.equals("")) {
      qry.setString("code", "%" + code.toUpperCase().trim() + "%");
    }
    if (parentCode != null && !parentCode.equals("")) {
      qry.setString("parentCode", "%" + parentCode.toUpperCase().trim() + "%");
    }
    if (description != null && !description.equals("")) {
      qry.setString("description", "%" + description.toUpperCase().trim() + "%");
    }

    return qry.list();
  }
示例#17
0
  @Override
  public String getSequenceForColumn(
      String schemaName, String tableName, String columnName, Connection cx) throws SQLException {

    String sequenceName = tableName + "_" + columnName + "_SEQUENCE";

    // sequence names have to be upper case to select values from them
    sequenceName = sequenceName.toUpperCase();
    Statement st = cx.createStatement();
    try {
      StringBuffer sql = new StringBuffer();
      sql.append("SELECT * FROM INFORMATION_SCHEMA.SEQUENCES ");
      sql.append("WHERE SEQUENCE_NAME = '").append(sequenceName).append("'");

      dataStore.getLogger().fine(sql.toString());
      ResultSet rs = st.executeQuery(sql.toString());
      try {
        if (rs.next()) {
          return sequenceName;
        }
      } finally {
        dataStore.closeSafe(rs);
      }
    } finally {
      dataStore.closeSafe(st);
    }

    return null;
  }
  @Override
  public String toString() {
    final StringBuffer stringBuffer2 = new StringBuffer();
    final String STOPID = "stopId: ";
    final String VALUES = "; values:";
    final char TAB = '\t';
    final char RETURN = '\n';

    for (Id stopId : this.getOccupancyStopIds()) { // Only occupancy!
      StringBuffer stringBuffer = new StringBuffer();
      stringBuffer.append(STOPID);
      stringBuffer.append(stopId);
      stringBuffer.append(VALUES);

      boolean hasValues = false; // only prints stops with volumes > 0
      @SuppressWarnings("deprecation")
      int[] values = this.getOccupancyVolumesForStop(stopId);

      for (int ii = 0; ii < values.length; ii++) {
        hasValues = hasValues || (values[ii] > 0);

        stringBuffer.append(TAB);
        stringBuffer.append(values[ii]);
      }
      stringBuffer.append(RETURN);
      if (hasValues) stringBuffer2.append(stringBuffer.toString());
    }
    return stringBuffer2.toString();
  }
示例#19
0
  /**
   * Normally called to initialize CoherenceCache. To be able to test the method without having
   * <code>com.tangosol.net.CacheFactory</code> implementation, it can also be called with a test
   * implementations classname.
   *
   * @param implementation Cache implementation classname to initialize.
   * @param params Parameters to initialize the cache (e.g. name, capacity).
   * @throws CacheAcquireException If cache can not be initialized.
   */
  @SuppressWarnings("unchecked")
  public void initialize(final String implementation, final Properties params)
      throws CacheAcquireException {
    super.initialize(params);

    String cacheURL = params.getProperty("cacheURL", DEFAULT_CACHE_URL);
    String cacheProperties = params.getProperty("cacheProperties", DEFAULT_CACHE_PROPERTIES);

    StringBuffer clusterURL = new StringBuffer();
    clusterURL.append(cacheURL);
    clusterURL.append(getName());
    clusterURL.append("?");
    clusterURL.append(cacheProperties);

    if (LOG.isDebugEnabled()) {
      LOG.debug(clusterURL.toString());
    }

    try {
      ClassLoader ldr = this.getClass().getClassLoader();
      Class<?> cls = ldr.loadClass(implementation);
      setCache(
          (Map)
              invokeStaticMethod(
                  cls, "find", TYPES_FIND_CACHE, new Object[] {clusterURL.toString()}));
    } catch (Exception e) {
      LOG.error("Problem!", e);
      String msg = "Error creating Gigaspaces cache: " + e.getMessage();
      LOG.error(msg, e);
      throw new CacheAcquireException(msg, e);
    }
  }
示例#20
0
 public Map<String, Object> checkElectricQuantity(UpsStatus upsStatus, AlarmRule alarmRule) {
   Map<String, Object> electricQuantityMap = new HashMap<String, Object>();
   StateEnum runState = StateEnum.good;
   StringBuffer alarmContent = new StringBuffer();
   StringBuffer alarmRuleType = new StringBuffer();
   OperationType operationType = alarmRule.getOperationType();
   Integer value = alarmRule.getValue();
   Integer minValue = alarmRule.getMinValue();
   Integer maxValue = alarmRule.getMaxValue();
   runState =
       alarmRuleService.ruleCompare(
           operationType,
           upsStatus.getElectricQuantity(),
           value,
           minValue,
           maxValue,
           alarmRule.getState());
   if (runState != StateEnum.good) {
     alarmContent.append("").append(alarmRule.getRemark()).append("、");
     alarmRuleType.append(alarmRule.getAlarmRuleType()).append("、");
   }
   electricQuantityMap.put("runState", runState);
   electricQuantityMap.put("alarmContent", alarmContent.toString());
   electricQuantityMap.put("alarmRuleType", alarmRuleType.toString());
   return electricQuantityMap;
 }
  /**
   * Creates the tickets.
   *
   * @param assignedToUser the assigned to user
   * @param subjectId the subject id
   * @param title the title
   * @param content the content
   * @return the JSON object
   * @throws Exception the exception
   */
  public JSONObject createTickets(
      String assignedToUser, String subjectId, String title, String content) throws Exception {
    logger.info("Executing Create ticket username: "******"/")) {
      url.append("/");
    }
    url.append("createStandardTicket");

    String templateObject = getJSON(assignedToUser, subjectId, title, content);

    BasicAuthorizationSLClient client = new BasicAuthorizationSLClient(username, apiKey);
    ClientResponse clientResponse = client.executePOST(url.toString(), templateObject);
    String response = clientResponse.getEntity(String.class);
    logger.info(
        "Executed create Ticket: clientResponse: "
            + clientResponse.getStatusCode()
            + ", response: "
            + response);

    if (clientResponse.getStatusCode() == 200) {
      JSONObject json = new JSONObject(response);
      logger.debug("Create Ticket: JSON Response: " + response);
      return json;
    }

    throw new Exception(
        "Could not create Ticket: Code: "
            + clientResponse.getStatusCode()
            + ", Reason: "
            + response);
  }
示例#22
0
  /**
   * 排序字段名替换成序号
   *
   * @param src
   * @param replacExpression
   * @return
   */
  public static String sortFieldNameToIndex(String src, String replacExpression) {
    if (strIsEmpty(src)) return null;
    List<String> replacList = Arrays.asList(replacExpression.toUpperCase().split(","));
    boolean isCopy = false;
    StringBuffer desc = new StringBuffer();
    StringBuffer v = new StringBuffer();

    for (char c : (src + " ").toUpperCase().toCharArray()) {
      if (c == 44) { // 逗号
        if (v.length() > 0) {
          int idx = replacList.indexOf(v.toString());
          if (idx == -1) desc.append(v.toString());
          else desc.append(idx + 1);
          desc.append(" ASC");
          v = new StringBuffer();
        }
        isCopy = false;
        desc.append(c);
      } else if (isCopy) {
        desc.append(c);
      } else if (c == 9 || c == 32) { // tab符, 空格
        if (v.length() > 0) {
          int idx = replacList.indexOf(v.toString());
          if (idx == -1) desc.append(v.toString());
          else desc.append(idx + 1);
          v = new StringBuffer();
          isCopy = true;
          desc.append(c);
        }
      } else {
        v.append(c);
      }
    }
    return desc.toString();
  }
示例#23
0
  private String decodeEntities(String s) {
    StringBuffer buf = new StringBuffer();

    Matcher m = P_ENTITY.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.decode(match).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENTITY_UNICODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENCODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    s = validateEntities(s);
    return s;
  }
示例#24
0
  /**
   * 한건의 쿠폰번호를 발행한다. [쿠폰번호 생성 규칙] 쿠폰분류코드 1자리 + 금일일자 2자리 + 금일일자에 해당되는 key 3자리 + 영문 2자리 + 랜덤번호 2자리 +
   * checkSum 2자리
   *
   * @param noDivCd String 쿠폰종류코드
   * @return String 생성 된 쿠폰번호
   * @throws Exception
   */
  private String genNo(String noDivCd) throws Exception {
    StringBuffer sb = new StringBuffer();

    // 1. 랜덤 영문 2자리
    String issueAlpha = RandomStringUtils.random(2, FIRST_FORMAT);

    // 2. 랜덤번호
    String randomNo3 = genRandomNo(3); // 4자리 생성
    String randomNo5 = genRandomNo(5); // 5자리 생성

    StringBuffer sb1 = new StringBuffer();
    StringBuffer sb2 = new StringBuffer();

    // 3. 앞의 5자리 번호 연결
    sb1.append(issueAlpha) // 랜덤 영문 2자리
        .append(randomNo3); // 랜덤 번호 3자리

    // 4. 뒤 5자리 번호 연경
    sb2.append(randomNo5); // 랜덤번호  5자리

    String checkSum = makeCheckSum(sb1.toString(), sb2.toString());

    sb.append(sb1).append(sb2).append(checkSum);

    return sb.toString();
  }
示例#25
0
  @Override
  public void exitClassDeclaration(ClassDeclarationContext ctx) {
    try {
      // To test need to remove
      if (LogUtil.isDebugEnabled(LOG_NAME)) {
        LogUtil.debug(
            CLASS_NAME,
            "exitClassDeclaration",
            "NearestMatch==>" + nearestMatchingsIfsForMethod,
            LOG_NAME);
      }

      conditionWriter.write(conditionText.toString());
      patternMatchWriter.write(patternText.toString());
      if (LogUtil.isDebugEnabled(LOG_NAME)) {
        // LogUtil.debug(CLASS_NAME,"exitClassDeclaration"
        // ,conditionWriter.toString(), LOG_NAME);
        // LogUtil.debug(CLASS_NAME,ctx.Identifier().getText(),"Skip count==>"+count,
        // LOG_NAME);
      }
    } catch (IOException ie) {
      System.out.println("exitclass" + ie.toString());
      LogUtil.error(CLASS_NAME, "exitClassDeclaration", ie.toString(), LOG_NAME);
      // ie.printStackTrace();
    }
  }
示例#26
0
 @SuppressWarnings("unchecked")
 public List<InstPlayerCard> getListPagination(
     int index, int size, String strWhere, int instPlayerId) throws Exception {
   try {
     StringBuffer sql = null;
     PlayerMemObj playerMemObj = getPlayerMemObjByPlayerId(instPlayerId);
     if (instPlayerId != 0 && isUseCach() && playerMemObj != null) {
       sql = new StringBuffer("select id, version from Inst_Player_Card ");
     } else {
       sql = new StringBuffer("select * from Inst_Player_Card ");
     }
     if (index <= 0 || size <= 0) {
       throw new Exception("index or size must bigger than zero");
     } else {
       index = (index - 1) * size;
     }
     if (strWhere != null && !strWhere.equals("")) {
       sql.append(" where " + strWhere);
     }
     sql.append(" limit " + index + "," + size + "");
     if (instPlayerId != 0 && isUseCach() && playerMemObj != null) {
       return listCacheCommonHandler(sql.toString(), instPlayerId);
     } else {
       return (List<InstPlayerCard>)
           this.getJdbcTemplate().query(sql.toString(), new ItemMapper());
     }
   } catch (Exception e) {
     throw e;
   }
 }
示例#27
0
  public static String propertiesToString(Map props, boolean newline) {
    StringBuffer buf = new StringBuffer(props.size() * 32);
    buf.append("{");

    if (props == null || props.isEmpty()) {
      buf.append("}");
      return buf.toString();
    }

    if (newline) {
      buf.append(Utility.CRLF);
    }

    Object[] entries = props.entrySet().toArray();
    int i, numEntries = entries.length;
    for (i = 0; i < numEntries - 1; i++) {
      appendMaskedProperty(buf, (Map.Entry) entries[i]);
      if (newline) {
        buf.append(Utility.CRLF);
      } else {
        buf.append(", ");
      }
    }

    // don't forget the last one
    appendMaskedProperty(buf, (Map.Entry) entries[i]);

    if (newline) {
      buf.append(Utility.CRLF);
    }

    buf.append("}");
    return buf.toString();
  }
示例#28
0
文件: POP3Client.java 项目: TAEB/anna
  /**
   * * Login to the POP3 server with the given username and authentication information. Use this
   * method when connecting to a server requiring authentication using the APOP command. Because the
   * timestamp produced in the greeting banner varies from server to server, it is not possible to
   * consistently extract the information. Therefore, after connecting to the server, you must call
   * {@link org.apache.commons.net.pop3.POP3#getReplyString getReplyString } and parse out the
   * timestamp information yourself.
   *
   * <p>You must first connect to the server with {@link org.apache.commons.net.SocketClient#connect
   * connect } before attempting to login. A login attempt is only valid if the client is in the
   * {@link org.apache.commons.net.pop3.POP3#AUTHORIZATION_STATE AUTHORIZATION_STATE } . After
   * logging in, the client enters the {@link org.apache.commons.net.pop3.POP3#TRANSACTION_STATE
   * TRANSACTION_STATE } . After connecting, you must parse out the server specific information to
   * use as a timestamp, and pass that information to this method. The secret is a shared secret
   * known to you and the server. See RFC 1939 for more details regarding the APOP command.
   *
   * <p>
   *
   * @param username The account name being logged in to.
   * @param timestamp The timestamp string to combine with the secret.
   * @param secret The shared secret which produces the MD5 digest when combined with the timestamp.
   * @return True if the login attempt was successful, false if not.
   * @exception IOException If a network I/O error occurs in the process of logging in.
   * @exception NoSuchAlgorithmException If the MD5 encryption algorithm cannot be instantiated by
   *     the Java runtime system. *
   */
  public boolean login(String username, String timestamp, String secret)
      throws IOException, NoSuchAlgorithmException {
    int i;
    byte[] digest;
    StringBuffer buffer, digestBuffer;
    MessageDigest md5;

    if (getState() != AUTHORIZATION_STATE) return false;

    md5 = MessageDigest.getInstance("MD5");
    timestamp += secret;
    digest = md5.digest(timestamp.getBytes());
    digestBuffer = new StringBuffer(128);

    for (i = 0; i < digest.length; i++) digestBuffer.append(Integer.toHexString(digest[i] & 0xff));

    buffer = new StringBuffer(256);
    buffer.append(username);
    buffer.append(' ');
    buffer.append(digestBuffer.toString());

    if (sendCommand(POP3Command.APOP, buffer.toString()) != POP3Reply.OK) return false;

    setState(TRANSACTION_STATE);

    return true;
  }
  /**
   * 保存checkbox被选中的信息
   *
   * @param mReceivers
   */
  public void selected(ArrayList<ReceiverItem> mReceivers) {
    Intent receiverIntent = new Intent();

    StringBuffer ownername = new StringBuffer();
    StringBuffer ownerid = new StringBuffer();

    if (mReceivers.size() > 0) {
      for (int i = 0; i < mReceivers.size(); i++) {
        if (mReceivers.get(i).ischecked) {
          ownername.append(mReceivers.get(i).receiver_name);
          ownername.append(",");

          ownerid.append(mReceivers.get(i).receiver_id);
          ownerid.append(",");
        }
      }
    }

    String ownernames = ownername.toString();
    String ownerids = ownerid.toString();
    if (ownernames.lastIndexOf(",") > 0) {
      ownernames = ownernames.substring(0, ownernames.lastIndexOf(","));
      ownerids = ownerids.substring(0, ownerids.lastIndexOf(","));
    }

    Bundle bundle = new Bundle();
    bundle.putString(AddApplicationActivity.KEY_RECEIVER_LIST, ownernames);
    bundle.putString(AddApplicationActivity.KEY_RECEIVER_ID, ownerids);

    receiverIntent.putExtra(AddApplicationActivity.KEY_RECEIVER_BUNDLE, bundle);

    ((Activity) context).setResult(StateActivity.RESULT_CODE, receiverIntent);
  }
示例#30
-3
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) jb.append(line);
    } catch (Exception e) {
      System.out.println("Erreur");
    }
    JSONObject json = new JSONObject(jb.toString());
    System.out.println(jb.toString());

    Petition p = new Petition();

    p.setTitle(json.getValue("title"));
    p.setDescription(json.getValue("text"));
    response.getWriter().println(p.toString());

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    // Récupération de l'utilisateur google courant

    if (user != null) {
      System.out.println(user.toString());
    } else {
      System.out.println("user null");
    }

    ObjectifyService.ofy().save().entities(p).now();
    response.getWriter().println("Ajout effectué");
  }