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);
  }
Exemplo n.º 2
1
 /**
  * Given a string, replace all tabs with the appropriate number of spaces.
  *
  * @param tabLength the length of each tab.
  * @param s the String to scan.
  */
 public static void replaceTabs(int tabLength, StringBuilder s) {
   if (whitespace == null || whitespace.length() < tabLength)
     whitespace = String.format("%" + tabLength + "s", " ");
   int index = 0;
   while ((index = s.indexOf("\t", index)) != -1) {
     int spaceCount = tabLength - index % tabLength;
     s.replace(index, index + 1, whitespace.substring(0, spaceCount));
     index += spaceCount;
   }
 }
Exemplo n.º 3
1
  public static StringBuilder replaceAll(StringBuilder in, String p, String r) {
    int pl = p.length(), rl = r.length(), s = in.indexOf(p, 0);

    if (pl == 0) return in;

    while (s >= 0) {
      in.replace(s, s + pl, r);
      s = in.indexOf(p, s + rl);
    }

    return in;
  }
Exemplo n.º 4
1
 /**
  * @param str The string to find the replacements for.
  * @param fromIndex The index from which replacements are found.
  * @param level The recursion level. The search stops if level is &gt; MAX_RECURSION_LEVEL.
  * @return A list of all possible replacements of a {#link str} given string
  */
 public List<String> getAllReplacements(final String str, final int fromIndex, final int level) {
   List<String> replaced = new ArrayList<>();
   if (level > MAX_RECURSION_LEVEL) { // Stop searching at some point
     replaced.add(str);
     return replaced;
   }
   StringBuilder sb = new StringBuilder();
   sb.append(str);
   int index = MAX_WORD_LENGTH;
   String key = "";
   int keyLength = 0;
   boolean found = false;
   // find first possible replacement after fromIndex position
   for (final String auxKey : replacementsTheRest.keySet()) {
     int auxIndex = sb.indexOf(auxKey, fromIndex);
     if (auxIndex > -1
         && (auxIndex < index
             || (auxIndex == index
                 && !(auxKey.length() < keyLength)))) { // select the longest possible key
       index = auxIndex;
       key = auxKey;
       keyLength = auxKey.length();
     }
   }
   if (index < MAX_WORD_LENGTH) {
     for (final String rep : replacementsTheRest.get(key)) {
       // start a branch without replacement (only once per key)
       if (!found) {
         replaced.addAll(getAllReplacements(str, index + key.length(), level + 1));
         found = true;
       }
       // avoid unnecessary replacements (ex. don't replace L by L·L when L·L already present)
       int ind = sb.indexOf(rep, fromIndex - rep.length() + 1);
       if (rep.length() > key.length()
           && ind > -1
           && (ind == index || ind == index - rep.length() + 1)) {
         continue;
       }
       // start a branch with replacement
       sb.replace(index, index + key.length(), rep);
       replaced.addAll(getAllReplacements(sb.toString(), index + rep.length(), level + 1));
       sb.setLength(0);
       sb.append(str);
     }
   }
   if (!found) {
     replaced.add(sb.toString());
   }
   return replaced;
 }
Exemplo n.º 5
0
 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());
 }
  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);
  }
Exemplo n.º 7
0
  // Utility method used by viewId conversion.  Appends the extension
  // if no extension is present.  Otherwise, replaces the extension.
  private void appendOrReplaceExtension(
      String viewId, String ext, int length, int extIdx, StringBuilder buffer) {

    buffer.setLength(0);
    buffer.append(viewId);

    if (extIdx != -1) {
      buffer.replace(extIdx, length, ext);
    } else {
      // no extension in the provided viewId, append the suffix
      buffer.append(ext);
    }
  }
