Example #1
1
  /**
   * @param querymap 封装sql的where语句 key value 相当于 where key=value
   * @param _sql 查出列表的sql
   * @param _csql 查出列表总数的sql
   * @param args 参数列表(不包括wheremap里的)
   * @return
   */
  private Object[] initPreSql(
      Map<String, Object> querymap, String _sql, String _csql, Object... args) {
    Object[] parms = null;
    psql.delete(0, psql.length());
    psql.append(_sql);
    csql.delete(0, csql.length());
    csql.append(_csql);
    int i = 0;
    if (MyUtil.isEmpty(args) && MyUtil.isEmpty(querymap)) return null;
    if (!MyUtil.isEmpty(args) && MyUtil.isEmpty(querymap)) return args;

    if (MyUtil.isEmpty(args)) {
      parms = new Object[querymap.size()];
    } else {
      parms = new Object[querymap.size() + args.length];
      for (Object arg : args) {
        parms[i++] = arg;
      }
    }
    for (String key : querymap.keySet()) {
      psql.append(" and ");
      psql.append(key);
      psql.append(" like ? ");

      csql.append(" and ");
      csql.append(key);
      csql.append(" like ? ");

      parms[i++] = "%" + String.valueOf(querymap.get(key)) + "%";
    }
    return parms;
  }
Example #2
1
  @SuppressLint("NewApi")
  @Override
  public void run() {
    ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    MemoryInfo mi = new MemoryInfo();
    am.getMemoryInfo(mi);
    StringBuilder buf = new StringBuilder();
    buf.append("mi.availMem=").append(mi.availMem / MB).append(", ");
    buf.append("mi.threshold=").append(mi.threshold / MB).append(", ");
    buf.append("mi.totalMem=").append(mi.totalMem / MB).append(", ");
    buf.append("mi.lowMemory=").append(mi.lowMemory);
    Log.d(TAG, "MemoryInfo=" + buf.toString());

    buf.delete(0, buf.length());
    buf.append("TotalMemory=" + TotalMemory()).append(", ");
    buf.append("FreeMemory=" + FreeMemory()).append(", ");
    buf.append("BusyMemory=" + BusyMemory());
    Log.d(TAG, "RootDirectory= " + buf.toString());

    buf.delete(0, buf.length());
    buf.append("TotalMemory=" + DeviceMemory.getInternalStorageSpace()).append(", ");
    buf.append("FreeMemory=" + DeviceMemory.getInternalFreeSpace()).append(", ");
    buf.append("BusyMemory=" + DeviceMemory.getInternalUsedSpace());
    Log.d(TAG, "DeviceMemory= " + buf.toString());
  }
 /**
  * Create result values from observation according to ResultEncoding and ResultStructure
  *
  * @param observations Observation to create result values from
  * @param sosResultEncoding The ResultEncoding
  * @param sosResultStructure The ResultStructure
  * @return Result values String from observation according to ResultEncoding and ResultStructure
  * @throws OwsExceptionReport If creation fails
  */
 public static String createResultValuesFromObservations(
     final List<AbstractObservation> observations,
     final SosResultEncoding sosResultEncoding,
     final SosResultStructure sosResultStructure)
     throws OwsExceptionReport {
   final StringBuilder builder = new StringBuilder();
   if (CollectionHelper.isNotEmpty(observations)) {
     final String tokenSeparator = getTokenSeparator(sosResultEncoding.getEncoding());
     final String blockSeparator = getBlockSeparator(sosResultEncoding.getEncoding());
     final Map<Integer, String> valueOrder =
         getValueOrderMap(sosResultStructure.getResultStructure());
     addElementCount(builder, observations.size(), blockSeparator);
     for (final AbstractObservation observation : observations) {
       for (final Integer intger : valueOrder.keySet()) {
         final String definition = valueOrder.get(intger);
         if (definition.equals(PHENOMENON_TIME)) {
           builder.append(
               getTimeStringForPhenomenonTime(
                   observation.getPhenomenonTimeStart(), observation.getPhenomenonTimeEnd()));
         } else if (definition.equals(RESULT_TIME)) {
           builder.append(getTimeStringForResultTime(observation.getResultTime()));
         } else {
           builder.append(getValueAsStringForObservedProperty(observation, definition));
         }
         builder.append(tokenSeparator);
       }
       builder.delete(builder.lastIndexOf(tokenSeparator), builder.length());
       builder.append(blockSeparator);
     }
     if (builder.length() > 0) {
       builder.delete(builder.lastIndexOf(blockSeparator), builder.length());
     }
   }
   return builder.toString();
 }
 /**
  * Method to create/get ignoring players file
  *
  * @param filename
  */
 public void initIgnoreLog(String filename) {
   StringBuilder sb = new StringBuilder();
   File existing = new File(filename);
   CivChat2.debugmessage("Initializing IgnoreLog...");
   try {
     if (existing.exists()) {
       // ignore file exists load it
       CivChat2.infoMessage(
           sb.append("Existing Ignore file: ").append(existing.getAbsolutePath()).toString());
       sb.delete(0, sb.length());
       FileWriter fw = new FileWriter(existing, true);
       writer = new BufferedWriter(fw);
       ignoredPlayers = existing;
       chatMan.loadIgnoredPlayers(ignoredPlayers);
     } else {
       // create new ignore file
       CivChat2.infoMessage(
           sb.append("Creating new Ignore file: ").append(existing.getAbsolutePath()).toString());
       sb.delete(0, sb.length());
       existing.createNewFile();
       PrintWriter pw = new PrintWriter(existing);
       writer = new BufferedWriter(pw);
       ignoredPlayers = existing;
       addIgnoreHeader();
     }
   } catch (IOException ex) {
     CivChat2.warningMessage("File Failed: " + ex);
   }
 }
  /**
   * Method to create/get chat log text file
   *
   * @return true if file was created successfully, false if failed
   */
  public void initchatLog(String filename) {
    StringBuilder sb = new StringBuilder();
    File existing = new File(filename);
    CivChat2.debugmessage(
        sb.append("Initializing chatlog... filename=[")
            .append(filename.toString())
            .append("]")
            .toString());
    sb.delete(0, sb.length());
    // first create chatlog file
    try {
      if (existing.exists()) {
        // directory already exists
        CivChat2.infoMessage(
            sb.append("Existing Chat File: ").append(existing.getAbsolutePath()).toString());
        sb.delete(0, sb.length());
        FileWriter fw = new FileWriter(existing.getAbsolutePath(), true);
        fileWriter = new BufferedWriter(fw);
      } else {
        CivChat2.infoMessage(
            sb.append("Creating new File").append(existing.getAbsolutePath()).toString());
        sb.delete(0, sb.length());
        existing.createNewFile();
        PrintWriter fStream = new PrintWriter(existing);
        fileWriter = new BufferedWriter(fStream);
        addHeader();
      }

    } catch (IOException ex) {
      CivChat2.warningMessage("File Failed" + ex);
    }
  }
