/**
  * Applies the size filter
  *
  * @param sb message to filter
  * @param front true if apply front sizer, false for back sizer
  * @param player whether or not it is for a player
  */
 private void filterSizer(StringBuilder sb, boolean front, boolean player) {
   Pattern regex = front ? EXPAND_FRONT : EXPAND_BACK;
   Matcher match = regex.matcher(sb);
   int size = sb.length();
   while (match.find()) {
     int playerSize = Integer.parseInt(match.group(2));
     int consoleSize = Integer.parseInt(match.group(3));
     String string = match.group(1);
     if (player) {
       sb.replace(
           match.start() + sb.length() - size,
           match.end(),
           (TextSizer.measureString(string) > playerSize - 2
               ? string
               : TextSizer.expand(string, playerSize, front)));
     } else {
       sb.replace(
           match.start() + sb.length() - size,
           match.end(),
           (string.length() > consoleSize
               ? string
               : TextSizer.expandConsole(string, consoleSize, front)));
     }
   }
 }
Example #2
1
 /** {@inheritDoc} */
 @Override
 public String toString() {
   StringBuilder result = new StringBuilder(64);
   result.append("[").append(getId()).append(":");
   if (productionLevel != null) {
     result.append(" ").append(productionLevel);
   }
   if (unattended) {
     result.append(" unattended");
   }
   if (!(inputs == null || inputs.isEmpty())) {
     result.append(" [inputs: ");
     for (AbstractGoods input : inputs) {
       result.append(input).append(", ");
     }
     int length = result.length();
     result.replace(length - 2, length, "]");
   }
   if (!(outputs == null || outputs.isEmpty())) {
     result.append(" [outputs: ");
     for (AbstractGoods output : outputs) {
       result.append(output).append(", ");
     }
     int length = result.length();
     result.replace(length - 2, length, "]");
   }
   result.append("]");
   return result.toString();
 }
