示例#1
1
 /**
  * Trim leading and trailing whitespace from the given String.
  *
  * @param str the String to check
  * @return the trimmed String
  * @see Character#isWhitespace
  */
 public static String trimWhitespace(String str) {
   if (!hasLength(str)) {
     return str;
   }
   StringBuilder sb = new StringBuilder(str);
   while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
     sb.deleteCharAt(0);
   }
   while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
     sb.deleteCharAt(sb.length() - 1);
   }
   return sb.toString();
 }
示例#2
1
  // tokenizes a string for PBM and PGM headers and plain PBM and PGM data.  If oneChar is true,
  // then
  // rather than parsing a whole string, a single character is read (not including whitespace or
  // comments)
  static String tokenizeString(InputStream stream, boolean oneChar) throws IOException {
    final int EOF = -1;

    StringBuilder b = new StringBuilder();
    int c;
    boolean inComment = false;

    while (true) {
      c = stream.read();
      if (c == EOF)
        throw new IOException(
            "Stream ended prematurely, before table reading was completed."); // no more tokens
      else if (inComment) {
        if (c == '\r' || c == '\n') // escape the comment
        inComment = false;
        else {
        } // do nothing
      } else if (Character.isWhitespace((char) c)) {
      } // do nothing
      else if (c == '#') // start of a comment
      {
        inComment = true;
      } else // start of a string
      {
        b.append((char) c);
        break;
      }
    }

    if (oneChar) return b.toString();

    // at this point we have a valid string.  We read until whitespace or a #
    while (true) {
      c = stream.read();
      if (c == EOF) break;
      else if (c == '#') // start of comment, read until a '\n'
      {
        while (true) {
          c = stream.read(); // could hit EOF, which is fine
          if (c == EOF) break;
          else if (c == '\r' || c == '\n') break;
        }
        // break;   // comments are not delimiters
      } else if (Character.isWhitespace((char) c)) break;
      else b.append((char) c);
    }
    return b.toString();
  }
  private static void autoImport(final PsiFile file, int offset, final Editor editor) {
    final CharSequence text = editor.getDocument().getCharsSequence();
    while (offset > 0 && Character.isJavaIdentifierPart(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0 || text.charAt(offset) != '.') return;

    offset--;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    PsiJavaCodeReferenceElement element =
        extractReference(
            PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiExpression.class, false));
    if (element == null) return;

    while (true) {
      final PsiJavaCodeReferenceElement qualifier = extractReference(element.getQualifier());
      if (qualifier == null) break;

      element = qualifier;
    }
    if (!(element.getParent() instanceof PsiMethodCallExpression)
        && element.multiResolve(true).length == 0) {
      new ImportClassFix(element).doFix(editor, false, false);
    }
  }
  private static boolean isWhitespace(String text) {
    if (text == null) return true;

    boolean isWhitespace = true;

    for (int i = text.length() - 1; i >= 0; i--) {
      char ch = text.charAt(i);

      if (!Character.isWhitespace(ch)) {
        // check for comment
        if (ch == '>' && text.indexOf("-->") + 2 == i) {
          int head = text.indexOf("<!--");

          if (head >= 0) {
            for (int j = 0; j < head; j++) {
              if (!Character.isWhitespace(text.charAt(j))) {
                return false;
              }
            }

            return true;
          }
        }

        return false;
      }
    }

    return true;
  }
  private void write(CharSequence text, boolean gsp) {
    if (!gsp) {
      out.print(text);
      return;
    }

    for (int ix = 0, ixz = text.length(); ix < ixz; ix++) {
      char c = text.charAt(ix);
      String rep = null;
      if (Character.isWhitespace(c)) {
        for (ix++; ix < ixz; ix++) {
          if (Character.isWhitespace(text.charAt(ix))) {
            continue;
          }
          ix--;
          rep = " ";
          break;
        }
      } else if (c == '&') {
        if (match("&semi;", text, ix)) {
          rep = ";";
          ix += 5;
        } else if (match("&amp;", text, ix)) {
          rep = "&";
          ix += 4;
        } else if (match("&lt;", text, ix)) {
          rep = "<";
          ix += 3;
        } else if (match("&gt;", text, ix)) {
          rep = ">";
          ix += 3;
        }
      } else if (c == '<') {
        if (match("<br>", text, ix) || match("<hr>", text, ix)) {
          rep = "\n";
          // incrementLineNumber();
          ix += 3;
        } else {
          int end = match(PARA_BREAK, text, ix);
          if (end <= 0) end = match(ROW_BREAK, text, ix);
          if (end > 0) {
            rep = "\n";
            // incrementLineNumber();
            ix = end;
          }
        }
      }
      if (rep != null) {
        out.print(rep);
      } else {
        out.print(c);
      }
    }
  }
