コード例 #1
0
ファイル: SqlParam.java プロジェクト: axelbarfod/PageObject
 public SqlParam(String value, int size) {
   if (size > 0) {
     this.value = StringUtils.rightPad(value, size);
   } else {
     this.value = value;
   }
 }
コード例 #2
0
  @Override
  protected void doExecute(ApplicationService applicationService)
      throws ApplicationServiceException {

    Set<Application> applications = applicationService.getApplications();
    console.printf("%s%10s%n", "State", "Name");
    for (Application curApp : applications) {
      ApplicationStatus appStatus = applicationService.getApplicationStatus(curApp);
      // only show applications that have features (gets rid of repo
      // aggregator 'apps')
      if (!curApp.getFeatures().isEmpty()) {
        console.print("[");
        switch (appStatus.getState()) {
          case ACTIVE:
            console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString());
            break;
          case FAILED:
            console.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
            break;
          case INACTIVE:
            // don't set a color
            break;
          case UNKNOWN:
            console.print(Ansi.ansi().fg(Ansi.Color.YELLOW).toString());
            break;
          default:
            break;
        }
        console.print(StringUtils.rightPad(appStatus.getState().toString(), STATUS_COLUMN_LENGTH));
        console.print(Ansi.ansi().reset().toString());
        console.println("] " + curApp.getName());
      }
    }
    return;
  }
コード例 #3
0
ファイル: RandomUtils.java プロジェクト: huagang/yy-utils
 /**
  * 返回指定位数的整数
  *
  * @param length
  * @return
  */
 public static int buildIntRandom(final int length) {
   String maxStr = StringUtils.rightPad("1", length + 1, '0');
   long max = Long.parseLong(maxStr);
   long i = Math.abs(random.nextLong()) % max;
   String rand = String.valueOf(i);
   return Integer.parseInt(rand);
 }
コード例 #4
0
  public ViewStatusCalculationWorker(
      final ToolContext toolContext,
      UniqueId portfolioId,
      final ViewStatusOption option,
      final ExecutorService executorService) {
    ArgumentChecker.notNull(toolContext, "toolContex");
    ArgumentChecker.notNull(portfolioId, "portfolioId");
    ArgumentChecker.notNull(option, "option");
    ArgumentChecker.notNull(option.getUser(), "option.user");
    ArgumentChecker.notNull(option.getMarketDataSpecification(), "option.marketDataSpecification");
    ArgumentChecker.notNull(executorService, "executorService");

    validateComponentsInToolContext(toolContext);
    _portfolioId = portfolioId;
    _user = option.getUser();
    _marketDataSpecification = option.getMarketDataSpecification();
    Map<String, Collection<String>> valueRequirementBySecType =
        scanValueRequirementBySecType(portfolioId, toolContext);
    if (s_logger.isDebugEnabled()) {
      StringBuilder strBuf = new StringBuilder();
      for (String securityType : Sets.newTreeSet(valueRequirementBySecType.keySet())) {
        Set<String> valueNames = Sets.newTreeSet(valueRequirementBySecType.get(securityType));
        strBuf.append(
            String.format(
                "%s\t%s\n", StringUtils.rightPad(securityType, 40), valueNames.toString()));
      }
      s_logger.debug("\n{}\n", strBuf.toString());
    }
    _toolContext = toolContext;
    _executor = executorService;
    _valueRequirementBySecType = valueRequirementBySecType;
  }
コード例 #5
0
  @Override
  public RaptorAliasResult apply(ChatConsoleController controller, String command) {
    if (command.equalsIgnoreCase("=tag")) {
      StringBuilder builder = new StringBuilder(1000);

      String[] tags = UserTagService.getInstance().getTags();
      Arrays.sort(tags);

      builder.append("Available Tags: ");
      for (String tag : tags) {
        builder.append(tag).append(" ");
      }

      builder.append("\n\nTagged users:\n");
      for (String tag : tags) {
        String[] users = UserTagService.getInstance().getUsersInTag(tag);
        if (users.length > 0) {
          builder.append(tag).append(":\n");
          Arrays.sort(users);
          int counter = 0;
          for (int i = 0; i < users.length; i++) {
            builder.append(StringUtils.rightPad(users[i], 20));
            counter++;
            if (counter == 3) {
              counter = 0;
              builder.append("\n");
            }
          }
          builder.append("\n\n");
        }
      }
      return new RaptorAliasResult(null, builder.toString().trim());
    }
    return null;
  }