Example #3
1
  private String cleanString(String string) {
    string.trim();
    String patt = "'";
    Pattern r = Pattern.compile(patt);

    StringBuilder sb = new StringBuilder(string);
    Matcher m = r.matcher(sb);
    int start = 0;
    String replString = "\\'";
    while (m.find(start)) {

      sb.replace(m.start(), m.end(), "\\'");
      start = m.start() + replString.length();
    }

    patt = "\n";
    r = Pattern.compile(patt);
    m = r.matcher(sb);
    start = 0;
    replString = "\' + char(13) + char(10) + \'";
    while (m.find(start)) {
      sb.replace(m.start(), m.end(), replString);
      start = m.start() + replString.length();
    }
    return sb.toString();
  }
  /** Reads in a tensor */
  public Tensor3D readTensor(String prefix) {
    // prepare a buffer that will contain the configuration value for this
    // tensor component. this code is called a lot of times; to avoid over-
    // loading the garbage collector, we reuse the string buffer that
    // represents the keyname of each component.

    // we'll need to store the entire prefix and then two characters to hold
    // each of the suffices. initialize the first part of the buffer with
    // the prefix itself and the last part of the buffer with dummy suffix
    int start = prefix.length();
    int end = start + 2; // maximum size of part suffix
    StringBuilder key = new StringBuilder(end);
    key.replace(0, start, prefix);

    // read each tensor component into a correspending array slot
    double[] t = tensorValues.get(); // new double[TENSOR_PARTS.length];
    for (int i = 0; i < t.length; ++i) {
      // replace the suffix of the buffer with the one that we are looking
      // for in this iteration
      key.replace(start, end, TENSOR_PARTS[i]);

      // get the value from the configuration; if it isn't found, then
      // use 0.0 as the value for this component
      String s = key.toString();
      t[i] = containsKey(s) ? getDouble(s) : 0.;
    }

    // create the tensor from the array of values
    return new Tensor3D(t[0], t[1], t[2], t[3], t[4], t[5]);
  }
  public void testPsi2DocMergeReplaceAfterAdd() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.insertString(document, 1, "a");
    buffer.insert(1, "a");

    synchronizer.replaceString(document, 3, 4, "a");
    buffer.replace(3, 4, "a");

    synchronizer.replaceString(document, 3, 5, "bb");
    buffer.replace(3, 5, "bb");
    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();
    assertEquals(affectedFragments.size(), 2);

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 3, 6);
  }
 private LimitType limitQuery(
     String limitPattern,
     LimitType limitType,
     String queryString,
     StringBuilder queryResult,
     Integer firstResult,
     Integer maxResults) {
   if (limitPattern == null) return null;
   int ix = limitPattern.indexOf("$S");
   if (ix >= 0) {
     limitType.afterSql = limitPattern.indexOf("$", ix + 1) > 0;
     queryResult.append(limitPattern.substring(0, ix));
     queryResult.append(queryString);
     queryResult.append(limitPattern.substring(ix + 2));
   } else {
     ix = limitPattern.indexOf("$s");
     if (ix >= 0) {
       limitType.afterSql = limitPattern.indexOf("$", ix + 1) > 0;
       int ix2 = queryString.toLowerCase().indexOf("select");
       if (ix2 < 0) return null;
       queryResult.append(limitPattern.substring(0, ix));
       queryResult.append(queryString.substring(ix2 + 6));
       queryResult.append(limitPattern.substring(ix + 2));
     } else {
       return null;
     }
   }
   if (limitType.alsoFirst) {
     ix = queryResult.indexOf("$F");
     if (ix >= 0) {
       if (queryResult.indexOf("$m", ix) < 0 && queryResult.indexOf("$M", ix) < 0)
         limitType.maxBeforeFirst = true;
       queryResult.replace(ix, ix + 2, "?");
     } else {
       ix = queryResult.indexOf("$f");
       if (ix >= 0) {
         limitType.zeroBasedFirst = true;
         if (queryResult.indexOf("$m", ix) < 0 && queryResult.indexOf("$M", ix) < 0)
           limitType.maxBeforeFirst = true;
         queryResult.replace(ix, ix + 2, "?");
       } else {
         return null;
       }
     }
   }
   ix = queryResult.indexOf("$M");
   if (ix >= 0) {
     queryResult.replace(ix, ix + 2, "?");
   } else {
     ix = queryResult.indexOf("$m");
     if (ix >= 0) {
       limitType.rowidBasedMax = true;
       queryResult.replace(ix, ix + 2, "?");
     } else {
       return null;
     }
   }
   return limitType;
 }
  public String getPositionAndAffiliationString(int limit, int additionalLength, String tail) {
    if (null == tail) {
      tail = "...";
    }
    StringBuilder sb = new StringBuilder();
    if (!Strings.isEmpty(this.get_sPosition())) {
      sb.append(this.get_sPosition());
    }
    if (!Strings.isEmpty(this.get_sPosition()) && !Strings.isEmpty(this.get_sAffiliation())) {
      sb.append(", ");
    }
    if (!Strings.isEmpty(this.get_sAffiliation())) {
      sb.append(this.get_sAffiliation());
    }
    int max = limit - additionalLength;

    // capitalize
    if (sb.length() > 0) {
      sb.replace(0, 1, new Character(sb.charAt(0)).toString().toUpperCase());
    }

    String result = null;
    if (sb.length() > max) {
      result = sb.substring(0, max) + tail;
    } else {
      result = sb.toString();
    }
    return result;
  }
 /**
  * Parse a CDATA String. If is a CDATA, removes leading and trailing string Otherwise does nothing
  *
  * @param string the string to parse
  * @return the parsed string
  */
 public static String parse(String string) {
   if (isCdata(string)) {
     StringBuilder sb = new StringBuilder(string.trim());
     sb.replace(0, CDATA_START.length(), "");
     int stopIndex = sb.lastIndexOf(CDATA_STOP);
     sb.replace(stopIndex, (stopIndex + CDATA_STOP.length()), "");
     string = sb.toString();
   }
   return string;
 }
 public String end() {
   if (json.length() > 1) {
     json.replace(json.length() - 1, json.length(), endChar);
     String jsonString = json.toString();
     json.replace(json.length() - 1, json.length(), divider);
     return jsonString;
   }
   String jsonString = json.append(endChar).toString();
   json.deleteCharAt(json.length() - 1);
   return jsonString;
 }
