Exemplo n.º 1
1
 /**
  * Removes comments from the specified string and returns the first characters of a query.
  *
  * @param qu query string
  * @param max maximum length of string to return
  * @return result
  */
 public static String removeComments(final String qu, final int max) {
   final StringBuilder sb = new StringBuilder();
   int m = 0;
   boolean s = false;
   final int cl = qu.length();
   for (int c = 0; c < cl && sb.length() < max; ++c) {
     final char ch = qu.charAt(c);
     if (ch == 0x0d) continue;
     if (ch == '(' && c + 1 < cl && qu.charAt(c + 1) == ':') {
       if (m == 0 && !s) {
         sb.append(' ');
         s = true;
       }
       ++m;
       ++c;
     } else if (m != 0 && ch == ':' && c + 1 < cl && qu.charAt(c + 1) == ')') {
       --m;
       ++c;
     } else if (m == 0) {
       if (ch > ' ') sb.append(ch);
       else if (!s) sb.append(' ');
       s = ch <= ' ';
     }
   }
   if (sb.length() >= max) sb.append("...");
   return sb.toString().trim();
 }
Exemplo n.º 2
1
 /**
  * Returns a map with variable bindings.
  *
  * @param opts main options
  * @return bindings
  */
 public static HashMap<String, String> bindings(final MainOptions opts) {
   final HashMap<String, String> bindings = new HashMap<>();
   final String bind = opts.get(MainOptions.BINDINGS).trim();
   final StringBuilder key = new StringBuilder();
   final StringBuilder val = new StringBuilder();
   boolean first = true;
   final int sl = bind.length();
   for (int s = 0; s < sl; s++) {
     final char ch = bind.charAt(s);
     if (first) {
       if (ch == '=') {
         first = false;
       } else {
         key.append(ch);
       }
     } else {
       if (ch == ',') {
         if (s + 1 == sl || bind.charAt(s + 1) != ',') {
           bindings.put(key.toString().trim(), val.toString());
           key.setLength(0);
           val.setLength(0);
           first = true;
           continue;
         }
         // literal commas are escaped by a second comma
         s++;
       }
       val.append(ch);
     }
   }
   if (key.length() != 0) bindings.put(key.toString().trim(), val.toString());
   return bindings;
 }
Exemplo n.º 3
1
Arquivo: Macro.java Projeto: bramk/bnd
  int process(CharSequence org, int index, char begin, char end, StringBuilder result, Link link) {
    StringBuilder line = new StringBuilder(org);
    int nesting = 1;

    StringBuilder variable = new StringBuilder();
    outer:
    while (index < line.length()) {
      char c1 = line.charAt(index++);
      if (c1 == end) {
        if (--nesting == 0) {
          result.append(replace(variable.toString(), link));
          return index;
        }
      } else if (c1 == begin) nesting++;
      else if (c1 == '\\' && index < line.length() - 1 && line.charAt(index) == '$') {
        // remove the escape backslash and interpret the dollar
        // as a
        // literal
        index++;
        variable.append('$');
        continue outer;
      } else if (c1 == '$' && index < line.length() - 2) {
        char c2 = line.charAt(index);
        char terminator = getTerminator(c2);
        if (terminator != 0) {
          index = process(line, index + 1, c2, terminator, variable, link);
          continue outer;
        }
      } else if (c1 == '.' && index < line.length() && line.charAt(index) == '/') {
        // Found the sequence ./
        if (index == 1 || Character.isWhitespace(line.charAt(index - 2))) {
          // make sure it is preceded by whitespace or starts at begin
          index++;
          variable.append(domain.getBase().getAbsolutePath());
          variable.append('/');
          continue outer;
        }
      }
      variable.append(c1);
    }
    result.append(variable);
    return index;
  }
Exemplo n.º 4
1
  /** Takes a string and hides its extension */
  public static String hideExtension(final String str) {
    String[] arr = str.split("\\.");

    if (arr.length <= 1) return str; // there was no "." in str.

    StringBuilder sb = new StringBuilder("");
    for (int i = 0; i < arr.length - 1; ++i) {
      if (sb.length() > 0) sb.append(".");
      sb.append(arr[i]);
    }
    return sb.toString();
  }