コード例 #6
0
  /**
   * 1:ANSI X9.8 Format(不带主账号) 06
   *
   * @param password
   * @param pinKey
   * @return
   * @throws Exception
   */
  public static String pinEncode(String password, byte[] pinKey) throws Exception {
    int passwordLength = password.length();
    String pin_fmt = StringUtils.rightPad("0" + passwordLength + password, 16, "F");
    byte[] pinBLOCK = DumpUtils.hexToBytes(pin_fmt);
    System.out.println("无主帐号pinBlock:" + Dump.getHexDump(pinBLOCK));

    byte[] des3Info = DesUtils.tripDesEncrypt(pinBLOCK, pinKey);
    return DumpUtils.bytesToHex(des3Info);
  }
コード例 #7
0
ファイル: RandomUtils.java プロジェクト: huagang/yy-utils
 /**
  * 生成长度为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;
 }
コード例 #8
0
 public static long getAbsoluteLong(String str, int fixLen) {
   try {
     return Long.parseLong(str);
   } catch (NumberFormatException e) {
     // 返回18位的long数字,通过补全str到hashcode
     return Long.parseLong(
         StringUtils.rightPad(String.valueOf(Math.abs(str.hashCode())), fixLen, "0"));
   }
 }
コード例 #9
0
  public final void testExecuteWhenRedirectURIExceedsMaxLength() throws Exception {
    String url =
        StringUtils.rightPad("/YourRhn.do", (int) CreateRedirectURI.MAX_URL_LENGTH + 1, "x");

    mockRequest.stubs().method("getRequestURI").will(returnValue(url));

    CreateRedirectURI command = new CreateRedirectURI();
    String redirectUrl = command.execute(getMockRequest());

    assertEquals(LoginAction.DEFAULT_URL_BOUNCE, redirectUrl);
  }
コード例 #10
0
ファイル: XDContainer.java プロジェクト: hexiaofeng/spring-xd
 @Override
 public void stop() {
   if (this.context != null && isContainerRunning()) {
     this.containerRunning = false;
     // Publish the container stopped event before the context is closed.
     this.context.publishEvent(new ContainerStoppedEvent(this));
     this.context.close();
     ((ConfigurableApplicationContext) context.getParent()).close();
     if (logger.isInfoEnabled()) {
       final String message = "Stopped container: " + this.jvmName;
       final StringBuilder sb = new StringBuilder(LINE_SEPARATOR);
       sb.append(StringUtils.rightPad("", message.length(), "-"))
           .append(LINE_SEPARATOR)
           .append(message)
           .append(LINE_SEPARATOR)
           .append(StringUtils.rightPad("", message.length(), "-"))
           .append(LINE_SEPARATOR);
       logger.info(sb.toString());
     }
   }
 }
コード例 #11
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;
    }
  }
コード例 #12
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;
  }
コード例 #13
0
  @Override
  public boolean exportData(String typeId, String dataId, File directory) {
    directory.mkdirs();

    final File exportTempFile;
    try {
      exportTempFile =
          File.createTempFile(
              SafeFilenameUtils.makeSafeFilename(StringUtils.rightPad(dataId, 2, '-') + "-"),
              SafeFilenameUtils.makeSafeFilename("." + typeId),
              directory);
    } catch (IOException e) {
      throw new RuntimeException(
          "Could not create temp file to export " + typeId + " " + dataId, e);
    }

    try {
      final String fileName = this.exportData(typeId, dataId, new StreamResult(exportTempFile));
      if (fileName == null) {
        logger.info("Skipped: type={} id={}", typeId, dataId);
        return false;
      }

      final File destFile = new File(directory, fileName + "." + typeId + ".xml");
      if (destFile.exists()) {
        logger.warn(
            "Exporting "
                + typeId
                + " "
                + dataId
                + " but destination file already exists, it will be overwritten: "
                + destFile);
        destFile.delete();
      }
      FileUtils.moveFile(exportTempFile, destFile);
      logger.info("Exported: {}", destFile);

      return true;
    } catch (Exception e) {
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }

      throw new RuntimeException("Failed to export " + typeId + " " + dataId, e);
    } finally {
      FileUtils.deleteQuietly(exportTempFile);
    }
  }
コード例 #14
0
  /**
   * 1:ANSI X9.8 Format(带主账号)
   *
   * @param password
   * @param pinKey
   * @param pan
   * @return
   * @throws Exception
   */
  public static String pinEncode(String password, byte[] pinKey, String pan) throws Exception {
    int passwordLength = password.length();
    int panLength = pan.length();
    String pin_fmt = StringUtils.rightPad("0" + passwordLength + password, 16, "F");
    byte[] pinBLOCK = DumpUtils.hexToBytes(pin_fmt);
    String pin_str = "0000" + pan.substring(3, 15);
    System.out.println("pinBlock:" + pin_str);
    byte[] panByte = DumpUtils.hexToBytes(pin_str);
    for (int i = 0; i < panByte.length; i++) {
      pinBLOCK[i] ^= panByte[i];
    }
    System.out.println("有主帐号pinBlock:" + Dump.getHexDump(pinBLOCK));

    byte[] des3Info = DesUtils.tripDesEncrypt(pinBLOCK, pinKey);
    return DumpUtils.bytesToHex(des3Info);
  }
