Example #1
0
  public static String getDateAsDDMMYYYYWithTimestamp(Date inputDate) {
    if (GenericUtils.isNotNull(inputDate)) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(inputDate);
      String day = new Integer(cal.get(Calendar.DATE)).toString();
      String mm = new Integer(cal.get(Calendar.MONTH) + 1).toString();
      String year = new Integer(cal.get(Calendar.YEAR)).toString();
      String hours = new Integer(cal.get(Calendar.HOUR_OF_DAY)).toString();
      String minutes = new Integer(cal.get(Calendar.MINUTE)).toString();
      String seconds = new Integer(cal.get(Calendar.SECOND)).toString();

      return StringUtils.leftPad(day, 2, "0")
          + DateUtils.DATE_SEPARATOR_CHAR
          + StringUtils.leftPad(mm, 2, "0")
          + DateUtils.DATE_SEPARATOR_CHAR
          + year
          + PortalConstant.SINGLE_SPACE
          + StringUtils.leftPad(hours, 2, "0")
          + PortalConstant.COLON
          + StringUtils.leftPad(minutes, 2, "0")
          + PortalConstant.COLON
          + StringUtils.leftPad(seconds, 2, "0");
    }

    return PortalConstant.BLANK_STRING;
  }
  /** @return Creates a unique path to an activity in the form of 2010-01-21-09-randombit */
  public static String createId() {
    Calendar c = Calendar.getInstance();

    String[] vals = new String[4];
    vals[0] = "" + c.get(Calendar.YEAR);
    vals[1] = StringUtils.leftPad("" + (c.get(Calendar.MONTH) + 1), 2, "0");
    vals[2] = StringUtils.leftPad("" + c.get(Calendar.DAY_OF_MONTH), 2, "0");
    vals[3] = StringUtils.leftPad("" + c.get(Calendar.HOUR_OF_DAY), 2, "0");

    StringBuilder id = new StringBuilder();

    for (String v : vals) {
      id.append(v).append("-");
    }

    byte[] bytes = new byte[20];
    String randomHash = "";
    try {
      if (random == null) {
        random = SecureRandom.getInstance("SHA1PRNG");
      }
      random.nextBytes(bytes);
      randomHash = Arrays.toString(bytes);
      randomHash = org.sakaiproject.nakamura.util.StringUtils.sha1Hash(randomHash);
    } catch (NoSuchAlgorithmException e) {
    } catch (UnsupportedEncodingException e) {
    }

    id.append(randomHash);
    return id.toString();
  }
Example #3
0
  public String onETLRptData() {
    List<String> msgList = new ArrayList<>();
    try {
      if (selectedOptions.isEmpty()) {
        MessageUtil.addInfo("请选择导入的报表...");
        return null;
      }

      for (String option : selectedOptions) {
        String fileSn = StringUtils.leftPad("" + (Integer.parseInt(option) - 1), 2, '0');
        String rptSn = StringUtils.leftPad(option, 2, '0');
        String filename = "LIST_" + fileSn + "_371000000.dat";
        String rptType = "10" + rptSn;
        eclImportService.importDataFromTxt(startdate, filename, rptType, msgList);
      }

      MessageUtil.addInfo("数据处理结果如下:");
      for (String s : msgList) {
        MessageUtil.addInfo(s);
      }
    } catch (Exception ex) {
      logger.error("数据处理错误。", ex);
      for (String s : msgList) {
        MessageUtil.addError(s);
      }
      MessageUtil.addError("数据处理错误。" + ex.getMessage());
    }
    return null;
  }
 @Override
 public void syncPayCancelLog(PayCancel payCancel) {
   PayCups payCups = payCupsService.findPayCups(payCancel.getPaycancelNo());
   if (payCups == null) {
     // throw new TransferFailedException(AppExCode.TRANS_NOT_EXIST, "sysncPayLog failed,not find
     // payCups");
     payCancel.setTransStatus(Const.TransStatus.FAILED); // 银联直连表无交易流水记录,未发交易,撤销失败
     return;
   }
   // 如果iso中心已经返回,但app与xposp已经断开
   String isoRespCode = payCups.getRespCode();
   if (StringUtils.isNotBlank(isoRespCode)) {
     // modify zengyj 20140716 服务端到银联已经响应成功,但客户端因超时交易未知
     if (Const.ISO_RESPCODE_OK.equals(isoRespCode)) {
       payCancel.setTransStatus(Const.TransStatus.SUCCESS);
     } else {
       payCancel.setTransStatus(Const.TransStatus.FAILED);
       isoRespCode =
           Const.TP_BEGIN_ISO + StringUtils.leftPad("" + Integer.parseInt(isoRespCode), 3, "0");
       payCancel.setErrCode(isoRespCode);
     }
     return;
   }
   CupsTrmnl cupsTrmnl =
       cupsTrmnlService.findByTrmnlNoAndMrchNo(payCups.getTrmnlNo(), payCups.getTrmnlMrchNo());
   if (cupsTrmnl == null) {
     throw new TransferFailedException(
         AppExCode.TERMINAL_NOT_EXIST, "goodee sysncPayLog failed,not find CupsTrmnl");
   }
   reversalProcess.process(cupsTrmnl, payCups, getAddress(payCancel.getAppAccessId()));
   payCancel.setTransStatus(TransStatus.FAILED);
 }