Example #6
1
  public static String formatBranches(
      LogInformation.Revision revision, boolean useNumbersIfNamesNotAvailable) {
    String branches = revision.getBranches();
    if (branches == null) return ""; // NOI18N

    boolean branchNamesAvailable = true;
    StringBuilder branchNames = new StringBuilder();
    StringTokenizer st = new StringTokenizer(branches, ";"); // NOI18N
    while (st.hasMoreTokens()) {
      String branchNumber = st.nextToken().trim();
      List<LogInformation.SymName> names =
          revision
              .getLogInfoHeader()
              .getSymNamesForRevision(createBranchRevisionNumber(branchNumber));
      if (names.size() > 0) {
        branchNames.append(names.get(0).getName());
      } else {
        branchNamesAvailable = false;
        if (useNumbersIfNamesNotAvailable) {
          branchNames.append(branchNumber);
        } else {
          break;
        }
      }
      branchNames.append("; "); // NOI18N
    }
    if (branchNamesAvailable || useNumbersIfNamesNotAvailable) {
      branchNames.delete(branchNames.length() - 2, branchNames.length());
    } else {
      branchNames.delete(0, branchNames.length());
    }
    return branchNames.toString();
  }
 public static URL container(String resource, ClassLoader cl) {
   final URL resUrl = cl.getResource(resource);
   if (resUrl == null) {
     throw new IllegalArgumentException("Resource not found: " + resource);
   }
   final StringBuilder url = new StringBuilder(resUrl.toExternalForm());
   try {
     if ("jar".equalsIgnoreCase(resUrl.getProtocol())) {
       url.delete(0, 4).delete(url.indexOf(resource) - 2, url.length());
     } else if ("file".equalsIgnoreCase(resUrl.getProtocol())) {
       url.delete(url.indexOf(resource), url.length());
     } else {
       throw new UnsupportedOperationException(
           "Cannot get container for resource ["
               + resource
               + "]. Unsupported URL protocol ["
               + resUrl.getProtocol()
               + "].");
     }
     return new URL(url.toString());
   } catch (MalformedURLException e) {
     throw new UnsupportedOperationException(
         "Cannot get container for resource [" + resource + "]. Malformed URL [" + url + "].");
   }
 }
  @RequestMapping(value = "/order/search/integral")
  public void searchUserIntegralByOrder(String orderNoes, HttpServletResponse response)
      throws IOException {
    String[] orderNoArray = orderNoes.split("\\n");

    Map<Integer, UserIntegralAndCoupon> uicMap =
        new LinkedHashMap<Integer, UserIntegralAndCoupon>();
    StringBuilder sbd = new StringBuilder();
    for (String orderNo : orderNoArray) {
      if (StringUtils.isBlank(orderNo) || NumberUtils.toLong(orderNo) <= 0) continue;

      long no = NumberUtils.toLong(orderNo.trim());
      Order order = tradeCenterBossClient.queryOrderByOrderNo(no);
      if (order == null) continue;

      User user = userService.getUserById(order.getUserId());
      if (user == null || uicMap.get(user.getId()) != null) continue;

      UserIntegralAndCoupon uic = new UserIntegralAndCoupon();
      uic.setUserId(user.getId());
      uic.setUserName(user.getUserName());
      uic.setPhone(StringUtils.isNotBlank(user.getPhone()) ? user.getPhone() : "");
      uic.setEmail(StringUtils.isNotBlank(user.getEmail()) ? user.getEmail() : "");
      uic.setIntegral(user.getCurrency());

      List<Coupon> coupons = couponService.queryCouponByUserId(order.getUserId());
      sbd.delete(0, sbd.length());
      int i = 0;
      String str = "";
      for (Coupon coupon : coupons) {
        sbd.append(coupon.getCode());
        if (coupon.isUsed()) str = "已使用";
        else if (coupon.isExpire()) str = "已过期";
        if (StringUtils.isNotBlank(str)) sbd.append("(").append(str).append(")");

        if (i != coupons.size() - 1) sbd.append(", ");

        i++;
      }
      uic.setCoupon(sbd.toString());

      sbd.delete(0, sbd.length());
      // 从地址中去寻找
      List<Address> addresses = addressService.queryAllAddress(order.getUserId());
      i = 0;
      for (Address address : addresses) {
        sbd.append(address.getName()).append("/").append(address.getMobile()).append("/");
        sbd.append(address.getProvince()).append(address.getLocation());
        if (address.isDefaultAddress()) sbd.append("<span style='color:red;'>(默认地址)</span>");

        if (i != addresses.size() - 1) sbd.append("\n");
      }
      uic.setAddress(sbd.toString());

      uicMap.put(user.getId(), uic);
    }
    new JsonResult(true).addData("orderList", uicMap.values()).toJson(response);
  }