Exemplo n.º 5
0
  @SuppressWarnings("deprecation")
  public void testAllResolved() {
    assertNotNull("Expected a Bundle Context", context);
    StringBuilder sb = new StringBuilder();

    for (Bundle b : context.getBundles()) {
      if (b.getState() == Bundle.INSTALLED
          && b.getHeaders().get(aQute.bnd.osgi.Constants.FRAGMENT_HOST) == null) {
        try {
          b.start();
        } catch (BundleException e) {
          sb.append(b.getBundleId())
              .append(" ")
              .append(b.getSymbolicName())
              .append(";")
              .append(b.getVersion())
              .append("\n");
          sb.append("    ").append(e.getMessage()).append("\n\n");
          System.err.println(e.getMessage());
        }
      }
    }
    Matcher matcher = IP_P.matcher(sb);
    String out =
        matcher.replaceAll(
            "\n\n         " + aQute.bnd.osgi.Constants.IMPORT_PACKAGE + ": $1;version=[$2,$3)\n");
    assertTrue("Unresolved bundles\n" + out, sb.length() == 0);
  }
Exemplo n.º 6
0
  public void insertListOfCallPoints(@Nullable List<CallPoint> callPoints) {
    if (content.length() == 0) {
      content.append(EOL).append("      ");
    }

    content.append("  <ol style='display:none'>");

    if (callPoints == null) {
      content.append("</ol>").append(EOL).append("      ");
      return;
    }

    content.append(EOL);

    CallPoint currentCP = callPoints.get(0);
    appendTestMethod(currentCP.getStackTraceElement());
    appendRepetitionCountIfNeeded(currentCP);

    for (int i = 1, n = callPoints.size(); i < n; i++) {
      CallPoint nextCP = callPoints.get(i);
      StackTraceElement ste = nextCP.getStackTraceElement();

      if (nextCP.isSameTestMethod(currentCP)) {
        content.append(", ").append(ste.getLineNumber());
      } else {
        content.append("</li>").append(EOL);
        appendTestMethod(ste);
      }

      appendRepetitionCountIfNeeded(nextCP);
      currentCP = nextCP;
    }

    content.append("</li>").append(EOL).append("        </ol>").append(EOL).append("      ");
  }
  // todo: give options for document splitting. A line or the whole file or
  // sentence splitting as now
  public Iterator<List<IN>> getIterator(Reader r) {
    Tokenizer<IN> tokenizer = tokenizerFactory.getTokenizer(r);
    // PTBTokenizer.newPTBTokenizer(r, false, true);
    List<IN> words = new ArrayList<IN>();
    IN previous = tokenFactory.makeToken();
    StringBuilder prepend = new StringBuilder();

    /*
     * This changes SGML tags into whitespace -- it should maybe be moved
     * elsewhere
     */
    while (tokenizer.hasNext()) {
      IN w = tokenizer.next();
      String word = w.get(CoreAnnotations.TextAnnotation.class);
      Matcher m = sgml.matcher(word);
      if (m.matches()) {

        String before = StringUtils.getNotNullString(w.get(CoreAnnotations.BeforeAnnotation.class));
        String after = StringUtils.getNotNullString(w.get(CoreAnnotations.AfterAnnotation.class));
        prepend.append(before).append(word);
        String previousTokenAfter =
            StringUtils.getNotNullString(previous.get(CoreAnnotations.AfterAnnotation.class));
        previous.set(AfterAnnotation.class, previousTokenAfter + word + after);
        // previous.appendAfter(w.word() + w.after());
      } else {

        String before = StringUtils.getNotNullString(w.get(CoreAnnotations.BeforeAnnotation.class));
        if (prepend.length() > 0) {
          w.set(BeforeAnnotation.class, prepend.toString() + before);
          // w.prependBefore(prepend.toString());
          prepend = new StringBuilder();
        }
        words.add(w);
        previous = w;
      }
    }

    List<List<IN>> sentences = wts.process(words);
    String after = "";
    IN last = null;
    for (List<IN> sentence : sentences) {
      int pos = 0;
      for (IN w : sentence) {
        w.set(PositionAnnotation.class, Integer.toString(pos));
        after = StringUtils.getNotNullString(w.get(CoreAnnotations.AfterAnnotation.class));
        w.remove(AfterAnnotation.class);
        last = w;
      }
    }
    if (last != null) {
      last.set(AfterAnnotation.class, after);
    }

    return sentences.iterator();
  }