コード例 #15
0
ファイル: SmsHelper.java プロジェクト: liyq1406/fbi-haierfip
  private static String sendMsgToDep(String msg) throws IOException {
    InetAddress addr = InetAddress.getByName("10.143.18.20");
    Socket socket = new Socket();
    int timeout_ms = 30 * 1000;
    try {
      socket.connect(new InetSocketAddress(addr, 61002), timeout_ms);
      socket.setSoTimeout(timeout_ms);

      // 组报文头
      String smsTxnCode = "0011";
      msg = smsTxnCode + msg;
      String msgLen =
          StringUtils.rightPad(
              "" + (msg.getBytes("GBK").length + MSG_HEADER_LENGTH), MSG_HEADER_LENGTH, " ");

      OutputStream os = socket.getOutputStream();
      os.write((msgLen + msg).getBytes("GBK"));
      os.flush();
      InputStream is = socket.getInputStream();

      byte[] inHeaderBuf = new byte[MSG_HEADER_LENGTH];
      int readNum = is.read(inHeaderBuf);
      if (readNum == -1) {
        throw new RuntimeException("服务器连接已关闭!");
      }
      if (readNum < MSG_HEADER_LENGTH) {
        throw new RuntimeException("读取报文头长度部分错误...");
      }

      int bodyLen = Integer.parseInt((new String(inHeaderBuf).trim())) - MSG_HEADER_LENGTH;
      byte[] inBodyBuf = new byte[bodyLen];

      readNum = is.read(inBodyBuf); // 阻塞读
      if (readNum != bodyLen) {
        throw new RuntimeException("报文长度错误,应为:[" + bodyLen + "], 实际获取长度:[" + readNum + "]");
      }

      return new String(inBodyBuf, "GBK");
    } finally {
      try {
        socket.close();
      } catch (IOException e) {
        //
      }
    }
  }
コード例 #16
0
ファイル: ArpaUtil.java プロジェクト: enom/rdap
 /**
  * parse IPV6 ARPA domain to IP bytes.
  *
  * @param name an ARPA string.
  * @return ARPA.
  */
 private static NetworkInBytes parseIpV6Arpa(String name) {
   LOGGER.debug("parseIp6Arpa, name:" + name);
   String arpa = StringUtils.removeEndIgnoreCase(name, CHAR_DOT + DomainUtil.IPV6_ARPA_SUFFIX);
   arpa = StringUtils.remove(arpa, CHAR_DOT);
   String ip = StringUtils.reverse(arpa);
   String fullIp = StringUtils.rightPad(ip, 32, '0');
   byte[] startIpBytes = DatatypeConverter.parseHexBinary(fullIp);
   int networkMask = StringUtils.length(arpa) * 4;
   IPv6Address fromByteArray = IPv6Address.fromByteArray(startIpBytes);
   IPv6Network network =
       IPv6Network.fromAddressAndMask(
           fromByteArray, IPv6NetworkMask.fromPrefixLength(networkMask));
   NetworkInBytes result =
       new NetworkInBytes(
           IpVersion.V6, network.getFirst().toByteArray(), network.getLast().toByteArray());
   return result;
 }