Example #9
1
  // Communications
  public void updateStatus(InputStream in) throws IOException {
    DataInputStream din = new DataInputStream(in);
    if (builder.length() != 0) {
      builder.delete(0, builder.length());
    }

    eventTotal.setText(form.format(new Long(din.readLong())));
    dataTotal.setText(Util.convertBytes(builder, din.readLong(), true).toString());
    builder.delete(0, builder.length());
    dataRate.setText(Util.convertBytesRate(builder, din.readDouble(), true).toString());
    eventRate.setText(form.format(new Integer((int) din.readDouble())) + "e/s");
  }
Example #10
1
 public void searchTags() {
   StringBuilder strTags = new StringBuilder();
   for (int i = 0; i < tempStrBuilder.length() - 1; i++) {
     i = tempStrBuilder.indexOf("<");
     if (i == -1) {
       break;
     }
     strTags.append(tempStrBuilder.substring(i, tempStrBuilder.indexOf(">") + 1));
     tempStrBuilder.delete(i, tempStrBuilder.indexOf(">") + 1);
     tags.add(strTags.toString());
     strTags.delete(0, strTags.length());
   }
 }
  @Override
  public synchronized void run() {
    while (!quit) {
      //			filter_input();
      try {
        Thread.sleep(1); // poll at 1kHz
        // grab data from shared buffer and move it the local one
        ourBuffer.append(sharedBuffer.take());
        // System.out.print(ourBuffer);
        // create a matcher to find an open tag in the buffer
        int endCloseTag;
        int startOpenTag;
        Matcher closeTagMatcher = closeTagPattern.matcher(ourBuffer);

        // look or a closing tag in our buffer
        if (closeTagMatcher.find()) {
          endCloseTag = closeTagMatcher.end();
          openTag = "<" + ourBuffer.charAt(closeTagMatcher.start() + 2) + ">";
          // find corresponding opening tag
          startOpenTag = ourBuffer.indexOf(openTag);
          // send the input string to the GUI for processing
          if (startOpenTag >= 0 && startOpenTag < endCloseTag) {
            gui.incoming(ourBuffer.substring(startOpenTag, endCloseTag));
            // clear our buffer
            ourBuffer.delete(startOpenTag, endCloseTag);
          } else {
            ourBuffer.delete(0, endCloseTag);
          }
        }
      } catch (Exception e) {
        System.out.print(e + "\n");
      }
    }
  }
  private void passivate(BufferedWriter writer, HashMap<String, List<String>> idx)
      throws IOException {
    StringBuilder bldr = new StringBuilder();
    int ctr = 0;
    List<String> value;
    TreeMap<String, List<String>> map = new TreeMap<String, List<String>>(idx);
    for (Entry<String, List<String>> etr : map.entrySet()) {
      value = etr.getValue();
      bldr.append(etr.getKey()).append("/").append(value.size()).append(":");
      bldr.append(asString(value));
      bldr.append("#");
      ctr++;

      if (ctr % 1000 == 0) {
        writer.write(bldr.toString());
        writer.newLine();
        bldr.delete(0, bldr.length());
        writer.flush();
      }
    }

    writer.write(bldr.toString());
    bldr.delete(0, bldr.length());
    writer.newLine();
    writer.flush();
    writer.close();
    idx.clear();
    idx = null;
    map.clear();
    map = null;
  }
 public String Reduce(String w) {
   int done = 0;
   StringBuilder sb = new StringBuilder(w);
   // System.out.println("Checking "+w);
   while (done == 0) {
     done = 1;
     int i = 0;
     while (i < sb.length()) {
       //	System.out.println("*"+sb.length());
       //	System.out.println(i);
       if (sb.charAt(i) == this.barL.get(sb.charAt((i + 1) % (sb.length())))) {
         if (i == 0) {
           sb.delete(0, 2);
           done = 0;
           i = 0;
         } else if (i < sb.length() - 1) {
           sb.delete(i, i + 2);
           done = 0;
           i = 0;
         } else if (i == sb.length() - 1) {
           sb.deleteCharAt(i);
           sb.deleteCharAt(0);
           done = 0;
           i = 0;
         }
       } else i++;
     }
   }
   return sb.toString();
 }
 public static String stripOpts(String orig, OptimizedPattern op[]) {
   String origLC = orig.toLowerCase();
   StringBuilder sb = null;
   int i = 0;
   int max = op.length;
   while (i < max) {
     if (origLC.indexOf(op[i].match) != -1) {
       sb = new StringBuilder(orig);
       break;
     }
     i++;
   }
   if (sb == null) {
     return orig;
   }
   while (i < max) {
     if (origLC.indexOf(op[i].match) != -1) {
       Matcher m = op[i].pattern.matcher(sb);
       if (m != null && m.matches()) {
         //        			dumpMatcher(m);
         if (op[i].start == op[i].end) {
           sb.delete(m.start(op[i].start), m.end(op[i].end));
         } else {
           if (m.group(op[i].end) == null) {
             sb.setLength(m.end(op[i].start));
           } else {
             sb = sb.delete(m.end(op[i].start), m.start(op[i].end));
           }
         }
       }
     }
     i++;
   }
   return sb.toString();
 }