Example #5
0
  public static String getDateAsYYYYMMDD(Date inputDate) {
    if (GenericUtils.isNotNull(inputDate)) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(inputDate);
      String day = new Integer(cal.get(Calendar.DATE)).toString();
      String mm = new Integer(cal.get(Calendar.MONTH) + 1).toString();
      String year = new Integer(cal.get(Calendar.YEAR)).toString();
      return year
          + DateUtils.DATE_SEPARATOR_CHAR
          + StringUtils.leftPad(mm, 2, "0")
          + DateUtils.DATE_SEPARATOR_CHAR
          + StringUtils.leftPad(day, 2, "0");
    }

    return PortalConstant.BLANK_STRING;
  }
Example #6
0
  public static String getDateAsDDMMYYYYFromMysqlDate(Date yyyymmdd) {
    if (GenericUtils.isNotNull(yyyymmdd)) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(yyyymmdd);
      String day = new Integer(cal.get(Calendar.DATE)).toString();
      String mm = new Integer(cal.get(Calendar.MONTH) + 1).toString();
      String year = new Integer(cal.get(Calendar.YEAR)).toString();
      return StringUtils.leftPad(day, 2, "0")
          + DateUtils.DATE_SEPARATOR_CHAR
          + StringUtils.leftPad(mm, 2, "0")
          + DateUtils.DATE_SEPARATOR_CHAR
          + year;
    }

    return PortalConstant.BLANK_STRING;
  }
Example #7
0
  @Override
  public Datum eval(Tuple params) {

    if (params.isBlankOrNull(0) || params.isBlankOrNull(1)) {
      return NullDatum.get();
    }

    String fillText;
    if (hasFillCharacters) {
      fillText = params.getText(2);
    } else {
      fillText = " ";
    }

    String input = params.getText(0);
    int expected = params.getInt4(1);

    int templen = expected - params.size(0);

    if (templen <= 0) {
      return DatumFactory.createText(input.substring(0, expected));
    } else {
      return DatumFactory.createText(StringUtils.leftPad(input, expected, fillText));
    }
  }
Example #8
0
 private void doTestWithSample(
     String fromFormat, DistinguishedName dn, DistinguishedName.Format toFormat, String expected) {
   String testedRepresentation = dn.toString(toFormat);
   System.out.println(
       StringUtils.leftPad(fromFormat + " as " + toFormat.name() + ": ", 45)
           + testedRepresentation);
   assertEquals(expected, testedRepresentation);
 }
Example #9
0
 /**
  * 生成唯一的序列数
  *
  * @return
  */
 public static synchronized String randomNumber() {
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
   seq++;
   String no = String.valueOf(seq);
   String next = StringUtils.leftPad(no, lenght, "0");
   seq = (seq >= max) ? 0 : seq;
   return simpleDateFormat.format(new Date()) + next;
 }
Example #10
0
  private int ingestLine(BatchWriter bw, String line) throws MutationsRejectedException {
    String[] parts = line.split(",");
    String longitude = StringUtils.leftPad(parts[0], PADSIZE_LATLON, '0');
    String latitude = StringUtils.leftPad(parts[1], PADSIZE_LATLON, '0');
    String ndsi = parts[2];
    // String ndsi_count = parts[3];
    String land_sea_mask = parts[4];

    Text longText = new Text(longitude);
    Text latText = new Text(latitude);

    Mutation m = new Mutation(longText);
    m.put(COLF_NDSI, latText, new Value(ndsi.getBytes(StandardCharsets.UTF_8)));
    m.put(COLF_LSM, latText, new Value(land_sea_mask.getBytes(StandardCharsets.UTF_8)));
    bw.addMutation(m);

    return 2;
  }
  public String getValorFormatado() {
    BigDecimal valor = new BigDecimal(this.valor);
    if (valor == null) return "0,00";

    return StringUtils.leftPad(
        new DecimalFormat("###,###,##0.00").format(valor.setScale(2, BigDecimal.ROUND_HALF_UP)),
        9,
        " ");
  }