示例#6
0
 public static String[] splitwords(String text) {
   ArrayList<String> words = new ArrayList<String>();
   StringBuilder buf = new StringBuilder();
   String st = "ws";
   int i = 0;
   while (i < text.length()) {
     char c = text.charAt(i);
     if (st == "ws") {
       if (!Character.isWhitespace(c)) st = "word";
       else i++;
     } else if (st == "word") {
       if (c == '"') {
         st = "quote";
         i++;
       } else if (c == '\\') {
         st = "squote";
         i++;
       } else if (Character.isWhitespace(c)) {
         words.add(buf.toString());
         buf = new StringBuilder();
         st = "ws";
       } else {
         buf.append(c);
         i++;
       }
     } else if (st == "quote") {
       if (c == '"') {
         st = "word";
         i++;
       } else if (c == '\\') {
         st = "sqquote";
         i++;
       } else {
         buf.append(c);
         i++;
       }
     } else if (st == "squote") {
       buf.append(c);
       i++;
       st = "word";
     } else if (st == "sqquote") {
       buf.append(c);
       i++;
       st = "quote";
     }
   }
   if (st == "word") words.add(buf.toString());
   if ((st != "ws") && (st != "word")) return (null);
   return (words.toArray(new String[0]));
 }
示例#7
0
 /** Set the text of an XML element, safely encode it if needed. */
 @NotNull
 public static Element setSafeXmlText(@NotNull Element element, @NotNull String text) {
   final Character first = firstCharacter(text);
   final Character last = lastCharacter(text);
   if (!StringHelper.isXmlCharacterData(text)
       || first != null && Character.isWhitespace(first)
       || last != null && Character.isWhitespace(last)) {
     element.setAttribute("encoding", "base64");
     final String encoded = new String(Base64.encodeBase64(text.getBytes()));
     element.setText(encoded);
   } else {
     element.setText(text);
   }
   return element;
 }
示例#8
0
    // get a list of whitespace separated classnames from a property.
    private String[] parseClassNames(String propertyName) {
	String hands = getProperty(propertyName);
	if (hands == null) {
	    return new String[0];
	}
	hands = hands.trim();
	int ix = 0;
	Vector result = new Vector();
	while (ix < hands.length()) {
	    int end = ix;
	    while (end < hands.length()) {
		if (Character.isWhitespace(hands.charAt(end))) {
		    break;
		}
		if (hands.charAt(end) == ',') {
		    break;
		}
		end++;
	    }
	    String word = hands.substring(ix, end);
	    ix = end+1;
	    word = word.trim();
	    if (word.length() == 0) {
		continue;
	    }
	    result.add(word);
	}
	return (String[]) result.toArray(new String[result.size()]);
    }
 /**
  * Returns a cyclified string representation of the given <tt>Object</tt>. Embedded constants are
  * prefixed with "#$".
  *
  * @return a <tt>String</tt> representation in cyclified form.
  */
 public static String cyclify(Object obj) {
   if (obj == null) {
     throw new BaseClientRuntimeException("Cannot cyclify null obj");
   } else if (!isCycLObject(obj)) {
     throw new BaseClientRuntimeException(
         "Cannot cyclify: '" + obj + "' (" + obj.getClass().getName() + ").");
   }
   if (obj instanceof CycObject) {
     return ((CycObject) obj).cyclify();
   }
   if (obj instanceof String) {
     return "\"" + (String) obj + "\"";
   }
   if (obj instanceof Character) {
     // @hack -- do better job of this. Need to support other non-printable characters!!!
     Character theChar = (Character) obj;
     if (theChar == ' ') {
       return "#\\Space";
     } else if (theChar == '\n') {
       return "#\\Newline";
     } else if (theChar == '\r') {
       return "#\\Return";
     } else if (theChar == '\t') {
       return "#\\Tab";
     }
     if (Character.isWhitespace(theChar)) {
       throw new IllegalArgumentException(
           "Don't know how to trasmit the whitespace character: " + (int) theChar.charValue());
     }
     return "#\\" + obj;
   }
   return obj.toString();
 }