Example #15
0
  public static boolean retrieveData(
      String fileName, Map<String, String> arry, String delimiter, int keyIndex, int valueIndex)
      throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String line = null;
    String delmilit = "\t\" \"\n";
    if (delimiter != null) {
      delmilit =
          delimiter; // usually some files donot start with data but with breif annoation, so we
                     // need filter the latter.
    }

    String[] row = null;
    StringBuilder tmpStr1 = new StringBuilder();
    StringBuilder tmpStr2 = new StringBuilder();
    while ((line = br.readLine()) != null) {
      line = line.trim();
      if (line.length() == 0) {
        continue;
      }
      row = line.split(delmilit);
      tmpStr1.append(row[keyIndex]);
      tmpStr2.append(row[valueIndex]);
      arry.put(tmpStr1.toString(), tmpStr1.toString());
      tmpStr1.delete(0, tmpStr1.length());
      tmpStr2.delete(0, tmpStr2.length());
    }
    br.close();
    return true;
  }
Example #16
0
  private static void addValidOperandsToList(List<String> operands, String opString) {
    if (opString != null) {
      StringBuilder opBuilder = new StringBuilder();

      // can't tokenise on comma because
      // address operand such as 0x0(%rax,%rax,1)
      // is a single parameter
      boolean inParentheses = false;

      for (int pos = 0; pos < opString.length(); pos++) {
        char c = opString.charAt(pos);

        if (c == C_OPEN_PARENTHESES) {
          inParentheses = true;
          opBuilder.append(c);
        } else if (c == C_CLOSE_PARENTHESES) {
          inParentheses = false;
          opBuilder.append(c);
        } else if (c == C_COMMA && !inParentheses) {
          String operand = opBuilder.toString();
          opBuilder.delete(0, opBuilder.length());
          operands.add(operand);
        } else {
          opBuilder.append(c);
        }
      }

      if (opBuilder.length() > 0) {
        String operand = opBuilder.toString();
        opBuilder.delete(0, opBuilder.length() - 1);
        operands.add(operand);
      }
    }
  }
    private List<String> _getIconNames(String baseSelector) {
      LinkedList<String> names = new LinkedList<String>();

      StringBuilder builder = new StringBuilder(64);
      builder.append(baseSelector);

      int suffixLength = SkinSelectors.ICON_SUFFIX.length();
      int baseIndex = builder.length();

      builder.append(SkinSelectors.ICON_SUFFIX);
      names.addFirst(builder.toString());
      builder.delete(baseIndex, baseIndex + suffixLength);

      if (isActive() || isSelected()) {
        builder.append(_SUFFIX_ACTIVE);
      } else if (isVisited()) {
        builder.append(_SUFFIX_VISITED);
      } else {
        builder.append(_SUFFIX_UNVISITED);
      }

      baseIndex = builder.length();

      builder.append(SkinSelectors.ICON_SUFFIX);
      names.addFirst(builder.toString());

      builder.delete(baseIndex, baseIndex + suffixLength);

      if (isDisabled()) {
        builder.append(_SUFFIX_READ_ONLY);
        builder.append(SkinSelectors.ICON_SUFFIX);
        names.addFirst(builder.toString());
      }
      return names;
    }