コード例 #17
0
  /**
   * 银行卡密码加密,先进行与主账号异或后进行3DES加密
   *
   * @param pin 银行卡密码
   * @param pan 银行卡号
   * @return
   */
  public static String getENPinBlock(String pin, String pan, byte[] pinKey) {
    String panStr = pan.substring(pan.length() - 12 - 1, pan.length() - 1);
    byte[] panBlock = new byte[8];
    System.arraycopy(CodecUtils.hex2byte(panStr), 0, panBlock, 2, 6);

    String pinLen = pin.length() + "";
    String pinStr = StringUtils.rightPad(pin, 14, 'F');
    byte[] pinBlock = new byte[8];
    System.arraycopy(CodecUtils.hex2byte(pinLen), 0, pinBlock, 0, 1);
    System.arraycopy(CodecUtils.hex2byte(pinStr), 0, pinBlock, 1, 7);

    for (int i = 0; i < panBlock.length; i++) {
      pinBlock[i] ^= panBlock[i];
    }
    byte[] des3Info = DesUtils.tripDesEncrypt(panBlock, pinKey);
    return DumpUtils.bytesToHex(des3Info);
  }
コード例 #18
0
ファイル: ClusterDumper.java プロジェクト: shopittome/mahout
  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();
  }
コード例 #19
0
 /**
  * 解密算法
  *
  * @param data 已加过密过的数据
  * @param key 解密的密钥,不能为空,与加密的密钥相同
  * @return 解密后的密码
  */
 public String decrypt(String data, String key) {
   if (data == null || key == null) return null;
   // 补全24位
   key = StringUtils.rightPad(key, 24);
   try {
     SecretKey secretKey = buildSecretKey(key);
     byte[] decrypted_pwd;
     synchronized (decryptCipher) {
       // 以解密模式初始化密钥
       decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
       // 解密密码
       decrypted_pwd = decryptCipher.doFinal(base64Decode(data));
     }
     // 得到结果
     return new String(decrypted_pwd);
   } catch (Exception e) {
     logger.error("When encrypt error occurs. Maybe your secretKey is not right", e);
     return null;
   }
 }
コード例 #20
0
ファイル: RightscaleTest.java プロジェクト: barnyard/pi
  // this test shows that Rightscale fails when the size of the file exceeds 999999 bytes
  @Override
  public void testPutLargeObject() throws Exception {
    // setup
    setupBucketMetaData(USER_NAME, bucketName);
    FileUtils.forceMkdir(new File(String.format("%s/%s", BUCKET_ROOT, bucketName)));
    String largeTestData = StringUtils.rightPad("a", 999999, 'a');
    String tmpFilePath = writeToTmpFile(largeTestData);

    // act
    runCommand(
        String.format(
            "%s put %s %s \"File.open('%s')\"",
            rightscaleBaseCommandWithGoodUser, bucketName, objectName, tmpFilePath));

    // assert
    assertResponse(commandExecutor.getOutputLines(), "true");
    File file = new File(String.format("%s/%s/%s", BUCKET_ROOT, bucketName, objectName));
    String readFileToString = FileUtils.readFileToString(file);
    assertEquals(largeTestData, readFileToString);
  }
コード例 #21
0
    /**
     * 加密算法
     *
     * @param data 等待加密的数据,不能为空
     * @param key 加密的密钥,不能为空
     * @return 加密以后的数据
     */
    public String encrypt(String data, String key) {
      if (data == null || key == null) return null;
      // 补全24位
      key = StringUtils.rightPad(key, 24);
      byte[] encrypted_pwd = null;

      try {
        SecretKey secretKey = buildSecretKey(key);
        synchronized (encryptCipher) {
          // 以加密模式初始化密钥
          encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
          // 加密密码
          encrypted_pwd = encryptCipher.doFinal(data.getBytes());
        }
        // 转成字符串,得到加密后的密码(新)
        return base64Encode(encrypted_pwd);
      } catch (Exception e) {
        logger.error("When encrypt error occurs. Maybe your secretKey is not right", e);
        return null;
      }
    }