Exemplo n.º 8
0
  // Derived from http://stackoverflow.com/a/3054692/250076
  public static File getRelativeFile(File targetFile, File baseFile) {
    try {
      targetFile = targetFile.getCanonicalFile();
      baseFile = baseFile.getCanonicalFile();
    } catch (IOException ignored) {
    }
    String pathSeparator = File.separator;
    String basePath = baseFile.getAbsolutePath();
    String normalizedTargetPath = normalize(targetFile.getAbsolutePath(), pathSeparator);
    String normalizedBasePath = normalize(basePath, pathSeparator);

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length
        && commonIndex < base.length
        && target[commonIndex].equals(base[commonIndex])) {
      common.append(target[commonIndex]).append(pathSeparator);
      commonIndex++;
    }

    if (commonIndex == 0) {
      throw new Error(
          "No common path element found for '"
              + normalizedTargetPath
              + "' and '"
              + normalizedBasePath
              + '\'');
    }

    boolean baseIsFile = true;

    if (baseFile.exists()) {
      baseIsFile = baseFile.isFile();
    } else if (basePath.endsWith(pathSeparator)) {
      baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
      int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

      for (int i = 0; i < numDirsUp; i++) {
        relative.append("..").append(pathSeparator);
      }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return new File(relative.toString());
  }
Exemplo n.º 9
0
  /** pad a value according the field definition. */
  private void padField(Map<String, String> extraparams, Field field) {
    String name = field.getName();
    String value = extraparams.get(name);
    PadDirectionList padDir = field.getPadDir();
    int requiredLength = field.getLength();

    // assert value != null;
    if (value == null) return;

    String padCharString = field.getPadChar();
    // if no pad char specified, don't attempt padding
    if (padCharString == null) return;
    assert padCharString.length() > 0;
    char padChar = padCharString.charAt(0);

    StringBuilder buf = new StringBuilder(requiredLength);
    if (padDir == PadDirectionList.LEFT) {
      for (int i = 0; i < requiredLength - value.length(); i++) buf.append(padChar);
      buf.append(value);
    } else if (padDir == PadDirectionList.RIGHT) {
      buf.append(value);
      for (int i = 0; i < requiredLength - value.length(); i++) buf.append(padChar);
    }
    assert buf.length() == requiredLength;
    if (requiredLength != value.length()) {
      // System.out.println("    updated " + name + " to '" + buf + "'");
      extraparams.put(name, buf.toString());
    }
    /*
    else {
        StringBuilder mybuf = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
    	if (i > 0)
    	    mybuf.append(',');
    	mybuf.append('\'');
    	mybuf.append(value.charAt(i));
    	mybuf.append('\'');
        }


        System.out.println("    field " + name + " not padded as " + mybuf.toString() + " is already " + requiredLength + " characters long");
    }
    */
  }
Exemplo n.º 10
0
 private static String getUnmatchedBrackets(final String initialText) {
   String text = initialText.replaceAll("\\\\.", "_"); // Remove escaped characters.
   text = text.replaceAll("'.'", "_"); // Remove character literals.
   text = text.replaceAll("\"([^\\n]*?)\"", "_"); // Remove string literals.
   text = text.replaceAll("/\\*(?s).*?\\*/", "_"); // Remove C comments.
   text = text.replaceAll("//[^\\n]*", "_"); // Remove C++ comments.
   StringBuilder unmatchedBrackets = new StringBuilder();
   for (int i = 0; i < text.length(); ++i) {
     char ch = text.charAt(i);
     if (PBracketUtilities.isOpenBracket(ch) && ch != '<') {
       unmatchedBrackets.append(ch);
     } else if (PBracketUtilities.isCloseBracket(ch) && ch != '>') {
       char openBracket = PBracketUtilities.getPartnerForBracket(ch);
       int lastCharIndex = unmatchedBrackets.length() - 1;
       if (lastCharIndex >= 0 && unmatchedBrackets.charAt(lastCharIndex) == openBracket) {
         unmatchedBrackets.deleteCharAt(lastCharIndex);
       } else {
         unmatchedBrackets.append(ch);
       }
     }
   }
   return unmatchedBrackets.toString();
 }