Exemplo n.º 8
0
  /**
   * Configures the basic replacements based on the configured options.
   *
   * @param options Options that will affect what is replaced.
   */
  @SuppressWarnings({"OverlyLongMethod"})
  private void setupReplacements(Options options) {
    this.replacements = new HashMap<String, String>();

    // build replacement regex
    StringBuilder entities = new StringBuilder(replacements.size() * 5);

    // this is a special case for double-encoded HTML entities.
    entities.append("&(?>amp;([#a-z0-9]++;)|(?>");
    addRepl(entities, "&amp;", "&");
    addRepl(entities, "&lt;", "<");
    addRepl(entities, "&gt;", ">");
    addRepl(entities, "&quot;", "\"");
    if (options.reverseHtmlSmartQuotes) {
      addRepl(entities, "&ldquo;", "\"");
      addRepl(entities, "&rdquo;", "\"");
      addRepl(entities, "&lsquo;", "\'");
      addRepl(entities, "&rsquo;", "\'");
      addRepl(entities, "&apos;", "\'");
      addRepl(entities, "&laquo;", "<<");
      addRepl(entities, "&raquo;", ">>");
    }
    if (options.reverseHtmlSmartPunctuation) {
      addRepl(entities, "&ndash;", "--");
      addRepl(entities, "&mdash;", "---");
      addRepl(entities, "&hellip;", "...");
    }
    entities.replace(entities.length() - 1, entities.length(), ");)");

    entityReplacementsPattern = Pattern.compile(entities.toString(), Pattern.CASE_INSENSITIVE);

    if (options.reverseUnicodeSmartPunctuation || options.reverseUnicodeSmartQuotes) {
      StringBuilder unicode = new StringBuilder("[\\Q");
      if (options.reverseUnicodeSmartQuotes) {
        addRepl(unicode, "\u201c", "\""); // left double quote: “
        addRepl(unicode, "\u201d", "\""); // right double quote: ”
        addRepl(unicode, "\u2018", "\'"); // left single quote: ‘
        addRepl(unicode, "\u2019", "\'"); // right single quote: ’
        addRepl(unicode, "\u00ab", "<<"); // left angle quote: «
        addRepl(unicode, "\u00bb", ">>"); // right angle quote: »
      }
      if (options.reverseUnicodeSmartPunctuation) {
        addRepl(unicode, "\u2013", "--"); // en-dash: –
        addRepl(unicode, "\u2014", "---"); // em-dash: —
        addRepl(unicode, "\u2026", "..."); // ellipsis: …
      }
      unicode.append("\\E]");
      unicodeReplacementsPattern = Pattern.compile(unicode.toString());
    }
  }
Exemplo n.º 9
0
 private void addClassPathToScriptEngine(File jarFile) throws ConfigurationException {
   try {
     StringBuilder cmd = new StringBuilder(addClassPathCmd);
     int tagStartPos = cmd.indexOf(parameterTag);
     int tageEndPos = tagStartPos + parameterTag.length();
     cmd.replace(tagStartPos, tageEndPos, jarFile.getAbsolutePath().replace("\\", "/"));
     // System.out.println("cmd " + cmd.toString());
     engine.eval("add-classpath", 1, 1, cmd.toString()); // $NON-NLS-1$
   } catch (Exception ex) {
     String msg = String.format("Failed to load class path %s", jarFile.getName()); // $NON-NLS-1$
     System.err.println(msg + " " + ex);
     throw new ConfigurationException(msg, ex);
   }
 }
Exemplo n.º 10
0
 /**
  * Imports a package into the script engine
  *
  * @param pkgName the name of the package
  * @throws ConfigurationException if the package cannot be imported
  */
 private void importPkgToScriptEngine(String pkgName) throws ConfigurationException {
   try {
     StringBuilder cmd = new StringBuilder(importPackageCmd);
     int tagStartPos = cmd.indexOf(parameterTag);
     int tageEndPos = tagStartPos + parameterTag.length();
     cmd.replace(tagStartPos, tageEndPos, pkgName);
     // System.out.println("cmd " + cmd.toString());
     engine.eval("load-packages", 1, 1, cmd.toString()); // $NON-NLS-1$
   } catch (Exception ex) {
     String msg = String.format("Failed to import package %s", pkgName); // $NON-NLS-1$
     System.err.println(msg + " " + ex);
     throw new ConfigurationException(msg, ex);
   }
 }
Exemplo n.º 11
0
  public void testPsi2DocReplaceAfterAdd() 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.commitTransaction(document);

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

    assertValidMarker(marker, 3, 6);
  }