Example #10
0
 /** 将下划线风格替换为驼峰风格 */
 public static String underlineToCamelhump(String str) {
   Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
   StringBuilder builder = new StringBuilder(str);
   for (int i = 0; matcher.find(); i++) {
     builder.replace(
         matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
   }
   if (Character.isUpperCase(builder.charAt(0))) {
     builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
   }
   return builder.toString();
 }
Example #11
0
  public void charactersToUpperCase(StringBuilder sb) {

    if (!Character.isUpperCase(sb.charAt(0))) {
      sb.replace(0, 1, String.valueOf(sb.charAt(0)).toUpperCase());
    }
    for (int i = 0; i < sb.length() - 2; i++) {

      if (sb.charAt(i) == '.' && !Character.isUpperCase(sb.charAt(i + 2))) {

        sb.replace(i + 2, i + 3, String.valueOf(sb.charAt(i + 2)).toUpperCase());
      }
    }
  }
 private static GrStatement createAssignment(
     VariableInfo[] infos, GrMethodCallExpression callExpression, final Project project) {
   StringBuilder text = new StringBuilder();
   if (infos.length > 1) text.append('(');
   for (VariableInfo info : infos) {
     text.append(info.getName()).append(", ");
   }
   if (infos.length > 1) {
     text.replace(text.length() - 2, text.length(), ") =");
   } else {
     text.replace(text.length() - 2, text.length(), " = ");
   }
   text.append(callExpression.getText());
   return GroovyPsiElementFactory.getInstance(project).createExpressionFromText(text.toString());
 }
Example #13
0
  private String getJPQL(SearchCriterion sc) {

    boolean isWhere = false;
    StringBuilder sb = new StringBuilder();
    sb.append(" from ");
    sb.append(clazz.getName());
    sb.append(" t ");
    if (StringUtils.isNotBlank(sc.getRelevanceSearch())) {
      sb.append(sc.getRelevanceSearch());
    }
    if (!StringUtils.isEmpty(sc.getFilter())) {
      isWhere = true;
      sb.append(" where ");
      sb.append(sc.getFilter());
    }
    Map<String, Object> map = sc.getFilterMap();
    if (map != null && !map.isEmpty()) {
      if (!isWhere) {
        sb.append(" where ");
      } else {
        sb.append("   and ");
      }
      for (String s : map.keySet()) {
        sb.append(s);
        sb.append(" = :");
        if (s.split("\\.").length > 1) {
          sb.append(s.split("\\.")[1]);
        } else {
          sb.append(s);
        }
        sb.append("   and ");
      }
      sb.replace(sb.length() - 6, sb.length(), "");
    }
    // 拼装排序条件
    List<SortCriterion> sortList = sc.getSortCriteria();
    if (sortList != null && !sortList.isEmpty()) {
      sb.append(" order by ");
      for (SortCriterion s : sortList) {
        sb.append(s.getSortField());
        sb.append(" ");
        sb.append(s.getSortType());
        sb.append(",");
      }
      sb.replace(sb.length() - 1, sb.length(), "");
    }
    return sb.toString();
  }
 @Override
 public void closeDialogsWithData(DialogType type, String tag, Bundle dialogData) {
   DialogFragment openDialogFragment =
       (DialogFragment) getSupportFragmentManager().findFragmentByTag(tag);
   openDialogFragment.dismiss();
   if (type.name().equalsIgnoreCase(DialogType.addProfileDialog.name())) {
     StringBuilder battleTag =
         new StringBuilder(dialogData.getString(AddProfileDialogFragment.BATTLE_TAG_KEY));
     String regionString = dialogData.getString(AddProfileDialogFragment.SELECTED_REGION_KEY);
     if (battleTag.length() > 0) {
       battleTag.replace(0, 1, battleTag.substring(0, 1).toUpperCase(new Locale("en-US")));
     }
     constructAndExecuteQuery(QueryTypes.loadData, regionString, battleTag.toString());
   } else if (type.name().equalsIgnoreCase(DialogType.profileOptionsDialog.name())) {
     final String regionString = dialogData.getString(ProfileOptionsDialog.SELECTED_OPTION_KEY);
     final int selectedProfile = dialogData.getInt(ProfileOptionsDialog.PROFILE_POSITION_KEY);
     final ProfileModel profileModel = (ProfileModel) mProfiles.get(selectedProfile);
     if (regionString.equalsIgnoreCase(ProfileOptions.delete.name())) {
       constructAndExecuteQuery(
           QueryTypes.deleteData, profileModel.getServer(), profileModel.getBattleTag());
     } else if (regionString.equalsIgnoreCase(ProfileOptions.refresh.name())) {
       constructAndExecuteQuery(
           QueryTypes.loadData, profileModel.getServer(), profileModel.getBattleTag());
     }
   }
 }
 private void replaceNextPlaceHolders(
     StringBuilder sqlWithQuestionMarks, Object... valuesToReplace) {
   for (Object nextValue : valuesToReplace) {
     int index = sqlWithQuestionMarks.indexOf("?");
     sqlWithQuestionMarks.replace(index, index + 1, String.valueOf(nextValue));
   }
 }
Example #16
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getParameter("foo");

    String bar = param;
    if (param.length() > 1) {
      StringBuilder sbxyz89740 = new StringBuilder(param);
      bar = sbxyz89740.replace(param.length() - "Z".length(), param.length(), "Z").toString();
    }

    try {
      java.util.Properties Benchmarkprops = new java.util.Properties();
      Benchmarkprops.load(
          this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties"));
      String algorithm = Benchmarkprops.getProperty("hashAlg2", "SHA5");
      java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println("Problem executing hash - TestCase");
      throw new ServletException(e);
    }

    response
        .getWriter()
        .println("Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed");
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("vector");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = param;
    if (param != null && param.length() > 1) {
      StringBuilder sbxyz87271 = new StringBuilder(param);
      bar = sbxyz87271.replace(param.length() - "Z".length(), param.length(), "Z").toString();
    }

    double value = new java.util.Random().nextDouble();
    String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front.

    String user = "Donna";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && ++i < cookies.length && !foundUser; ) {
      javax.servlet.http.Cookie cookie = cookies[i];
      if (cookieName.equals(cookie.getName())) {
        if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
          foundUser = true;
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextDouble() executed");
  }
  public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);
    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();

    for (int i = 0; i < 10; i++) {
      synchronizer.insertString(document, i, "" + i);
      buffer.insert(i, "" + i);
    }

    assertEquals(1, affectedFragments.size());
    synchronizer.replaceString(document, 0, 20, "0123456789");
    buffer.replace(0, 20, "0123456789");

    assertEquals(1, affectedFragments.size());

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 5);
  }
  public static String getReadableVersion(String version) {
    try {
      String number = version.substring(version.indexOf("-") + 1, version.lastIndexOf("-"));
      String date =
          version.substring(
              version.lastIndexOf("-") + 1,
              version.endsWith(".zip") ? version.lastIndexOf(".") : version.length());

      SimpleDateFormat curFormater = new SimpleDateFormat("yyyyMMdd");
      Date dateObj = null;
      try {
        dateObj = curFormater.parse(date);
      } catch (ParseException e) {
        // ignore
      }
      SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy");

      if (dateObj == null) {
        return number;
      }
      String newDateStr = postFormater.format(dateObj);

      StringBuilder b = new StringBuilder(newDateStr);
      int i = 0;
      do {
        b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
        i = b.indexOf(" ", i) + 1;
      } while (i > 0 && i < b.length());
      return number + " - " + b.toString();
    } catch (Exception ex) {
      // unknown version format
      return version;
    }
  }