Example #18
0
 /**
  * This function returns the dynamic replacement of the protocol from the Success or Failure urls
  *
  * @param rawURL Raw url with out real protocol
  * @param servletRequest Servlet request has real protocol value
  * @return the dynamic replacement of the protocol from the Success or Failure urls
  */
 private String processDynamicVariables(String rawURL, HttpServletRequest servletRequest) {
   if (rawURL.indexOf("%") != -1) {
     int index;
     StringBuilder sb = new StringBuilder(200);
     // protocol processing
     if ((index = rawURL.indexOf("%protocol")) != -1) {
       sb.append(rawURL.substring(0, index));
       if (isConsoleRemote) {
         sb.append(consoleProto);
       } else {
         String protocol = null;
         if (servletRequest != null) {
           protocol =
               RequestUtils.getRedirectProtocol(
                   servletRequest.getScheme(), servletRequest.getServerName());
         }
         if (protocol != null) {
           sb.append(protocol);
         } else {
           sb.append(consoleProto);
         }
       }
       sb.append(rawURL.substring(index + "%protocol".length()));
       rawURL = sb.toString();
     }
     if ((index = rawURL.indexOf("%host")) != -1) {
       int hostlen = "%host".length();
       sb.delete(0, 200);
       sb.append(rawURL.substring(0, index));
       if (isConsoleRemote) {
         sb.append(consoleHost);
       } else {
         String host = null;
         if (servletRequest != null) {
           host = servletRequest.getHeader("Host");
         }
         if (host != null) {
           sb.append(host);
           // This is to remove extra ":"
           hostlen = hostlen + 1;
         } else {
           sb.append(consoleHost);
         }
       }
       sb.append(rawURL.substring(index + hostlen));
       rawURL = sb.toString();
     }
     if ((index = rawURL.indexOf("%port")) != -1) {
       sb.delete(0, 200);
       sb.append(rawURL.substring(0, index));
       if (isConsoleRemote) {
         sb.append(consolePort);
       }
       sb.append(rawURL.substring(index + "%port".length()));
       rawURL = sb.toString();
     }
   }
   return rawURL;
 }