コード例 #22
0
ファイル: CollectorDetail.java プロジェクト: hawking81/kfs
  public void setFromFileForCollectorDetail(
      String detailLine,
      Map<String, String> accountRecordBalanceTypeMap,
      Date curDate,
      UniversityDate universityDate,
      int lineNumber,
      MessageMap messageMap) {

    try {

      final Map<String, Integer> pMap =
          getCollectorDetailFieldUtil().getFieldBeginningPositionMap();

      detailLine =
          org.apache.commons.lang.StringUtils.rightPad(
              detailLine, GeneralLedgerConstants.getSpaceAllCollectorDetailFields().length(), ' ');

      setCreateDate(curDate);
      if (!GeneralLedgerConstants.getSpaceUniversityFiscalYear()
          .equals(
              detailLine.substring(
                  pMap.get(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR),
                  pMap.get(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE)))) {
        try {
          setUniversityFiscalYear(
              new Integer(
                  getValue(
                      detailLine,
                      pMap.get(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR),
                      pMap.get(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE))));
        } catch (NumberFormatException e) {
          messageMap.putError(
              KFSConstants.GLOBAL_ERRORS,
              KFSKeyConstants.ERROR_CUSTOM,
              "Collector detail university fiscal year "
                  + lineNumber
                  + " string "
                  + detailLine.substring(
                      pMap.get(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR),
                      pMap.get(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE)));
          setUniversityFiscalYear(null);
        }
      } else {
        setUniversityFiscalYear(null);
      }

      if (!GeneralLedgerConstants.getSpaceChartOfAccountsCode()
          .equals(
              detailLine.substring(
                  pMap.get(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR),
                  pMap.get(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE))))
        setChartOfAccountsCode(
            getValue(
                detailLine,
                pMap.get(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE),
                pMap.get(KFSPropertyConstants.ACCOUNT_NUMBER)));
      else setChartOfAccountsCode(GeneralLedgerConstants.getSpaceChartOfAccountsCode());
      setAccountNumber(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.ACCOUNT_NUMBER),
              pMap.get(KFSPropertyConstants.SUB_ACCOUNT_NUMBER)));

      // if chart code is empty while accounts cannot cross charts, then derive chart code from
      // account number
      AccountService acctserv = SpringContext.getBean(AccountService.class);
      if (StringUtils.isEmpty(getChartOfAccountsCode())
          && StringUtils.isNotEmpty(getAccountNumber())
          && !acctserv.accountsCanCrossCharts()) {
        Account account = acctserv.getUniqueAccountForAccountNumber(getAccountNumber());
        if (account != null) {
          setChartOfAccountsCode(account.getChartOfAccountsCode());
        }
      }

      setSubAccountNumber(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.SUB_ACCOUNT_NUMBER),
              pMap.get(KFSPropertyConstants.FINANCIAL_OBJECT_CODE)));
      setFinancialObjectCode(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.FINANCIAL_OBJECT_CODE),
              pMap.get(KFSPropertyConstants.FINANCIAL_SUB_OBJECT_CODE)));
      setFinancialSubObjectCode(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.FINANCIAL_SUB_OBJECT_CODE),
              pMap.get(KFSPropertyConstants.FINANCIAL_BALANCE_TYPE_CODE)));

      // We are in Collector Detail for ID Billing Details because the value from file positions 26,
      // 27 = DT.  We don not want to set Financial Balance Type Code to detail type code (DT)
      // Generate the account record key to retrieve the balance type from the map which contains
      // the balance type from the accounting record/origin entry
      String accountRecordKey = generateAccountRecordBalanceTypeKey();
      String financialBalanceTypeCode = accountRecordBalanceTypeMap.get(accountRecordKey);
      // Default to "AC" if we do not find account record key record from the map
      setFinancialBalanceTypeCode(
          StringUtils.defaultIfEmpty(
              financialBalanceTypeCode,
              GeneralLedgerConstants.FINALNCIAL_BALANCE_TYPE_FOR_COLLECTOR_DETAIL_RECORD));
      setFinancialObjectTypeCode(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.FINANCIAL_OBJECT_TYPE_CODE),
              pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_SEQUENCE_NUMBER)));
      setUniversityFiscalPeriodCode(universityDate.getUniversityFiscalAccountingPeriod());
      setCollectorDetailSequenceNumber(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_SEQUENCE_NUMBER),
              pMap.get(KFSPropertyConstants.FINANCIAL_DOCUMENT_TYPE_CODE)));
      setFinancialDocumentTypeCode(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.FINANCIAL_DOCUMENT_TYPE_CODE),
              pMap.get(KFSPropertyConstants.FINANCIAL_SYSTEM_ORIGINATION_CODE)));
      setFinancialSystemOriginationCode(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.FINANCIAL_SYSTEM_ORIGINATION_CODE),
              pMap.get(KFSPropertyConstants.DOCUMENT_NUMBER)));
      setDocumentNumber(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.DOCUMENT_NUMBER),
              pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_AMOUNT)));
      try {
        setCollectorDetailItemAmount(
            getValue(
                detailLine,
                pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_AMOUNT),
                pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_GL_CREDIT_CODE)));
      } catch (NumberFormatException e) {
        setCollectorDetailItemAmount(KualiDecimal.ZERO);
        messageMap.putError(
            KFSConstants.GLOBAL_ERRORS,
            KFSKeyConstants.ERROR_CUSTOM,
            "Collector detail amount cannot be parsed on line "
                + lineNumber
                + " amount string "
                + detailLine.substring(
                    pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_AMOUNT),
                    pMap.get(KFSPropertyConstants.GL_CREDIT_CODE)));
      }
      if (KFSConstants.GL_CREDIT_CODE.equalsIgnoreCase(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_GL_CREDIT_CODE),
              pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_NOTE_TEXT)))) {
        setCollectorDetailItemAmount(getCollectorDetailItemAmount().negated());
      }
      setCollectorDetailNoteText(
          getValue(
              detailLine,
              pMap.get(KFSPropertyConstants.COLLECTOR_DETAIL_NOTE_TEXT),
              GeneralLedgerConstants.getSpaceAllCollectorDetailFields().length()));

      if (org.apache.commons.lang.StringUtils.isEmpty(getSubAccountNumber())) {
        setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
      }
      if (org.apache.commons.lang.StringUtils.isEmpty(getFinancialSubObjectCode())) {
        setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
      }
      if (org.apache.commons.lang.StringUtils.isEmpty(getCollectorDetailSequenceNumber())) {
        setCollectorDetailSequenceNumber(" ");
      }
    } catch (Exception e) {
      throw new RuntimeException(
          e + " occurred in CollectorDetail.setFromFileForCollectorDetail()");
    }
  }