Example #20
0
  /**
   * Formats a URI by adding a forward slash and removing the last forward slash from the URI.
   *
   * <p>e.g. some/random/uri/ -> /some/random/uri e.g. some/random/uri -> /some/random/uri e.g.
   * /some/random/uri/ -> /some/random/uri e.g. / -> / e.g. ////// -> /
   *
   * @param uri
   * @return
   */
  public static String formatUri(String uri) {
    if (StringUtilities.nullSafeStartsWith(uri, "\\")) {
      // windows file system
      return uri;
    }

    if (StringUtilities.isBlank(uri) || StringUtilities.nullSafeEqualsIgnoreCase("/", uri)) {
      return "/";
    }

    final StringBuilder externalName = new StringBuilder(uri);

    if (externalName.charAt(0) != '/') {
      externalName.insert(0, "/");
    }

    int doubleSlash = externalName.indexOf("//");

    while (doubleSlash > -1) {
      // removes leading '/'
      externalName.replace(doubleSlash, doubleSlash + 2, "/");
      doubleSlash = externalName.indexOf("//");
    }

    if (externalName.charAt(externalName.length() - 1) == '/' && externalName.length() != 1) {
      externalName.deleteCharAt(externalName.length() - 1);
    }

    return externalName.toString();
  }
Example #21
0
  // helper
  private static boolean replace(StringBuilder sb, String str0, String str1) {
    int i = sb.indexOf(str0);
    if (i == -1) return false;

    sb.replace(i, i + str0.length(), str1);
    return true;
  }