Example #19
0
 /**
  * Bietet der hoster eine Möglichkeit mehrere links gleichzeitig zu prüfen, kann das über diese
  * Funktion gemacht werden.
  */
 @Override
 public boolean checkLinks(final DownloadLink[] urls) {
   if (urls == null || urls.length == 0) {
     return false;
   }
   try {
     if (Rapidshare.RS_API_WAIT > System.currentTimeMillis()) {
       for (final DownloadLink u : urls) {
         u.setAvailable(true);
         u.getLinkStatus()
             .setStatusText(
                 JDL.L("plugin.host.rapidshare.status.apiflood", "unchecked (API Flood)"));
       }
       return true;
     }
     logger.finest("OnlineCheck: " + urls.length + " links");
     final StringBuilder idlist = new StringBuilder();
     final StringBuilder namelist = new StringBuilder();
     final ArrayList<DownloadLink> links = new ArrayList<DownloadLink>();
     int size = 0;
     for (final DownloadLink u : urls) {
       if (size > 3000) {
         logger.finest("OnlineCheck: SplitCheck " + links.size() + "/" + urls.length + " links");
         /* do not stop here because we are not finished yet */
         this.checkLinksIntern2(links);
         links.clear();
         idlist.delete(0, idlist.capacity());
         namelist.delete(0, namelist.capacity());
       }
       /* workaround reset */
       u.setProperty("htmlworkaround", null);
       idlist.append(",").append(Rapidshare.getID(u.getDownloadURL()));
       namelist.append(",").append(this.getName(u));
       links.add(u);
       size =
           ("https://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles&files="
                   + idlist.toString().substring(1)
                   + "&filenames="
                   + namelist.toString().substring(1)
                   + "&incmd5=1")
               .length();
     }
     if (links.size() != 0) {
       if (links.size() != urls.length) {
         logger.finest("OnlineCheck: SplitCheck " + links.size() + "/" + urls.length + " links");
       } else {
         logger.finest("OnlineCheck: Check " + urls.length + " links");
       }
       if (!this.checkLinksIntern2(links)) {
         return false;
       }
     }
   } catch (final Exception e) {
     e.printStackTrace();
     return false;
   }
   return true;
 }
Example #20
0
  @RequestMapping("/list")
  public ModelAndView list(
      @RequestParam(value = "lotno") String lotno,
      @RequestParam(value = "batchcode") String batchcode,
      @RequestParam(value = "starttime") String starttime,
      @RequestParam(value = "endtime") String endtime,
      ModelAndView view) {
    logger.info("opentime/list");
    if (StringUtil.isEmpty(lotno) || StringUtil.isEmpty(starttime) || StringUtil.isEmpty(endtime)) {
      view.addObject("errormsg", "时间不允许为空");
      view.setViewName("opentime/list");
      return view;
    }
    StringBuilder builder = new StringBuilder("where");
    List<Object> params = new ArrayList<Object>();
    StringBuilder mysql = new StringBuilder("where");
    builder.append(" o.id.lotno=? and");
    params.add(lotno);
    mysql.append(" o.lotno = ? and");
    if (!StringUtil.isEmpty(batchcode)) {
      builder.append(" o.batchcode =? and");
      params.add(batchcode);
      mysql.append(" o.batchcode = ? and");
    }
    if (!StringUtil.isEmpty(starttime)) {
      builder.append(" to_char(o.agencyopentime, 'yyyy-mm-dd') >= ? and");
      params.add(starttime);
      mysql.append(" o.codedate >= ? and");
    }
    if (!StringUtil.isEmpty(endtime)) {
      builder.append(" to_char(o.agencyopentime, 'yyyy-mm-dd') <= ? and");
      params.add(endtime + " 23:59:59");
      mysql.append(" o.codedate <= ? and");
    }
    if (builder.toString().endsWith("and")) {
      builder.delete(builder.length() - 3, builder.length());
      mysql.delete(mysql.length() - 3, mysql.length());
    }
    if (builder.toString().endsWith("where")) {
      builder.delete(builder.length() - 5, builder.length());
      mysql.delete(mysql.length() - 5, mysql.length());
    }

    try {
      if (!StringUtil.isEmpty(builder.toString())) {
        view.addObject("list", Twininfo.findAllTwininfoes(builder.toString(), params));
        view.addObject(
            "list2", prizecrawlerDao.findAllTagencyprizecode2(mysql.toString(), params.toArray()));
      }

    } catch (Exception e) {
      view.addObject("errormsg", "查询出错");
      logger.error("opentime/list error", e);
    }
    view.setViewName("opentime/list");
    return view;
  }