コード例 #23
0
  public VelocityContext getBiospecimenLabelContext(Biospecimen biospecimen) {
    /* lets make a Context and put data into it */
    VelocityContext velocityContext = new VelocityContext();

    String biospecimenUid = biospecimen.getBiospecimenUid();

    String dateOfBirth = "";
    if (biospecimen.getLinkSubjectStudy().getPerson().getDateOfBirth() != null) {
      dateOfBirth =
          simpleDateFormat.format(biospecimen.getLinkSubjectStudy().getPerson().getDateOfBirth());
    }

    // // Ok first check and see if last character is a number.
    // String lastLineOfCircle = "";
    // String secondLineOfCircle = "";
    // String lastChar = biospecimenUid.substring(biospecimenUid.length() - 1);
    // // Need to find out where the study code ends
    // // Trim off the year component
    // String withoutYear = biospecimenUid.substring(2);
    // Pattern pat = Pattern.compile("\\d");
    // Matcher matcher = pat.matcher(withoutYear);
    // boolean gotMatch = matcher.find();
    // int indexOfnum = -1;
    // if (gotMatch) {
    // indexOfnum = matcher.start() + 2;
    // }
    // // if (lastChar.matches(REAL_NUMBER)) {
    // // // We have a clone, therefore go one backwards.
    // // lastLineOfCircle = biospecimenUid.substring(biospecimenUid.length() - 2);
    // // secondLineOfCircle = biospecimenUid.substring(indexOfnum, biospecimenUid.length() - 2);
    // // }
    // // else {
    // lastLineOfCircle = lastChar;
    // secondLineOfCircle = biospecimenUid.substring(indexOfnum, biospecimenUid.length() - 1);
    // // }
    // String secondLine = secondLineOfCircle;
    //
    // try {
    // secondLine = new Integer(secondLineOfCircle).toString();
    // }
    // catch (NumberFormatException e) {
    // log.error(e.getMessage());
    // }
    //
    log.info("velocity context should have specimen=" + biospecimenUid + " and dob=" + dateOfBirth);
    velocityContext.put("biospecimenUid", biospecimenUid);
    // velocityContext.put("firstLineOfCircle", biospecimenUid.substring(0, indexOfnum));
    // velocityContext.put("secondLineOfCircle", secondLine);
    // velocityContext.put("lastLineOfCircle", lastLineOfCircle);

    // Pad out to at least 15 characters
    biospecimenUid = org.apache.commons.lang.StringUtils.rightPad(biospecimenUid, 15);

    // Split biospecimenUid into 3 equal strings
    velocityContext.put("firstLineOfCircle", biospecimenUid.substring(0, 5).trim());
    velocityContext.put("secondLineOfCircle", biospecimenUid.substring(5, 11));
    velocityContext.put("lastLineOfCircle", biospecimenUid.substring(11, biospecimenUid.length()));

    // Sample type
    velocityContext.put("sampleType", biospecimen.getSampleType().getName());
    velocityContext.put("subjectUid", biospecimen.getLinkSubjectStudy().getSubjectUID());

    if (dateOfBirth != null) {
      velocityContext.put("dateOfBirth", dateOfBirth);
    } else {
      velocityContext.put("dateOfBirth", "noDOB");
    }
    return velocityContext;
  }