Example #22
0
    public String doSomething(String param) throws ServletException, IOException {

      // Chain a bunch of propagators in sequence
      String a85270 = param; // assign
      StringBuilder b85270 = new StringBuilder(a85270); // stick in stringbuilder
      b85270.append(" SafeStuff"); // append some safe content
      b85270.replace(
          b85270.length() - "Chars".length(),
          b85270.length(),
          "Chars"); // replace some of the end content
      java.util.HashMap<String, Object> map85270 = new java.util.HashMap<String, Object>();
      map85270.put("key85270", b85270.toString()); // put in a collection
      String c85270 = (String) map85270.get("key85270"); // get it back out
      String d85270 = c85270.substring(0, c85270.length() - 1); // extract most of it
      String e85270 =
          new String(
              new sun.misc.BASE64Decoder()
                  .decodeBuffer(
                      new sun.misc.BASE64Encoder()
                          .encode(d85270.getBytes()))); // B64 encode and decode it
      String f85270 = e85270.split(" ")[0]; // split it on a space
      org.owasp.benchmark.helpers.ThingInterface thing =
          org.owasp.benchmark.helpers.ThingFactory.createThing();
      String g85270 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe'
      String bar = thing.doSomething(g85270); // reflection

      return bar;
    }
  /** @return new shift offset */
  private static int trimTag(StringBuilder buf, CommentTag tag, int shiftOffset) {
    int startOffset = tag.fStartOffset - shiftOffset;
    int endOffset = tag.fEndOffset - shiftOffset;
    buf.replace(startOffset, endOffset, ""); // $NON-NLS-1$

    return shiftOffset + tag.length() - 1;
  }
Example #24
0
    public static StringBuilder seqSubs(StringBuilder sb) {

      StringBuilder retSb = new StringBuilder(sb);
      int diff = 0;

      Matcher matcher = Pattern.compile("seq\\(([0-9]+),([0-9]+),([0-9]+)\\)").matcher(retSb);

      while (matcher.find()) {
        int start = matcher.start() + diff;
        int end = matcher.end() + diff;

        String tmp;

        tmp = matcher.group(1);
        int from = Integer.parseInt(tmp);
        tmp = matcher.group(2);
        int to = Integer.parseInt(tmp);
        tmp = matcher.group(3);
        int step = Integer.parseInt(tmp);

        StringBuilder sb_seq = new StringBuilder();
        for (int i = from; i < to; i += step) {
          sb_seq.append(i + " ");
        }
        int length_new = sb_seq.length();
        int length_old = end - start;
        diff += (length_new - length_old);

        retSb.replace(start, end, sb_seq.toString());
      }
      return retSb;
    }
Example #25
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheParameter("foo");

    // Chain a bunch of propagators in sequence
    String a93077 = param; // assign
    StringBuilder b93077 = new StringBuilder(a93077); // stick in stringbuilder
    b93077.append(" SafeStuff"); // append some safe content
    b93077.replace(
        b93077.length() - "Chars".length(),
        b93077.length(),
        "Chars"); // replace some of the end content
    java.util.HashMap<String, Object> map93077 = new java.util.HashMap<String, Object>();
    map93077.put("key93077", b93077.toString()); // put in a collection
    String c93077 = (String) map93077.get("key93077"); // get it back out
    String d93077 = c93077.substring(0, c93077.length() - 1); // extract most of it
    String e93077 =
        new String(
            new sun.misc.BASE64Decoder()
                .decodeBuffer(
                    new sun.misc.BASE64Encoder()
                        .encode(d93077.getBytes()))); // B64 encode and decode it
    String f93077 = e93077.split(" ")[0]; // split it on a space
    org.owasp.benchmark.helpers.ThingInterface thing =
        org.owasp.benchmark.helpers.ThingFactory.createThing();
    String bar = thing.doSomething(f93077); // reflection

    java.io.File file = new java.io.File(bar);
  }