示例#10
0
 public static int makestring(String a, Token b) {
   char[] temp = new char[a.length()];
   temp = a.toCharArray();
   int i = 1;
   if (temp[0] == '\'') {
     while (Character.isLetter(temp[i])
         || Character.isDigit(temp[i])
         || isoperator(temp[i])
         || ispunc(temp[i])
         || Character.isWhitespace(temp[i])) {
       i++;
       if (temp[i - 1] == '\'') {
         setToken(b, i - 2, a.substring(1, i - 1), LexToInt.string);
         return i;
       }
       if (i == a.length()) {
         break;
       }
     }
     if (temp[i - 1] == '\'') {
       setToken(b, i - 2, a.substring(1, i - 1), LexToInt.string);
       return i;
     }
   }
   return -1;
 }
示例#11
0
  String cleanupSource(String source) {
    if (source.isEmpty()) {
      return source.concat("\n");
    }

    int lastChIdx = source.length() - 1;
    if (source.charAt(lastChIdx) != '\n') {
      // Append a newline at the end
      source = source.concat("\n");
    } else {
      // Remove all newlines at the end but one
      while (lastChIdx >= 1) {
        Character ch1 = source.charAt(lastChIdx);
        if (ch1 == '\n' || Character.isWhitespace(ch1)) {
          source = source.substring(0, lastChIdx--);
        } else {
          break;
        }
      }

      source = source.concat("\n");
    }

    return source;
  }
示例#12
0
 /** Receive notification of character data inside an element. */
 @Override
 public void characters(char ch[], int start, int len) {
   while (len > 0 && Character.isWhitespace(ch[start])) {
     ++start;
     --len;
   }
   while (len > 0 && Character.isWhitespace(ch[start + len - 1])) {
     --len;
   }
   if (len > 0) {
     if (_chars.length() > 0) {
       _chars.append(' ');
     }
     _chars.append(ch, start, len);
   }
 }
示例#13
0
 String[] getArgNames(JNIMethod method) {
   int n_args = method.getParameters().size();
   if (n_args == 0) return new String[0];
   String name = method.getName();
   String params = "";
   int index = 0;
   while (true) {
     index = classSource.indexOf(name, index + 1);
     if (!Character.isWhitespace(classSource.charAt(index - 1))) continue;
     if (index == -1) return null;
     int parantesesStart = classSource.indexOf("(", index);
     if (classSource.substring(index + name.length(), parantesesStart).trim().length() == 0) {
       int parantesesEnd = classSource.indexOf(")", parantesesStart);
       params = classSource.substring(parantesesStart + 1, parantesesEnd);
       break;
     }
   }
   String[] names = new String[n_args];
   StringTokenizer tk = new StringTokenizer(params, ",");
   for (int i = 0; i < names.length; i++) {
     String s = tk.nextToken().trim();
     StringTokenizer tk1 = new StringTokenizer(s, " ");
     String s1 = null;
     while (tk1.hasMoreTokens()) {
       s1 = tk1.nextToken();
     }
     names[i] = s1.trim();
   }
   return names;
 }