コード例 #24
0
ファイル: CreateEntireFile.java プロジェクト: racerm3/DMV
  private String createRecord(ResultSet rs, String type) throws Exception {
    try {
      // String dlNumber = rs.getString("IREC_DOC_NBR");
      String dlNumber = rs.getString(1);
      dlNumber = dlNumber.trim();
      if (dlNumber.length() < 8) {
        dlNumber = StringUtils.leftPad(dlNumber, 8, ZERO);
      }
      dlNumber = StringUtils.leftPad(dlNumber, 10, ZERO);

      // String lastName = rs.getString("DPSP_LAST_NME");
      String lastName = rs.getString(2);
      lastName = lastName.trim();
      lastName = StringUtils.rightPad(lastName, 40, SPACE);

      // String firstName = rs.getString("DPSP_FIRST_NME");
      String firstName = rs.getString(3);
      if (firstName == null) {
        firstName = StringUtils.rightPad("", 40, SPACE);
      } else {
        firstName = firstName.trim();
        firstName = StringUtils.rightPad(firstName, 40, SPACE);
      }

      // String middleName = rs.getString("DPSP_MIDDLE_NME");
      String middleName = rs.getString(4);
      if (middleName == null) {
        middleName = StringUtils.rightPad("", 40, SPACE);
      } else {
        middleName = middleName.trim();
        middleName = StringUtils.rightPad(middleName, 40, SPACE);
      }

      // String suffix = rs.getString("DPSP_SUFFIX");
      String suffix = rs.getString(5);
      if (suffix == null) {
        suffix = "";
      } else {
        suffix = suffix.trim();
      }
      suffix = translateSuffixCode(suffix);

      String dob = "";
      // Object obj = rs.getObject("DPSP_DOB");
      Object obj = rs.getObject(6);
      if (obj == null) {
        dob = StringUtils.rightPad("", 8, SPACE);
      } else {
        dob = ((java.sql.Date) obj).toString();
        // dob = StringUtils.rightPad(dob, 10, SPACE);
        dob = parseDOB(dob);
      }

      // String address1 = rs.getString("DMDT_STRT_ADDR_1");
      String address1 = rs.getString(7);
      if (address1 == null) {
        address1 = StringUtils.rightPad("", 32, SPACE);
      } else {
        address1 = address1.trim();
        address1 = StringUtils.rightPad(address1, 32, SPACE);
      }

      // String address2 = rs.getString("DMDT_STRT_ADDR_2");
      String address2 = rs.getString(8);
      if (address2 == null) {
        address2 = StringUtils.rightPad("", 32, SPACE);
      } else {
        address2 = address2.trim();
        address2 = StringUtils.rightPad(address2, 32, SPACE);
      }

      // String city = rs.getString("DMDT_CITY");
      String city = rs.getString(9);
      if (city == null) {
        city = StringUtils.rightPad("", 33, SPACE);
      } else {
        city = city.trim();
        city = StringUtils.rightPad(city, 33, SPACE);
      }

      // String state = rs.getString("DMDT_STATE");
      String state = rs.getString(10);
      if (state == null) {
        state = StringUtils.rightPad("", 2, SPACE);
      } else {
        state = state.trim();
        state = StringUtils.rightPad(state, 2, SPACE);
      }

      // String zipcode = rs.getString("ZIPCODE");
      String zipcode = rs.getString(11);
      if (zipcode == null) {
        zipcode = StringUtils.rightPad("", 5, SPACE);
      } else {
        zipcode = zipcode.trim();
        zipcode = StringUtils.rightPad(zipcode, 5, SPACE);
      }

      // String zipcodeext = rs.getString("ZIPCODEEXT");
      String zipcodeext = rs.getString(12);
      if (zipcodeext == null) {
        zipcodeext = StringUtils.rightPad("", 4, SPACE);
      } else {
        zipcodeext = zipcodeext.trim();
        zipcodeext = StringUtils.rightPad(zipcodeext, 4, SPACE);
      }

      // String originalIssueDate = rs.getString("OIDTE");
      String originalIssueDate = rs.getString(13);
      if (originalIssueDate == null) {
        originalIssueDate = StringUtils.rightPad("", 10, SPACE);
      } else {
        originalIssueDate = originalIssueDate.trim();
        // originalIssueDate = StringUtils.rightPad(originalIssueDate,
        // 10, SPACE);
        originalIssueDate = parseDOB(originalIssueDate);
      }

      // String cardType = rs.getString("IREC_ISSUANCE_TYP");
      String cardType = rs.getString(14);
      if (cardType == null) {
        cardType = StringUtils.rightPad("", 2, SPACE);
      } else {
        cardType = type;
      }

      String recordStr =
          dlNumber
              + lastName
              + firstName
              + middleName
              + suffix
              + dob
              + address1
              + address2
              + city
              + state
              + zipcode
              + zipcodeext
              + originalIssueDate
              + cardType;

      return recordStr;
    } // end of try
    catch (Exception e) {
      System.out.println("createRecord()" + e);
      logger.error("Exception during createRecord()", e);
      rc = false;

      throw new RuntimeException(e.getMessage());
    }
  }