Example #12
0
 /**
  * 生成长度为length的字符串,字符串只包含数字
  *
  * @param length 字符串的长度
  * @return
  */
 public static String buildRandom(final int length) {
   // 长度为length的最多整数
   String maxStr = StringUtils.rightPad("1", length + 1, '0');
   long max = Long.parseLong(maxStr);
   long i = random.nextLong(); // 取得随机数
   i = Math.abs(i) % max; // 取正数,并限制其长度
   String value = StringUtils.leftPad(String.valueOf(i), length, '0');
   return value;
 }
Example #13
0
 public String getContractno() {
   if (StringUtils.isBlank(contractno)) {
     this.contractno =
         new StringBuilder()
             .append("contract")
             .append(StringUtils.leftPad(room_id + "", 4, "0"))
             .toString();
   }
   return contractno;
 }
Example #14
0
 public String convertirLetras(final CantidadMonetaria importe) {
   double val1 = importe.amount().abs().doubleValue();
   int entero = importe.amount().intValue();
   double cent = val1 - (double) entero;
   long valor = Math.round(cent * 100);
   final String svalor = String.valueOf(valor);
   final String ok = StringUtils.leftPad(svalor, 2, '0');
   num_letras = decmillon(importe.amount().intValue());
   num_letras += " PESOS {0}/100 M.N.";
   return MessageFormat.format(num_letras, ok);
 }
 private static String dumpRef(long ref) {
   return StringUtils.leftPad(Long.toBinaryString(ref), 64, "0")
       + " o="
       + Ref.getOffset(ref)
       + " s="
       + Ref.getStateByte(ref)
       + " l="
       + Ref.hasList(ref)
       + " h="
       + Long.toBinaryString(Ref.getHashBits(ref));
 }
Example #16
0
  public static int generatetRowKeySalt(final String[] r, int idx, int rNum) {
    // TODO Auto-generated method stub
    // [4][8][8][4]
    // String r[]=rowItems;

    try {
      String revMsisdn = r[idx];
      long msisdn;

      if (StrUtils.isBlankorZeroString(revMsisdn)) // 如果是空号码,那么生成一个随机的18位到数字
      {

        msisdn = (long) (Math.random() * 1000000000000000000L); // 生成一个随机到18位数字
        revMsisdn = StringUtils.rightPad(String.valueOf(msisdn), 18, "0");
        // 补全到16位到长整数
        msisdn = Long.parseLong(revMsisdn);
      } else {
        // 对小于11位的号码,如固话号码,左补0到11位(正常到msisdn位长)
        revMsisdn = StringUtils.leftPad((new StringBuffer(r[idx])).reverse().toString(), 11, "0");
        // 注意,有可能含有非数字字符,正常返回11位到long数字,当以下异常时,将取字符串hashcode,并返回固定位长的long
        // 1)revMsisdn可能包含字符,2)revMsisdn长度可能超过11位
        // msisdn最长应该在11-15位间,返回16位右补长字段即可
        msisdn = getAbsoluteLong(revMsisdn, 16);
      }

      int salt = Math.abs(revMsisdn.hashCode()) % rNum;
      if (salt == 97) {
        // System.out.println(r[idx]);
        if (hm2.containsKey(r[idx] + "")) {
          int counter = hm2.get(r[idx]);
          counter++;
          hm2.put(r[idx] + "", counter);
        } else {
          hm2.put(r[idx], 1);
        }
      }

      //	if(salt==142)
      //	{
      //		int counter=phone.get(revMsisdn);
      //		phone.put(revMsisdn, counter+1);
      //	}

      return salt;

    } catch (Exception e) {
      // e.printStackTrace();

      // CLogger.logStackTrace(e);
      return -1;
    }
  }