Example #21
0
  /**
   * Read a header. Return null if the last header was already read.
   *
   * @param is The message input stream.
   * @param sb The string builder to reuse.
   * @return The header read or null.
   * @throws IOException
   */
  public static Parameter readHeader(InputStream is, StringBuilder sb) throws IOException {
    Parameter result = null;

    // Detect the end of headers
    int next = is.read();
    if (HttpUtils.isCarriageReturn(next)) {
      next = is.read();
      if (!HttpUtils.isLineFeed(next)) {
        throw new IOException(
            "Invalid end of headers. Line feed missing after the carriage return.");
      }
    } else {
      result = new Parameter();

      // Parse the header name
      while ((next != -1) && (next != ':')) {
        sb.append((char) next);
        next = is.read();
      }

      if (next == -1) {
        throw new IOException("Unable to parse the header name. End of stream reached too early.");
      } else {
        result.setName(sb.toString());
        sb.delete(0, sb.length());

        next = is.read();
        while (HttpUtils.isSpace(next)) {
          // Skip any separator space between colon and header value
          next = is.read();
        }

        // Parse the header value
        while ((next != -1) && (!HttpUtils.isCarriageReturn(next))) {
          sb.append((char) next);
          next = is.read();
        }

        if (next == -1) {
          throw new IOException(
              "Unable to parse the header value. End of stream reached too early.");
        } else {
          next = is.read();

          if (HttpUtils.isLineFeed(next)) {
            result.setValue(sb.toString());
            sb.delete(0, sb.length());
          } else {
            throw new IOException(
                "Unable to parse the HTTP header value. The carriage return must be followed by a line feed.");
          }
        }
      }
    }

    return result;
  }
  @Test
  public void testDelete_4() {
    final StringBuilder bottomRef = new StringBuilder(baseString);
    bottomRef.delete(7, 12);
    bottomRef.delete(6, 9);

    bottom.delete(7, 12);
    bottom.delete(6, 7);

    assertEquals(bottomRef.toString(), bottom.get());
  }
  @Test
  public void testGetLookupParameters() throws Exception {
    protocolFundingSourceService = new ProtocolFundingSourceServiceImpl();
    StringBuilder builder = new StringBuilder();

    Entry<String, String> entry =
        protocolFundingSourceService.getLookupParameters(FundingSourceType.SPONSOR);
    Assert.assertNotNull(entry);
    builder.append("sponsorCode:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA);
    builder.append("sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME);
    Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString()));
    builder.delete(0, builder.length());

    entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.UNIT);
    Assert.assertNotNull(entry);
    builder.append("unitNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA);
    builder.append("unitName:" + PROTOCOL_FUNDING_SOURCE_NAME);
    Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString()));
    builder.delete(0, builder.length());

    entry =
        protocolFundingSourceService.getLookupParameters(FundingSourceType.PROPOSAL_DEVELOPMENT);
    Assert.assertNotNull(entry);
    builder.append("proposalNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA);
    builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA);
    builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE);
    Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString()));
    builder.delete(0, builder.length());

    entry =
        protocolFundingSourceService.getLookupParameters(FundingSourceType.INSTITUTIONAL_PROPOSAL);
    Assert.assertNotNull(entry);
    builder.append("proposalId:" + PROTOCOL_FUNDING_SOURCE + Constants.COMMA);
    builder.append("proposalNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA);
    builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA);
    builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE);
    Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString()));
    builder.delete(0, builder.length());

    entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.AWARD);
    Assert.assertNotNull(entry);
    builder.append("awardId:" + PROTOCOL_FUNDING_SOURCE + Constants.COMMA);
    builder.append("awardNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA);
    builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA);
    builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE);
    Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString()));

    try {
      entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.OTHER);
      fail("IllegalArgumentException was not thrown for invalid test case using OTHER");
    } catch (IllegalArgumentException e) {
      // yup
    }
  }
Example #24
0
 protected static void fixExtraneous(StringBuilder text, Tag tag) {
   int tagEnd = tag.pos + tag.tag.length();
   if (tag.pos > 0 && tagEnd < text.length() && text.substring(tag.pos, tagEnd).equals(tag.tag)) {
     text.delete(tag.pos, tagEnd);
   } else {
     int i = text.indexOf(tag.tag);
     if (i != -1) {
       text.delete(i, i + tag.tag.length());
     }
   }
 }