コード例 #25
0
 /**
  * Gera e retorna uma string aleatória composta por 16 caracteres. A string gerada é na verdade um
  * número hexadecimal com 32 posições.
  *
  * @return a string aleatória gerada.
  */
 public static synchronized String generate() {
   final String value1 = Long.toHexString(Math.abs(SECURE_RANDOM.nextLong()));
   final String value2 = Long.toHexString(Math.abs(SECURE_RANDOM.nextLong()));
   return StringUtils.rightPad(value1.concat(value2).toUpperCase(), 32, '0');
 }
コード例 #26
0
  public void run() throws IOException {
    IClearCaseAdapter cc = ClearCaseAdapterFactory.create();
    cc.setViewPath(new File(getViewPath()));

    // Find changed files between now and 'history days' back.
    List changedFiles =
        cc.findChangedFiles(
            DateOnlyUtil.addDays(new Date(), -getHistoryDays()),
            new Date(),
            new SuffixFileFilter("*"));

    // Build up the list of audits to run...
    List audits = new ArrayList();
    audits.add(new MissingCommentAudit());
    audits.add(new ContainsTabsAudit());
    List finalResults = new ArrayList();

    // Run the audits
    for (Iterator iter = audits.iterator(); iter.hasNext(); ) {
      IAudit audit = (IAudit) iter.next();
      finalResults.addAll(audit.audit(changedFiles));
    }

    // Sort the audit results
    Comparator sortByUser = new ObjectComparator("username", "filename");
    Collections.sort(finalResults, sortByUser);

    // Find the max length of the data in the results so the output looks
    // nice and lined up
    int maxUsername = getMaxLength(finalResults, "username");
    int maxFilename = getMaxLength(finalResults, "fileOnly");
    int maxReason = getMaxLength(finalResults, "reason");
    int maxDate = getMaxLength(finalResults, "date");

    // Create header row
    StringBuffer sb = new StringBuffer();
    sb.append(StringUtils.repeat("=", 80));
    sb.append("\n");
    sb.append(StringUtils.rightPad("User", maxUsername));
    sb.append(StringUtils.rightPad("File", maxFilename));
    sb.append(StringUtils.rightPad("Reason", maxReason));
    sb.append(StringUtils.rightPad("Timestamp", maxDate));
    sb.append("Dir\n");
    sb.append(StringUtils.repeat("=", 80));
    sb.append("\n");

    // Format the audit results
    for (ListIterator iter = finalResults.listIterator(); iter.hasNext(); ) {
      IAuditResult result = (IAuditResult) iter.next();

      sb.append(StringUtils.rightPad(getAlias(result.getUsername()), maxUsername));

      sb.append(StringUtils.rightPad(result.getFileOnly(), maxFilename));
      sb.append(StringUtils.rightPad(result.getReason(), maxReason));
      sb.append(StringUtils.rightPad(result.getDate(), maxDate));
      sb.append(FilenameUtils.getFullPathNoEndSeparator(result.getFilename()));
      sb.append("\n");
    }

    System.out.println(sb);
  }