Example #17
0
  /**
   * 在指定的位置追加内容
   *
   * @param str 待追加的字符串
   * @param size 总长度
   * @param padStr 需要追加的内容
   * @param format 对齐方式;1、左对齐;0、右对齐
   * @return
   */
  public static String padString(String str, int size, String padStr, int format) {
    String newStr = null;
    switch (format) { // 根据对齐模式,选择空格的合适的位置
      case FORMAT_RIGHT: // 右对齐,将零字符放在字符串左边
        newStr = StringUtils.leftPad(str, size, padStr);
        break;
      case FORMAT_LEFT: // 左对齐,将零字符放在字符串右边
        newStr = StringUtils.rightPad(str, size, padStr);
        break;
    }

    return newStr;
  }
 private static void handleRightAdjust(TerminalSendAction terminalSendAction) {
   List<TerminalField> fields = terminalSendAction.getFields();
   for (TerminalField terminalField : fields) {
     if (terminalField.getRightAdjust() != RightAdjust.NONE) {
       if (terminalField.getLength() > terminalField.getValue().length()) {
         String fillerChar = terminalField.getRightAdjust() == RightAdjust.ZERO_FILL ? "0" : " ";
         String newValue =
             StringUtils.leftPad(terminalField.getValue(), terminalField.getLength(), fillerChar);
         terminalField.setValue(newValue);
       }
     }
   }
 }
  private static String formatWWN(String wwn) {
    if (StringUtils.isBlank(wwn)) {
      return null;
    }
    // Left pad with zeros to make 16 chars, trim any excess
    wwn = StringUtils.substring(StringUtils.leftPad(wwn, 16, '0'), 0, 16);

    StrBuilder sb = new StrBuilder();
    for (int i = 0; i < wwn.length(); i += 2) {
      sb.appendSeparator(':');
      sb.append(StringUtils.substring(wwn, i, i + 2));
    }
    return sb.toString();
  }
Example #20
0
 private void writeText() {
   if (!writeText) {
     return;
   }
   String filename =
       String.format(
           TEXT_NAME, name, StringUtils.leftPad(String.valueOf(page.getPageNumber()), 3, '0'));
   File file = getFile(filename);
   try {
     String text = getResultantText();
     FileUtils.writeStringToFile(file, text);
   } catch (IOException e) {
     System.out.println("error writing text file");
     e.printStackTrace();
   }
 }
Example #21
0
  private static String getTopFeatures(Vector vector, String[] dictionary, int numTerms) {

    List<TermIndexWeight> vectorTerms = new ArrayList<TermIndexWeight>();

    Iterator<Vector.Element> iter = vector.iterateNonZero();
    while (iter.hasNext()) {
      Vector.Element elt = iter.next();
      vectorTerms.add(new TermIndexWeight(elt.index(), elt.get()));
    }

    // Sort results in reverse order (ie weight in descending order)
    Collections.sort(
        vectorTerms,
        new Comparator<TermIndexWeight>() {
          @Override
          public int compare(TermIndexWeight one, TermIndexWeight two) {
            return Double.compare(two.weight, one.weight);
          }
        });

    Collection<Pair<String, Double>> topTerms = new LinkedList<Pair<String, Double>>();

    for (int i = 0; (i < vectorTerms.size()) && (i < numTerms); i++) {
      int index = vectorTerms.get(i).index;
      String dictTerm = dictionary[index];
      if (dictTerm == null) {
        log.error("Dictionary entry missing for {}", index);
        continue;
      }
      topTerms.add(new Pair<String, Double>(dictTerm, vectorTerms.get(i).weight));
    }

    StringBuilder sb = new StringBuilder(100);

    for (Pair<String, Double> item : topTerms) {
      String term = item.getFirst();
      sb.append("\n\t\t");
      sb.append(StringUtils.rightPad(term, 40));
      sb.append("=>");
      sb.append(StringUtils.leftPad(item.getSecond().toString(), 20));
    }
    return sb.toString();
  }
 private Set<String> addCoachesToExternalDataAndAttributeService(int quota) {
   Set<String> usernames = Sets.newHashSet();
   if (quota <= 0) {
     return usernames;
   }
   for (int i = 1; i <= quota; i++) {
     String paddedIdx = StringUtils.leftPad("" + i, 3, "0");
     String username = "******" + paddedIdx;
     createExternalPerson(
         "bulk_coach_school_id_" + paddedIdx,
         username,
         "BulkCoach",
         "BulkCoach" + paddedIdx,
         "" + i,
         "bulkcoach" + paddedIdx + "@school.edu");
     usernames.add(username);
   }
   personAttributesService.getCoachUsernames().addAll(usernames);
   sessionFactory.getCurrentSession().flush();
   return usernames;
 }
  @Test
  public void testMatrix() {
    OptionsMatrix<Integer> matrix = new OptionsMatrix<Integer>(4, Integer[].class);

    Row<Integer>[] table =
        matrix
            .addVariant("a", 0, 10, 200)
            .addVariant("b", 0, 200)
            .addVariant("c", 10, 150, 500)
            .addVariant("d", 0, 200)
            .createTable();

    System.out.println(Arrays.toString(matrix.getVariantNames()));

    for (Row<Integer> row : table) {

      for (int j = 0; j < row.size(); j++) {
        System.out.print(StringUtils.leftPad(Integer.toString(row.get(j)), 4));
      }
      System.out.println();
    }
  }
 @Override
 public void syncCashLoadLog(PayCashLoad cashLoad, Integer appSyn) {
   PayCups payCups = payCupsService.findPayCups(cashLoad.getCashLoadNo());
   if (payCups == null) {
     // throw new TransferFailedException(AppExCode.TRANS_NOT_EXIST, "sysncPayLog failed,not find
     // payCups");
     cashLoad.setTransStatus(Const.TransStatus.FAILED); // 银联直连表无交易流水记录,未发交易,消费失败
     return;
   }
   if (appSyn == null) {
     // 如果iso中心已经返回,但app与xposp已经断开,写卡失败
     String isoRespCode = payCups.getRespCode();
     if (StringUtils.isNotBlank(isoRespCode)) {
       // 服务端到银联已经响应成功,但客户端因超时交易未知
       if (Const.ISO_RESPCODE_OK.equals(isoRespCode)) {
         cashLoad.setTransStatus(Const.TransStatus.SUCCESS);
       } else {
         cashLoad.setTransStatus(Const.TransStatus.FAILED);
         isoRespCode =
             Const.TP_BEGIN_ISO
                 + StringUtils.leftPad(
                     "" + Integer.parseInt(isoRespCode.replace("A", "10")), 3, "0");
         cashLoad.setErrCode(isoRespCode);
       }
       return;
     }
   }
   CupsTrmnl cupsTrmnl =
       cupsTrmnlService.findByTrmnlNoAndMrchNo(payCups.getTrmnlNo(), payCups.getTrmnlMrchNo());
   if (cupsTrmnl == null) {
     throw new TransferFailedException(
         AppExCode.TERMINAL_NOT_EXIST, "sysncPayLog failed,not find CupsTrmnl");
   }
   reversalProcess.process(cupsTrmnl, payCups);
   cashLoad.setTransStatus(TransStatus.FAILED);
 }