Example #26
0
  private Class<?> getGeneratedComponent(URLClassLoader loader) {
    try {
      StringBuilder s1 = generateSource();

      String digest = getDigest(s1.toString());
      String name = "Comp_" + digest;
      int indexOf = s1.indexOf("$$$");
      s1.replace(indexOf, indexOf + 3, name);

      String source = s1.toString();

      if (log.isDebugEnabled()) {
        log.debug("Generated Class :" + name);
        log.debug("Generated Source:\n" + source);
      }

      ModelCompiler mc = ModelCompiler.create(System.getProperty("oms.modelcompiler"));
      Class jc = mc.compile(loader, name, source);

      // TODO refactor for more generic use (internal, external compiler).
      // oms3.compiler.Compiler.compile1(log, name, source); // This is
      // external javac
      // Class jc = loader.loadClass(name);

      // oms3.compiler.Compiler tc =
      // oms3.compiler.Compiler.singleton(loader);
      // Class jc = tc.compileSource(name, source);
      return jc;
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }
  @Override
  public void pushToDB(Connection con) {
    Statement stmt;

    try {
      stmt = con.createStatement();
      StringBuilder sqlString = new StringBuilder("INSERT INTO question_response VALUES(null,");
      sqlString.append(statement);
      sqlString.append("\",\" ");
      for (String string : answers) {
        sqlString.append(string);
        sqlString.append(" &&& ");
      }
      sqlString.replace(sqlString.length() - 5, sqlString.length(), "");
      sqlString.append("\" ");

      System.out.print(sqlString.toString());
      ResultSet resultSet = stmt.executeQuery(sqlString.toString());

      stmt = con.createStatement();
      sqlString = new StringBuilder("SELECT * FROM question_response WHERE statement=\"");
      sqlString.append(statement);
      sqlString.append("\" ");

      System.out.print(sqlString.toString());
      resultSet = stmt.executeQuery(sqlString.toString());

      while (resultSet.next()) {
        this.setqID(resultSet.getInt("question_id")); // will always be the last one
      }
    } catch (Exception e) {

    }
  }
Example #28
0
 /**
  * 获取指定文件大小的字符串单位B? KB? MB? GB?
  *
  * @param filesize 文件大小(byte)
  * @return 文件大小的字符串单位B? KB? MB? GB?
  */
 public static String formatSize(long filesize) {
   if (filesize < 0) {
     return "0 B";
   }
   if (df == null) {
     df = new DecimalFormat("#.00");
   }
   if (mstrbuf == null) {
     mstrbuf = new StringBuilder();
   }
   mstrbuf.replace(0, mstrbuf.length(), STR_EMPTY);
   if (filesize < 1024) {
     mstrbuf.append(filesize);
     mstrbuf.append(" B");
   } else if (filesize < 1048576) {
     mstrbuf.append(df.format((double) filesize / 1024));
     mstrbuf.append(" K");
   } else if (filesize < 1073741824) {
     mstrbuf.append(df.format((double) filesize / 1048576));
     mstrbuf.append(" M");
   } else {
     mstrbuf.append(df.format((double) filesize / 1073741824));
     mstrbuf.append(" G");
   }
   return mstrbuf.toString();
 }
  private static String doSomething(String param) throws ServletException, IOException {

    // Chain a bunch of propagators in sequence
    String a47625 = param; // assign
    StringBuilder b47625 = new StringBuilder(a47625); // stick in stringbuilder
    b47625.append(" SafeStuff"); // append some safe content
    b47625.replace(
        b47625.length() - "Chars".length(),
        b47625.length(),
        "Chars"); // replace some of the end content
    java.util.HashMap<String, Object> map47625 = new java.util.HashMap<String, Object>();
    map47625.put("key47625", b47625.toString()); // put in a collection
    String c47625 = (String) map47625.get("key47625"); // get it back out
    String d47625 = c47625.substring(0, c47625.length() - 1); // extract most of it
    String e47625 =
        new String(
            new sun.misc.BASE64Decoder()
                .decodeBuffer(
                    new sun.misc.BASE64Encoder()
                        .encode(d47625.getBytes()))); // B64 encode and decode it
    String f47625 = e47625.split(" ")[0]; // split it on a space
    org.owasp.benchmark.helpers.ThingInterface thing =
        org.owasp.benchmark.helpers.ThingFactory.createThing();
    String bar = thing.doSomething(f47625); // reflection

    return bar;
  }
 public static StringBuilder firstToLowerCase(StringBuilder builder) {
   String lower = builder.substring(0, 1).toLowerCase();
   builder.replace(0, 1, lower);
   // String post = string.substring(1, string.length());
   // String first = ("" + string.charAt(0)).toLowerCase();
   return builder;
 }