Exemplo n.º 12
0
  public void testPsi2DocForwardRangesChanges() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

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

    synchronizer.insertString(document, 7, "b");
    buffer.insert(7, "b");

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

    synchronizer.commitTransaction(document);

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

    assertValidMarker(marker, 3, 8);
  }
Exemplo n.º 13
0
  public static int solution(int X) {
    // identical adjacent digits
    // remove one from the group
    // largest possible

    int curMax = Integer.MIN_VALUE;

    StringBuilder sb = new StringBuilder("" + X);

    // identify groups
    for (int i = 1; i < sb.length(); i++) {
      // group
      if (sb.charAt(i - 1) == sb.charAt(i)) {
        char ch = sb.charAt(i);
        sb.replace(i, i + 1, "");
        curMax = Math.max(curMax, Integer.parseInt(sb.toString()));
        sb.insert(i, ch);
      }
    }
    return curMax;
  }
Exemplo n.º 14
0
    /** @return */
    public String build() {
      String path = prefixPath(baseUrl.getPath(), this.path);
      int port = baseUrl.getPort();
      if (baseUrl.getPort() == baseUrl.getDefaultPort()) port = -1;

      String host = baseUrl.getHost();
      if (StringUtils.isNotBlank(host) && host.startsWith(".")) host = host.substring(1);

      final StringBuilder builder;
      try {
        builder = new StringBuilder(new URL(baseUrl.getProtocol(), host, port, path).toString());
      } catch (MalformedURLException e) {
        throw new RuntimeException(e);
      }

      StringBuilder query = new StringBuilder();
      for (Entry<String, Object> entry : urlParams.entrySet()) {
        final String key = entry.getKey();
        Object value = entry.getValue();
        if (value == null) continue;

        if (value instanceof Object[]) {
          for (final Object v : (Object[]) value) {
            appendQueryString(key, v, query);
          }
        } else if (value instanceof Collection) {
          for (final Object v : (Collection<?>) value) {
            appendQueryString(key, v, query);
          }
        } else appendQueryString(key, value, query);
      }
      if (query.length() > 0) query.replace(0, 1, "?");
      builder.append(query);

      if (values.get() != null && values.get().size() > 0)
        return MessageFormat.format(builder.toString(), values.get().toArray());
      return builder.toString();
    }
  protected String parseStringValue(
      String strVal, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) {

    StringBuilder buf = new StringBuilder(strVal);

    int startIndex = strVal.indexOf(this.placeholderPrefix);
    while (startIndex != -1) {
      int endIndex = findPlaceholderEndIndex(buf, startIndex);
      if (endIndex != -1) {
        String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
        String originalPlaceholder = placeholder;
        if (!visitedPlaceholders.add(originalPlaceholder)) {
          throw new IllegalArgumentException(
              "Circular placeholder reference '"
                  + originalPlaceholder
                  + "' in property definitions");
        }
        // Recursive invocation, parsing placeholders contained in the placeholder key.
        placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
        // Now obtain the value for the fully resolved key...
        String propVal = placeholderResolver.resolvePlaceholder(placeholder);
        if (propVal == null && this.valueSeparator != null) {
          int separatorIndex = placeholder.indexOf(this.valueSeparator);
          if (separatorIndex != -1) {
            String actualPlaceholder = placeholder.substring(0, separatorIndex);
            String defaultValue =
                placeholder.substring(separatorIndex + this.valueSeparator.length());
            propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
            if (propVal == null) {
              propVal = defaultValue;
            }
          }
        }
        if (propVal != null) {
          // Recursive invocation, parsing placeholders contained in the
          // previously resolved placeholder value.
          propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
          buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
          if (logger.isTraceEnabled()) {
            logger.trace("Resolved placeholder '" + placeholder + "'");
          }
          startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length());
        } else if (this.ignoreUnresolvablePlaceholders) {
          // Proceed with unprocessed value.
          startIndex =
              buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
        } else {
          throw new IllegalArgumentException(
              "Could not resolve placeholder '"
                  + placeholder
                  + "'"
                  + " in string value \""
                  + strVal
                  + "\"");
        }
        visitedPlaceholders.remove(originalPlaceholder);
      } else {
        startIndex = -1;
      }
    }

    return buf.toString();
  }