Example #25
0
 public Month(Integer value) {
   this.value = StringUtils.leftPad(Integer.toString(value), 2, '0');
 }
Example #26
0
  public Map<String, Object> save(Room room) {
    // 保存或修改房源
    Map<String, Object> result = new HashMap<String, Object>();
    if (room == null) {
      result.put("error", "房源信息为空...");
    }
    if (!isExist(room)) { // 如果不存在 房源名称是否重复
      if (room.getId() != null && room.getId() > 0) // 修改的情况
      {
        /*
         * 新增的字段 bed; wardrobe; air_conditioning;tv; kitchen; bashroom
         */
        String[] updateFields =
            new String[] {
              "room_name = ?",
              "address = ?",
              "price = ?",
              "rental_start_time = ?",
              "rental_end_time = ?",
              "status = ?",
              "`desc` = ?",
              "size = ?",
              "kind = ?",
              "floor = ?",
              "orient = ?",
              "occupancy = ?",
              "metro=?",
              "comm_id = ?",
              "bed=?",
              "wardrobe=?",
              "air_conditioning=?",
              "tv=?",
              "gasstove=?",
              "washing=?",
              "heater = ?",
              "refrigerator = ?",
              " microwaveOven= ?",
              "room_host= ?",
              "recommend=?",
              "recommendTarget=?",
              "cityid=?,decoration = ?,rent_type = ?,company_id=?,smartlock=?",
              "isRecommend=?"
            };
        Object[] fieldsValue =
            new Object[] {
              room.getRoom_name(),
              room.getAddress(),
              room.getPrice(),
              room.getRental_start_time(),
              room.getRental_end_time(),
              room.getStatus(),
              room.getDesc(),
              room.getSize(),
              room.getKind(),
              room.getFloor(),
              room.getOrient(),
              room.getOccupancy(),
              room.getMetro(),
              room.getComm_id(),
              room.getBed(), // 床
              room.getWardrobe(), // 衣柜
              room.getAir_conditioning(), // 空调
              room.getTv(), // 电视
              room.getGasstove(), // 燃气灶
              room.getWashing(), // 洗衣机
              room.getHeater(), // 热水器
              room.getRefrigerator(), // 冰箱
              room.getMicrowaveOven(), // 微波炉
              room.getRoom_host(),
              room.getRecommend(),
              room.getRecommendTarget(),
              room.getCityid(),
              room.getDecoration(),
              room.getRent_type(),
              room.getCompany_id(),
              room.getSmartlock(),
              room.getIsRecommend()
            };
        /*
         * for( int i = 0; i < updateFields.length; i++ ){
         * System.out.println(updateFields[i] + ":" + String.valueOf(
         * fieldsValue[i] )); }
         */

        String sql =
            "update "
                + Room.TABLENAME
                + " set "
                + StringUtils.join(updateFields, ",")
                + " where id ="
                + room.getId().toString();
        // System.out.println(sql );
        int affected = jdbcTemplate.update(sql, fieldsValue);
        if (affected > 0) {
          result.put("success", "修改成功");
        } else {
          result.put("success", "修改失败");
        }
      } else { // 新增

        String sql =
            "insert into "
                + Room.TABLENAME
                + " (room_name,"
                + "address,price,"
                + "rental_start_time,"
                + "rental_end_time,"
                + "status,size,"
                + "kind,floor,"
                + "orient,occupancy,"
                + "metro,`desc`,"
                + "comm_id,"
                + " bed,wardrobe,"
                + "air_conditioning,"
                + "tv,gasstove,"
                + "washing,heater,refrigerator,microwaveOven,room_host,"
                + "recommend,"
                + "recommendTarget,cityid,createtime,decoration,rent_type,company_id, smartlock, isRecommend) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        System.out.println(sql);

        int affected =
            jdbcTemplate.update(
                sql,
                new Object[] {
                  room.getRoom_name(),
                  room.getAddress(),
                  room.getPrice(),
                  room.getRental_start_time(),
                  room.getRental_end_time(),
                  room.getStatus(),
                  room.getSize(),
                  room.getKind(),
                  room.getFloor(),
                  room.getOrient(),
                  room.getOccupancy(),
                  room.getMetro(),
                  room.getDesc(),
                  room.getComm_id(),
                  room.getBed(),
                  room.getWardrobe(),
                  room.getAir_conditioning(),
                  room.getTv(),
                  room.getGasstove(), // 燃气灶
                  room.getWashing(), // 洗衣机
                  room.getHeater(), // 热水器
                  room.getRefrigerator(), // 冰箱
                  room.getMicrowaveOven(), // 微波炉
                  room.getRoom_host(),
                  room.getRecommend(),
                  room.getRecommendTarget(),
                  room.getCityid(),
                  CalendarUtil.getInstance().getCurrentTime(),
                  room.getDecoration(),
                  room.getRent_type(),
                  room.getCompany_id(),
                  room.getSmartlock(),
                  room.getIsRecommend()
                });
        // 获得id,再更新房源编号

        if (affected > 0) {
          String query = "select last_insert_id() as id from " + Image.TABLENAME + " limit 1";
          System.out.println("图片id查询语句:" + query);
          int id = jdbcTemplate.queryForInt(query);
          String roomSeq = room.getRoomSeq() + StringUtils.leftPad(id + "", 5, "0");
          affected =
              jdbcTemplate.update(
                  "update " + Room.TABLENAME + " set roomSeq = ? where id = ?",
                  new Object[] {roomSeq, id});
          if (affected > 0) {
            System.out.println("房源保存成功,且房源编号更新成功...");
          }
          result.put("success", "保存成功");
        } else {
          result.put("success", "保存失败");
        }
      }
    } else {
      result.put("error", "房源名称已存在");
    }

    return result;
  }