Example #25
0
  /**
   * M{etodo que cifra un texto
   *
   * @param clave
   * @param ubicacionArchivo
   * @throws FileNotFoundException
   * @throws IOException
   */
  protected void cifrar(String clave, String ubicacionArchivo)
      throws FileNotFoundException, IOException {
    FileReader fr = new FileReader(ubicacionArchivo);
    BufferedReader br = new BufferedReader(fr);
    String lineaTexto;
    int cont = 0;
    int[][] matrizTextoBits = new int[8][8];
    int[][] matrizClaveBits = new int[clave.length()][8];
    FileWriter fw = new FileWriter("textoCifrado.txt", true);

    matrizClaveBits = claveEnBits(matrizClaveBits, clave);

    while ((lineaTexto = br.readLine()) != null) {
      byte[] lineaEnBytes = lineaTexto.getBytes(StandardCharsets.UTF_8);
      StringBuilder binario = new StringBuilder();
      System.out.println("lineaTexto: " + lineaTexto);
      for (byte letra : lineaEnBytes) {
        System.out.println((char) letra);
        int val = letra;
        for (int i = 0; i < 8; i++) {
          binario.append((val & 128) == 0 ? 0 : 1);
          val <<= 1;
        }

        String[] letraTextoBits = binario.toString().split("");

        letraTextoEnMatriz(letraTextoBits, matrizTextoBits, cont);
        cont++;

        if (cont == 8) {
          System.out.println("cierra bloque.");
          cifrarBloque(matrizTextoBits, matrizClaveBits, fw, cont);
          matrizTextoBits = new int[8][8];
          cont = 0;
        }
        binario.delete(0, binario.length());
      }
      int validar = 0;
      for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
          validar += matrizTextoBits[i][j];
        }
      }
      if (validar != 0) {
        System.out.println("cierra bloque linea.");
        cifrarBloque(matrizTextoBits, matrizClaveBits, fw, cont);
      }
      matrizTextoBits = new int[8][8];
      binario.delete(0, binario.length());
      cont = 0;
      fw.write(System.lineSeparator());
    }
    fw.close();
  }
 public String readAnnotation(ZLFile file) {
   myReadState = READ_NOTHING;
   myBuffer.delete(0, myBuffer.length());
   if (readDocument(file)) {
     final int len = myBuffer.length();
     if (len > 1) {
       if (myBuffer.charAt(len - 1) == '\n') {
         myBuffer.delete(len - 1, len);
       }
       return myBuffer.toString();
     }
   }
   return null;
 }
Example #27
0
  /**
   * Remove leading and trailing whitespace
   *
   * @param input
   */
  private static void trim(final StringBuilder input) {
    int length = input.length();
    int breakLength = BREAK.length();

    while (length > 0) {
      if (input.indexOf(BREAK) == 0) input.delete(0, breakLength);
      else if (length >= breakLength && input.lastIndexOf(BREAK) == length - breakLength)
        input.delete(length - breakLength, length);
      else if (Character.isWhitespace(input.charAt(0))) input.deleteCharAt(0);
      else if (Character.isWhitespace(input.charAt(length - 1))) input.deleteCharAt(length - 1);
      else break;
      length = input.length();
    }
  }
  @Test
  public void testDelete_1() {
    bottom.delete(2, 5);
    top.delete(2, 4);

    final StringBuilder bottomRef = new StringBuilder(baseString);
    bottomRef.delete(2, 5);

    final StringBuilder topRef = new StringBuilder(bottomRef);
    topRef.delete(2, 4);

    assertEquals(bottomRef.toString(), bottom.get());
    assertEquals(topRef.toString(), top.get());
  }
Example #29
0
  public static void main(String[] args) {
    Loopey loop = new Loopey();
    // loop.loopey(3);
    loop.loopeyLabel(4);
    // loop.loopeyWhileLabel(5);

    int x = 4;
    StringBuilder sb = new StringBuilder("..fedcba");
    sb.delete(3, 6);
    sb.insert(3, "az");
    if (sb.length() > 6) x = sb.indexOf("b");
    sb.delete((x - 3), (x - 2));
    System.out.println(sb + " " + x + " " + sb.length());
  }
 public static String removeBlankLines(String s) {
   StringBuilder sb = new StringBuilder(s);
   int len = sb.length();
   while (len > 0) {
     for (int i = 0; i < len; i++) {
       char c = sb.charAt(i);
       if (c == ' ') continue;
       if (c != '\n') return sb.delete(0, i).toString();
       sb.delete(0, i + 1);
       break;
     }
     len = sb.length();
   }
   return sb.toString();
 }