示例#14
0
 /**
  * @ensures: if input file is read, a String is filled with words from file and searched in
  *     dictionary list, and if found increase words found counter, otherwise increase words not
  *     found. Otherwise error reading file
  */
 public void readFileOliver() {
   try {
     FileInputStream inf = new FileInputStream(new File("oliver.txt"));
     char let;
     String str = "";
     String key = "";
     int n = 0;
     while ((n = inf.read()) != -1) {
       let = (char) n;
       if (Character.isLetter(let)) {
         str += Character.toLowerCase(let);
       }
       if ((Character.isWhitespace(let) || let == '-') && !str.isEmpty()) {
         key = str;
         str = "";
         boolean a = dictionary[(int) key.charAt(0) - 97].contains(key);
         if (a == true) {
           counter = dictionary[(int) key.charAt(0) - 97].indexOf(key);
           counterWFound++;
           counterWFCompared += counter;
         } else {
           counter =
               dictionary[(int) key.charAt(0) - 97].indexOf(
                   dictionary[(int) key.charAt(0) - 97].getLast());
           counterWNotFound++;
           counterWNFCompared += counter;
         }
       }
     }
     inf.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /**
   * Called to parse a double or single quote string.
   *
   * @return The string parsed.
   * @throws IOException If an I/O exception occurs.
   */
  protected String parseString() throws IOException {
    StringBuilder result = new StringBuilder();
    eatWhitespace();
    if ("\"\'".indexOf(this.source.peek()) != -1) {
      int delim = this.source.read();
      while ((this.source.peek() != delim) && (this.source.peek() != -1)) {
        if (result.length() > 1000) {
          break;
        }
        int ch = parseSpecialCharacter();
        if ((ch == 13) || (ch == 10)) {
          continue;
        }
        result.append((char) ch);
      }
      if ("\"\'".indexOf(this.source.peek()) != -1) {
        this.source.read();
      }
    } else {
      while (!Character.isWhitespace(this.source.peek())
          && (this.source.peek() != -1)
          && (this.source.peek() != '>')) {
        result.append(parseSpecialCharacter());
      }
    }

    return result.toString();
  }
示例#16
0
  public static String getRequiredReplName(String text) {
    if (text == null) {
      return null;
    }

    String trimmed = text.trim();
    if (!trimmed.startsWith("%")) {
      return null;
    }

    // get script head
    int scriptHeadIndex = 0;
    for (int i = 0; i < trimmed.length(); i++) {
      char ch = trimmed.charAt(i);
      if (Character.isWhitespace(ch) || ch == '(' || ch == '\n') {
        break;
      }
      scriptHeadIndex = i;
    }
    if (scriptHeadIndex < 1) {
      return null;
    }
    String head = text.substring(1, scriptHeadIndex + 1);
    return head;
  }
  /**
   * Parse any special characters(i.e. &nbsp);
   *
   * @return The character that was parsed.
   * @throws IOException If a read error occurs
   */
  private char parseSpecialCharacter() throws IOException {
    char result = (char) this.source.read();
    int advanceBy = 0;

    // is there a special character?
    if (result == '&') {
      int ch = 0;
      StringBuilder buffer = new StringBuilder();

      // loop through and read special character
      do {
        ch = this.source.peek(advanceBy++);
        if ((ch != '&') && (ch != ';') && !Character.isWhitespace(ch)) {
          buffer.append((char) ch);
        }

      } while ((ch != ';') && (ch != -1) && !Character.isWhitespace(ch));

      String b = buffer.toString().trim().toLowerCase();

      // did we find a special character?
      if (b.length() > 0) {
        if (b.charAt(0) == '#') {
          try {
            result = (char) Integer.parseInt(b.substring(1));
          } catch (NumberFormatException e) {
            advanceBy = 0;
          }
        } else {
          if (charMap.containsKey(b)) {
            result = charMap.get(b);
          } else {
            advanceBy = 0;
          }
        }
      } else {
        advanceBy = 0;
      }
    }

    while (advanceBy > 0) {
      read();
      advanceBy--;
    }

    return result;
  }
 private static boolean hasWhitespace(String string) {
   int length = string.length();
   for (int i = 0; i < length; i++) {
     if (Character.isWhitespace(string.charAt(i))) {
       return true;
     }
   }
   return false;
 }
示例#19
0
 public static int[] findspaces(String text) {
   java.util.List<Integer> l = new ArrayList<Integer>();
   for (int i = 0; i < text.length(); i++) {
     char c = text.charAt(i);
     if (Character.isWhitespace(c)) l.add(i);
   }
   int[] ret = new int[l.size()];
   for (int i = 0; i < ret.length; i++) ret[i] = l.get(i);
   return (ret);
 }
 private static int getNewIndent(final PsiFile psiFile, final int firstWhitespace) {
   final Document document = psiFile.getViewProvider().getDocument();
   final int startOffset = document.getLineStartOffset(document.getLineNumber(firstWhitespace));
   int endOffset = startOffset;
   final CharSequence charsSequence = document.getCharsSequence();
   while (Character.isWhitespace(charsSequence.charAt(endOffset++))) ;
   final String newIndentStr = charsSequence.subSequence(startOffset, endOffset - 1).toString();
   return IndentHelperImpl.getIndent(
       psiFile.getProject(), psiFile.getFileType(), newIndentStr, true);
 }
  /**
   * Check to see if the ending tag is present.
   *
   * @param name The type of end tag being saught.
   * @return True if the ending tag was found.
   * @throws IOException Thrown if an IO error occurs.
   */
  private boolean peekEndTag(String name) throws IOException {
    int i = 0;

    // pass any whitespace
    while ((this.source.peek(i) != -1) && Character.isWhitespace(this.source.peek(i))) {
      i++;
    }

    // is a tag beginning
    if (this.source.peek(i) != '<') {
      return false;
    } else {
      i++;
    }

    // pass any whitespace
    while ((this.source.peek(i) != -1) && Character.isWhitespace(this.source.peek(i))) {
      i++;
    }

    // is it an end tag
    if (this.source.peek(i) != '/') {
      return false;
    } else {
      i++;
    }

    // pass any whitespace
    while ((this.source.peek(i) != -1) && Character.isWhitespace(this.source.peek(i))) {
      i++;
    }

    // does the name match
    for (int j = 0; j < name.length(); j++) {
      if (Character.toLowerCase(this.source.peek(i)) != Character.toLowerCase(name.charAt(j))) {
        return false;
      }
      i++;
    }

    return true;
  }
示例#22
0
 public static int makespace(String a, Token b) {
   char[] temp = new char[a.length()];
   temp = a.toCharArray();
   int i = 0;
   if (a.isEmpty()) {
     setToken(b, a.length(), "\n", LexToInt.delete);
     return a.length();
   }
   if (Character.isWhitespace(temp[i])) {
     while (Character.isWhitespace(temp[i])) {
       i++;
       if (i == a.length()) {
         break;
       }
     }
     setToken(b, i, a.substring(0, i), LexToInt.delete);
     return i;
   }
   return -1;
 }
示例#23
0
 /**
  * True if all the elements in the current node are blanks
  *
  * @return true if all are blanks
  * @throws javax.xml.stream.XMLStreamException
  */
 private boolean allBlanks() throws XMLStreamException {
   boolean res = true;
   if (!reader.hasText()) {
     return true;
   }
   String text = reader.getText();
   for (int i = 0, limit = text.length(); i < limit; i++) {
     res = res && Character.isWhitespace(text.charAt(i));
   }
   return res;
 }
示例#24
0
文件: Master.java 项目: lemmy/dnsjava
 private static String stripTrailing(String s) {
   if (s == null) return null;
   int lastChar;
   int semi;
   if ((semi = s.lastIndexOf(';')) < 0) lastChar = s.length() - 1;
   else lastChar = semi - 1;
   for (int i = lastChar; i >= 0; i--) {
     if (!Character.isWhitespace(s.charAt(i))) return s.substring(0, i + 1);
   }
   return "";
 }
示例#25
0
  private static void autoImport(
      @NotNull final PsiFile file, int offset, @NotNull final Editor editor) {
    final CharSequence text = editor.getDocument().getCharsSequence();
    while (offset > 0 && Character.isJavaIdentifierPart(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0 || text.charAt(offset) != '.') return;

    offset--;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    autoImportReference(
        file,
        editor,
        extractReference(
            PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiExpression.class, false)));
  }
 /**
  * Check whether the given String has actual text. More specifically, returns <code>true</code> if
  * the string not <code>null</code>, its length is greater than 0, and it contains at least one
  * non-whitespace character.
  *
  * <p><code>StringUtils.hasText(null) == false<br/>
  * StringUtils.hasText("") == false<br/>
  * StringUtils.hasText(" ") == false<br/>
  * StringUtils.hasText("12345") == true<br/>
  * StringUtils.hasText(" 12345 ") == true</code>
  *
  * <p>
  *
  * <p>Copied from the Spring Framework while retaining all license, copyright and author
  * information.
  *
  * @param str the String to check (may be <code>null</code>)
  * @return <code>true</code> if the String is not <code>null</code>, its length is greater than 0,
  *     and it does not contain whitespace only
  * @see java.lang.Character#isWhitespace
  */
 public static boolean hasText(String str) {
   if (!hasLength(str)) {
     return false;
   }
   int strLen = str.length();
   for (int i = 0; i < strLen; i++) {
     if (!Character.isWhitespace(str.charAt(i))) {
       return true;
     }
   }
   return false;
 }
示例#27
0
 /**
  * Check whether the given CharSequence contains any whitespace characters.
  *
  * @param str the CharSequence to check (may be {@code null})
  * @return {@code true} if the CharSequence is not empty and contains at least 1 whitespace
  *     character
  * @see Character#isWhitespace
  */
 public static boolean containsWhitespace(CharSequence str) {
   if (!hasLength(str)) {
     return false;
   }
   int strLen = str.length();
   for (int i = 0; i < strLen; i++) {
     if (Character.isWhitespace(str.charAt(i))) {
       return true;
     }
   }
   return false;
 }
示例#28
0
  private static String a(String value, int pos) throws RuntimeException {
    LinkedList<Character> chars = new LinkedList<Character>();
    int currentPos = pos + 1;
    boolean flagQuote = false;
    boolean var5 = false;
    boolean var6 = false;

    for (int i = 0; currentPos < value.length(); ++currentPos) {
      char c = value.charAt(currentPos);
      if (c == '"') {
        if (b(value, currentPos)) {
          if (!flagQuote) {
            throw new RuntimeException("Illegal use of \\\": " + value);
          }
        } else {
          flagQuote = !flagQuote;
          if (flagQuote && !var6) {
            var5 = true;
          }

          if (!flagQuote) {
            i = currentPos;
          }
        }
      } else if (!flagQuote) {
        if (c != '{' && c != '[') {
          if (c == '}' && (chars.isEmpty() || chars.pop() != 123)) {
            throw new RuntimeException("Unbalanced curly brackets {}: " + value);
          }

          if (c == ']' && (chars.isEmpty() || chars.pop() != 91)) {
            throw new RuntimeException("Unbalanced square brackets []: " + value);
          }

          if (c == ',' && chars.isEmpty()) {
            return value.substring(0, currentPos);
          }
        } else {
          chars.push(c);
        }
      }

      if (!Character.isWhitespace(c)) {
        if (!flagQuote && var5 && i != currentPos) {
          return value.substring(0, i + 1);
        }

        var6 = true;
      }
    }

    return value.substring(0, currentPos);
  }
    boolean skipSpaces() {
      int _c;

      do {
        _c = getNext();
        if (_c == Integer.MIN_VALUE) {
          return false;
        }
      } while (Character.isWhitespace((char) _c));

      this.idx--;

      return true;
    }
示例#30
0
 /**
  * Trim <i>all</i> whitespace from the given String: leading, trailing, and in between characters.
  *
  * @param str the String to check
  * @return the trimmed String
  * @see Character#isWhitespace
  */
 public static String trimAllWhitespace(String str) {
   if (!hasLength(str)) {
     return str;
   }
   int len = str.length();
   StringBuilder sb = new StringBuilder(str.length());
   for (int i = 0; i < len; i++) {
     char c = str.charAt(i);
     if (!Character.isWhitespace(c)) {
       sb.append(c);
     }
   }
   return sb.toString();
 }