Example #27
0
 /**
  * Devolve o número do documento formatado (com 4 digitos)
  *
  * @return
  */
 public String getNumeroDoDocumentoFormatado() {
   return StringUtils.leftPad(this.numeroDocumento, 4, '0');
 }
Example #28
0
  private void testBinarySortableFastCase(int caseNum, boolean doNonRandomFill, Random r)
      throws Throwable {

    SerdeRandomRowSource source = new SerdeRandomRowSource();
    source.init(r);

    int rowCount = 1000;
    Object[][] rows = source.randomRows(rowCount);

    if (doNonRandomFill) {
      MyTestClass.nonRandomRowFill(rows, source.primitiveCategories());
    }

    // We need to operate on sorted data to fully test BinarySortable.
    source.sort(rows);

    StructObjectInspector rowStructObjectInspector = source.rowStructObjectInspector();

    PrimitiveTypeInfo[] primitiveTypeInfos = source.primitiveTypeInfos();
    int columnCount = primitiveTypeInfos.length;

    int writeColumnCount = columnCount;
    StructObjectInspector writeRowStructObjectInspector = rowStructObjectInspector;
    boolean doWriteFewerColumns = r.nextBoolean();
    if (doWriteFewerColumns) {
      writeColumnCount = 1 + r.nextInt(columnCount);
      if (writeColumnCount == columnCount) {
        doWriteFewerColumns = false;
      } else {
        writeRowStructObjectInspector = source.partialRowStructObjectInspector(writeColumnCount);
      }
    }

    String fieldNames = ObjectInspectorUtils.getFieldNames(rowStructObjectInspector);
    String fieldTypes = ObjectInspectorUtils.getFieldTypes(rowStructObjectInspector);
    String order;
    order = StringUtils.leftPad("", columnCount, '+');
    String nullOrder;
    nullOrder = StringUtils.leftPad("", columnCount, 'a');
    AbstractSerDe serde_ascending =
        TestBinarySortableSerDe.getSerDe(fieldNames, fieldTypes, order, nullOrder);

    AbstractSerDe serde_ascending_fewer = null;
    if (doWriteFewerColumns) {
      String partialFieldNames = ObjectInspectorUtils.getFieldNames(writeRowStructObjectInspector);
      String partialFieldTypes = ObjectInspectorUtils.getFieldTypes(writeRowStructObjectInspector);

      serde_ascending_fewer =
          TestBinarySortableSerDe.getSerDe(partialFieldNames, partialFieldTypes, order, nullOrder);
    }

    order = StringUtils.leftPad("", columnCount, '-');
    nullOrder = StringUtils.leftPad("", columnCount, 'z');
    AbstractSerDe serde_descending =
        TestBinarySortableSerDe.getSerDe(fieldNames, fieldTypes, order, nullOrder);

    AbstractSerDe serde_descending_fewer = null;
    if (doWriteFewerColumns) {
      String partialFieldNames = ObjectInspectorUtils.getFieldNames(writeRowStructObjectInspector);
      String partialFieldTypes = ObjectInspectorUtils.getFieldTypes(writeRowStructObjectInspector);

      serde_descending_fewer =
          TestBinarySortableSerDe.getSerDe(partialFieldNames, partialFieldTypes, order, nullOrder);
    }

    boolean[] columnSortOrderIsDesc = new boolean[columnCount];
    Arrays.fill(columnSortOrderIsDesc, false);
    byte[] columnNullMarker = new byte[columnCount];
    Arrays.fill(columnNullMarker, BinarySortableSerDe.ZERO);
    byte[] columnNotNullMarker = new byte[columnCount];
    Arrays.fill(columnNotNullMarker, BinarySortableSerDe.ONE);

    /*
     * Acending.
     */
    testBinarySortableFast(
        source,
        rows,
        columnSortOrderIsDesc,
        columnNullMarker,
        columnNotNullMarker,
        serde_ascending,
        rowStructObjectInspector,
        serde_ascending_fewer,
        writeRowStructObjectInspector,
        /* ascending */ true,
        primitiveTypeInfos,
        /* useIncludeColumns */ false, /* doWriteFewerColumns */
        false,
        r);

    testBinarySortableFast(
        source,
        rows,
        columnSortOrderIsDesc,
        columnNullMarker,
        columnNotNullMarker,
        serde_ascending,
        rowStructObjectInspector,
        serde_ascending_fewer,
        writeRowStructObjectInspector,
        /* ascending */ true,
        primitiveTypeInfos,
        /* useIncludeColumns */ true, /* doWriteFewerColumns */
        false,
        r);

    if (doWriteFewerColumns) {
      testBinarySortableFast(
          source,
          rows,
          columnSortOrderIsDesc,
          columnNullMarker,
          columnNotNullMarker,
          serde_ascending,
          rowStructObjectInspector,
          serde_ascending_fewer,
          writeRowStructObjectInspector,
          /* ascending */ true,
          primitiveTypeInfos,
          /* useIncludeColumns */ false, /* doWriteFewerColumns */
          true,
          r);

      testBinarySortableFast(
          source,
          rows,
          columnSortOrderIsDesc,
          columnNullMarker,
          columnNotNullMarker,
          serde_ascending,
          rowStructObjectInspector,
          serde_ascending_fewer,
          writeRowStructObjectInspector,
          /* ascending */ true,
          primitiveTypeInfos,
          /* useIncludeColumns */ true, /* doWriteFewerColumns */
          true,
          r);
    }

    /*
     * Descending.
     */
    Arrays.fill(columnSortOrderIsDesc, true);

    testBinarySortableFast(
        source,
        rows,
        columnSortOrderIsDesc,
        columnNullMarker,
        columnNotNullMarker,
        serde_descending,
        rowStructObjectInspector,
        serde_ascending_fewer,
        writeRowStructObjectInspector,
        /* ascending */ false,
        primitiveTypeInfos,
        /* useIncludeColumns */ false, /* doWriteFewerColumns */
        false,
        r);

    testBinarySortableFast(
        source,
        rows,
        columnSortOrderIsDesc,
        columnNullMarker,
        columnNotNullMarker,
        serde_descending,
        rowStructObjectInspector,
        serde_ascending_fewer,
        writeRowStructObjectInspector,
        /* ascending */ false,
        primitiveTypeInfos,
        /* useIncludeColumns */ true, /* doWriteFewerColumns */
        false,
        r);

    if (doWriteFewerColumns) {
      testBinarySortableFast(
          source,
          rows,
          columnSortOrderIsDesc,
          columnNullMarker,
          columnNotNullMarker,
          serde_descending,
          rowStructObjectInspector,
          serde_descending_fewer,
          writeRowStructObjectInspector,
          /* ascending */ false,
          primitiveTypeInfos,
          /* useIncludeColumns */ false, /* doWriteFewerColumns */
          true,
          r);

      testBinarySortableFast(
          source,
          rows,
          columnSortOrderIsDesc,
          columnNullMarker,
          columnNotNullMarker,
          serde_descending,
          rowStructObjectInspector,
          serde_descending_fewer,
          writeRowStructObjectInspector,
          /* ascending */ false,
          primitiveTypeInfos,
          /* useIncludeColumns */ true, /* doWriteFewerColumns */
          true,
          r);
    }
  }
Example #29
0
 private static String getIntegerString(int length) {
   String value = StringUtils.leftPad(String.valueOf(getUniqueInt()), length, '0');
   return StringUtils.right(value, length);
 }
Example #30
0
  @Override
  public String[] saveToString() {

    ArrayList<String> file = new ArrayList<String>();

    String line = "'" + defaults.getStringDefaultValue(OxDefaultFields.SERIESCODE).getStringValue();
    line += "  <" + defaults.getIntegerDefaultValue(OxDefaultFields.FIRSTYEAR).getStringValue();
    line += "-" + defaults.getIntegerDefaultValue(OxDefaultFields.LASTYEAR).getStringValue() + "> ";
    line += defaults.getStringDefaultValue(OxDefaultFields.DESCRIPTION).getStringValue() + "'";

    file.add(line);

    line = defaults.getIntegerDefaultValue(OxDefaultFields.SERIESLENGTH).getStringValue() + ",";
    line += defaults.getIntegerDefaultValue(OxDefaultFields.STARTYEAR).getStringValue();

    file.add(line);

    // Data
    Integer col = 0;
    line = "";
    Boolean hasCounts = false;
    for (TridasValue val : valuesGroup.getValues()) {
      col++;

      if (col > 10) {
        file.add(line.substring(0, line.length() - 1));
        line = "";
        col = 1;
      }

      line += StringUtils.leftPad(val.getValue(), 3) + " ";

      if (val.isSetCount()) hasCounts = true;
    }

    if (line.length() > 0) {
      file.add(line.substring(0, line.length() - 1));
    }

    file.add("");

    // Add counts section if applicable
    if (hasCounts) {
      col = 0;
      line = "";
      for (TridasValue val : valuesGroup.getValues()) {
        col++;

        if (col > 10) {
          file.add(line.substring(0, line.length() - 1));
          line = "";
          col = 1;
        }

        if (val.isSetCount()) {
          line += StringUtils.leftPad(val.getCount().toString(), 3) + " ";
        } else {
          line += StringUtils.leftPad("0".toString(), 3) + " ";
          defaults.addConversionWarning(
              new ConversionWarning(WarningType.INVALID, I18n.getText("oxford.countsEmpty")));
        }
      }
      if (line.length() > 0) {
        file.add(line.substring(0, line.length() - 1));
      }
    }

    // Comments
    if (defaults.getStringDefaultValue(OxDefaultFields.COMMENTS).getValue() != null) {
      file.add(defaults.getStringDefaultValue(OxDefaultFields.COMMENTS).getStringValue());
    }

    // Return file
    return file.toArray(new String[0]);
  }