// FIXME cosmically ineffective not to implemente the other write methods.
 @Override
 public void write(int b) throws IOException {
   this.buffer.append((char) b);
   String s = buffer.toString();
   // This next line is an optimisation. Only convert the whole buffer to string
   // if the most recent character might be the end of the line separator.
   if ((lineSeparator.indexOf(b) != -1) && s.contains(lineSeparator)) {
     s = prefix + "'" + s + "'";
     switch (loggingLevel) {
       case TRACE:
         logger.trace(s);
         break;
       case DEBUG:
         logger.debug(s);
         break;
       case INFO:
         logger.info(s);
         break;
       case WARN:
         logger.warn(s);
         break;
       case ERROR:
         logger.error(s);
         break;
     }
     buffer.setLength(0);
   }
 }
  /*
   * A '{' has been read. Process a block tag
   */
  private String processBlockTag() throws IOException {

    int c = nextChar();

    if (c != '@') {
      StringBuffer buffer = new StringBuffer();
      buffer.append('{');
      buffer.append((char) c);
      return buffer.toString();
    }

    StringBuffer buffer = new StringBuffer();
    if (c != -1) {

      buffer.setLength(0);
      buffer.append((char) c);

      c = getTag(buffer);
      String tag = buffer.toString();

      buffer.setLength(0);
      if (c != -1 && c != '}') {
        buffer.append((char) c);
        c = getContent(buffer, '}');
      }

      return printBlockTag(tag, buffer.toString());
    }

    return null;
  }
  /*
   * A '@' has been read. Process a javadoc tag
   */
  private String processSimpleTag() throws IOException {

    fParameters = new ArrayList<String>();
    fExceptions = new ArrayList<String>();
    fAuthors = new ArrayList<String>();
    fSees = new ArrayList<String>();
    fSince = new ArrayList<String>();
    fRest = new ArrayList<Pair>();

    StringBuffer buffer = new StringBuffer();
    int c = '@';
    while (c != -1) {

      buffer.setLength(0);
      buffer.append((char) c);
      c = getTag(buffer);
      String tag = buffer.toString();

      buffer.setLength(0);
      if (c != -1) {
        // e.g. @SuppressWarnings(...) case
        if (!Character.isWhitespace(c)) {
          buffer.append((char) c);
        }
        c = getContentUntilNextTag(buffer);
      }

      handleTag(tag, buffer.toString());
    }

    return printSimpleTag();
  }
  public void endElement(java.lang.String uri, java.lang.String localName, java.lang.String qName)
      throws SAXException {

    try {
      if (qName.equals("p") || qName.equals("description")) {
        writer.write(getText());
        accumulator.setLength(0);
      }

      if (qName.equals("description")) {
        counting = false;
      }

      if (!counting) {
        writer.write(getText());
        accumulator.setLength(0);
        writer.write("</" + qName + ">\n");
      } else {
        if (qName.equals("row")) {
          accumulator.append(" ");
        }
        if (qName.equals("p")) {
          writer.write("\n");
          accumulator.append(" ");
        }
      }
    } catch (Exception e) {
      //		    e.printStackTrace();
      throw new GrobidException("An exception occured while running Grobid.", e);
    }
  }
Beispiel #5
0
  /**
   * Reads a string
   *
   * <pre>
   * &lt;string>value&lt;/string>
   * </pre>
   */
  public String readString() throws IOException {
    int tag = parseTag();

    String value;

    switch (tag) {
      case TAG_NULL:
        expectTag(TAG_NULL_END);
        return null;

      case TAG_STRING:
        _sbuf.setLength(0);
        value = parseString(_sbuf).toString();
        expectTag(TAG_STRING_END);
        return value;

      case TAG_XML:
        _sbuf.setLength(0);
        value = parseString(_sbuf).toString();
        expectTag(TAG_XML_END);
        return value;

      default:
        throw expectedTag("string", tag);
    }
  }
 private void setup() {
   StringBuffer buf = new StringBuffer(100);
   buf.append("SELECT ");
   StringBuffer whereBuf = new StringBuffer(100);
   whereBuf.append(" WHERE");
   List primaryKeyList = new ArrayList();
   for (int i = 0; i < table.getColumnSize(); ++i) {
     DataColumn column = table.getColumn(i);
     buf.append(column.getColumnName());
     buf.append(", ");
     if (column.isPrimaryKey()) {
       whereBuf.append(" ");
       whereBuf.append(column.getColumnName());
       whereBuf.append(" = ? AND");
       primaryKeyList.add(column.getColumnName());
     }
   }
   buf.setLength(buf.length() - 2);
   whereBuf.setLength(whereBuf.length() - 4);
   buf.append(" FROM ");
   buf.append(table.getTableName());
   buf.append(whereBuf);
   sql = buf.toString();
   primaryKeys = (String[]) primaryKeyList.toArray(new String[primaryKeyList.size()]);
 }
Beispiel #7
0
  /**
   * 252ms
   *
   * @param n
   * @return
   */
  public String countAndSay(int n) {
    StringBuffer sbBuffer = new StringBuffer("1");
    if (n == 1) {
      return sbBuffer.toString();
    }

    int ret = 1;
    StringBuffer retStringBuffer = new StringBuffer();
    while (true) {
      for (int i = 0; i < sbBuffer.length(); ) {
        char t = sbBuffer.charAt(i);
        int k = 0;
        while (i + k < sbBuffer.length() && sbBuffer.charAt(i + k) == t) {
          k++;
        }
        i = i + k;
        retStringBuffer.append(String.valueOf(k));
        retStringBuffer.append(t);
      }

      ret++;
      if (ret == n) {
        return retStringBuffer.toString();
      }
      sbBuffer.setLength(0);
      sbBuffer.append(retStringBuffer);
      retStringBuffer.setLength(0);
    }
  }
  /**
   * Converts the given format into a pattern accepted by <code>java.text.SimpleDataFormat</code>
   *
   * @param format
   */
  public static String toJavaDatePattern(String format) {

    int len = format.length();
    char ch;
    StringBuffer sb = new StringBuffer(len);
    Tokenizer tokenizer = new Tokenizer();

    for (int i = 0; i <= len; i++) {
      ch = (i == len) ? e : format.charAt(i);

      if (!tokenizer.next(ch, dateTokens)) {
        int index = tokenizer.getLastMatch();

        if (index >= 0) {
          sb.setLength(sb.length() - tokenizer.length());
          sb.append(javaDateTokens[index]);
        }

        tokenizer.reset();

        if (tokenizer.isConsumed()) {
          continue;
        }
      }

      sb.append(ch);
    }

    sb.setLength(sb.length() - 1);

    String javaPattern = sb.toString();

    return javaPattern;
  }
  private void finishComposition() {
    int len = buffer.length();
    if (len == 6 && format != SPECIAL_ESCAPE) {
      char codePoint = (char) getCodePoint(buffer, 2, 5);
      if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
        buffer.setLength(0);
        buffer.append(codePoint);
        sendCommittedText();
        return;
      }
    } else if (len == 8 && format == SPECIAL_ESCAPE) {
      int codePoint = getCodePoint(buffer, 2, 7);
      if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
        buffer.setLength(0);
        buffer.appendCodePoint(codePoint);
        sendCommittedText();
        return;
      }
    } else if (len == 12 && format == SURROGATE_PAIR) {
      char[] codePoint = {(char) getCodePoint(buffer, 2, 5), (char) getCodePoint(buffer, 8, 11)};
      if (Character.isHighSurrogate(codePoint[0]) && Character.isLowSurrogate(codePoint[1])) {
        buffer.setLength(0);
        buffer.append(codePoint);
        sendCommittedText();
        return;
      }
    }

    beep();
  }
  public void init(String record) {
    String[] fields = record.split("\\" + String.valueOf(this.delimiter));
    StringBuffer uuidStringBuffer = new StringBuffer();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

    if (fields[0].replace(String.valueOf(this.enclosure), "").equals("")) {
      uuidStringBuffer.setLength(0);
      this.opportunityid = null;
    } else {
      uuidStringBuffer.setLength(0);
      uuidStringBuffer.append(fields[0].replace(String.valueOf(this.enclosure), ""));
      uuidStringBuffer.insert(8, '-');
      uuidStringBuffer.insert(13, '-');
      uuidStringBuffer.insert(18, '-');
      uuidStringBuffer.insert(23, '-');
      this.opportunityid = UUID.fromString(uuidStringBuffer.toString());
    }

    if (fields[1].replace(String.valueOf(this.enclosure), "").equals("")) {
      uuidStringBuffer.setLength(0);
      this.lookupid = null;
    } else {
      uuidStringBuffer.setLength(0);
      uuidStringBuffer.append(fields[1].replace(String.valueOf(this.enclosure), ""));
      uuidStringBuffer.insert(8, '-');
      uuidStringBuffer.insert(13, '-');
      uuidStringBuffer.insert(18, '-');
      uuidStringBuffer.insert(23, '-');
      this.lookupid = UUID.fromString(uuidStringBuffer.toString());
    }
  }
Beispiel #11
0
  @Override
  public void publish(LogRecord record) {
    if (record.getLevel().intValue() < getLevel().intValue()) {
      return;
    }
    if (IL.isInternalLog()) {
      return;
    }
    Runnable off = internalLog();
    try {
      StringBuffer sb = NbModuleLogHandler.toString(record);
      PrintStream ps = getLog();
      if (ps != null) {
        try {
          ps.println(sb.toString());
        } catch (LinkageError err) {
          // prevent circular references
        }
      }

      if (messages.length() + sb.length() > 20000) {
        if (sb.length() > 20000) {
          messages.setLength(0);
          sb.delete(0, sb.length() - 20000);
        } else {
          messages.setLength(20000 - sb.length());
        }
      }

      messages.append(sb.toString());
    } finally {
      off.run();
    }
  }
  @Test
  public void testTestingProgressIndicator() throws Exception {
    TestSystem fitMock = mock(TestSystem.class);
    when(fitMock.getName()).thenReturn("Fit:laughing.fit");

    formatter.testSystemStarted(fitMock);
    formatter.announceNumberTestsToRun(20);
    formatter.announceStartNewTest("RelativeName", "FullName");

    assertSubString(
        "<script>document.getElementById(\"test-summary\").innerHTML ="
            + " \"<div id=\\\"progressBar\\\" class=\\\"pass\\\" style=\\\"width:0.0%\\\">",
        pageBuffer.toString());
    assertSubString("Running&nbsp;tests&nbsp;...&nbsp;(1/20)", pageBuffer.toString());
    pageBuffer.setLength(0);

    formatter.processTestResults("RelativeName", new TestSummary(1, 0, 0, 0));
    formatter.announceStartNewTest("RelativeName", "FullName");

    assertSubString(
        "<script>document.getElementById(\"test-summary\").innerHTML ="
            + " \"<div id=\\\"progressBar\\\" class=\\\"pass\\\" style=\\\"width:5.0%\\\">",
        pageBuffer.toString());
    assertSubString("(2/20)", pageBuffer.toString());
    pageBuffer.setLength(0);

    formatter.processTestResults("RelativeName", new TestSummary(1, 0, 0, 0));
    formatter.announceStartNewTest("RelativeName", "FullName");

    assertSubString(
        "<script>document.getElementById(\"test-summary\").innerHTML ="
            + " \"<div id=\\\"progressBar\\\" class=\\\"pass\\\" style=\\\"width:10.0%\\\">",
        pageBuffer.toString());
    assertSubString("(3/20)", pageBuffer.toString());
  }
Beispiel #13
0
 /** Reads data from the udev monitor. Blocks until data is available */
 private Map<String, String> readEvent() throws IOException {
   Map<String, String> map = new HashMap<>();
   ByteBuffer b;
   synchronized (this) {
     b = buffer;
     if (b == null) {
       return map;
     }
   }
   int length = _readEvent(fd, b);
   synchronized (this) {
     if (buffer == null) {
       return map;
     }
     int propertiesOffset = _getPropertiesOffset(buffer);
     int propertiesLength = _getPropertiesLength(buffer);
     int propertiesEnd = propertiesOffset + propertiesLength;
     if (length < propertiesEnd) {
       throw new IOException("Mismatched property segment length");
     }
     buffer.position(propertiesOffset);
     // Data read from the udev monitor is in the form of a list of
     // lines separated by null bytes.
     // Each line defines a key/value pair, with the
     // format: <key>=<value><null terminator>
     StringBuffer key = new StringBuffer();
     StringBuffer value = new StringBuffer();
     nextKey:
     while (buffer.position() < propertiesEnd) {
       key.setLength(0);
       value.setLength(0);
       boolean readKey = false;
       while (buffer.position() < length && !readKey) {
         char ch = (char) buffer.get();
         switch (ch) {
           case '\000': // no value on this line
             map.put(key.toString(), "");
             continue nextKey;
           case '=':
             readKey = true;
             break;
           default:
             key.append(ch);
         }
       }
       while (buffer.position() < propertiesEnd) {
         char ch = (char) buffer.get();
         switch (ch) {
           case '\000':
             map.put(key.toString(), value.toString());
             continue nextKey;
           default:
             value.append(ch);
         }
       }
     }
     buffer.clear();
   }
   return map;
 }
  // parses a canonical form of correlation key set through an automata subsystem(FSM)
  private void parseCanonicalForm(String canonicalForm) {
    ParserState state = ParserState.INITIAL;

    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < canonicalForm.length(); i++) {
      char ch = canonicalForm.charAt(i);
      if (state == ParserState.INITIAL) {
        if (ch == '@') {
          state = ParserState.MET_ALPHA;
        } else {
          buf.append(ch);
          state = ParserState.MET_LEFT_BRACKET;
        }
      } else if (state == ParserState.MET_ALPHA) {
        if (ch == '[') {
          version = buf.toString();
          buf.setLength(0);
          state = ParserState.MET_LEFT_BRACKET;
        } else {
          buf.append(ch);
        }
      } else if (state == ParserState.MET_LEFT_BRACKET) {
        if (ch == ']') {
          state = ParserState.MET_RIGHT_BRACKET;
        } else {
          buf.append(ch);
        }
      } else if (state == ParserState.MET_RIGHT_BRACKET) {
        if (ch == ']') {
          buf.append(ch);
          state = ParserState.MET_LEFT_BRACKET;
        } else if (ch == ',') {
          if (buf.toString().trim().length() != 0) {
            add(new CorrelationKey(buf.toString()));
          }
          buf.setLength(0);
          state = ParserState.MET_COMMA;
        } else if (ch == '?') { // this is only a convenient feature for testing
          if (buf.toString().trim().length() != 0) {
            add(new OptionalCorrelationKey(buf.toString()));
          }
          buf.setLength(0);
          state = ParserState.MET_COMMA;
        }
      } else if (state == ParserState.MET_COMMA) {
        if (ch == '[') {
          state = ParserState.MET_LEFT_BRACKET;
        }
      }
    }
    if (buf.toString().trim().length() != 0) {
      if (state == ParserState.MET_ALPHA) {
        version = buf.toString();
      } else {
        add(new CorrelationKey(buf.toString()));
      }
    }
  }
 /**
  * Process the text so that it will render with a combination of fonts if needed.
  *
  * @param text the text
  * @return a <CODE>Phrase</CODE> with one or more chunks
  */
 public Phrase process(String text) {
   int fsize = fonts.size();
   if (fsize == 0) throw new IndexOutOfBoundsException("No font is defined.");
   char cc[] = text.toCharArray();
   int len = cc.length;
   StringBuffer sb = new StringBuffer();
   Font font = null;
   int lastidx = -1;
   Phrase ret = new Phrase();
   for (int k = 0; k < len; ++k) {
     char c = cc[k];
     if (c == '\n' || c == '\r') {
       sb.append(c);
       continue;
     }
     if (Utilities.isSurrogatePair(cc, k)) {
       int u = Utilities.convertToUtf32(cc, k);
       for (int f = 0; f < fsize; ++f) {
         font = (Font) fonts.get(f);
         if (font.getBaseFont().charExists(u)) {
           if (lastidx != f) {
             if (sb.length() > 0 && lastidx != -1) {
               Chunk ck = new Chunk(sb.toString(), (Font) fonts.get(lastidx));
               ret.add(ck);
               sb.setLength(0);
             }
             lastidx = f;
           }
           sb.append(c);
           sb.append(cc[++k]);
           break;
         }
       }
     } else {
       for (int f = 0; f < fsize; ++f) {
         font = (Font) fonts.get(f);
         if (font.getBaseFont().charExists(c)) {
           if (lastidx != f) {
             if (sb.length() > 0 && lastidx != -1) {
               Chunk ck = new Chunk(sb.toString(), (Font) fonts.get(lastidx));
               ret.add(ck);
               sb.setLength(0);
             }
             lastidx = f;
           }
           sb.append(c);
           break;
         }
       }
     }
   }
   if (sb.length() > 0) {
     Chunk ck = new Chunk(sb.toString(), (Font) fonts.get(lastidx == -1 ? 0 : lastidx));
     ret.add(ck);
   }
   return ret;
 }
  // 得到的tokens包含源代码的由词法分析器分析出的所有单词,但不包含注释
  private static ArrayList<JavaScriptToken> parse(
      Reader in, ErrorReporter reporter) // 返回tokens(保存的是源文件中出现的javascript关键字和NAME,REGEXP,STRING等类型)
      throws IOException, EvaluatorException {

    CompilerEnvirons env = new CompilerEnvirons(); // 创建编译环境对象
    env.setLanguageVersion(Context.VERSION_1_7); // 设置语言版本
    Parser parser = new Parser(env, reporter); // 创建解释器对象
    parser.parse(in, null, 1); // 解释输入流
    String source = parser.getEncodedSource(); // 获得已编码的源码(词法分析阶段通常是把从源程序中识别出的各个单词的词文
    // 转换为某种内部表示
    int offset = 0;
    int length = source.length();
    ArrayList<JavaScriptToken> tokens = new ArrayList<JavaScriptToken>();
    StringBuffer sb = new StringBuffer();

    while (offset < length) {
      int tt = source.charAt(offset++); // 获取特定位置上的字符,并转化为ASCII编码
      switch (tt) {
        case Token.CONDCOMMENT: // 条件注释
        case Token.KEEPCOMMENT: // 注释
        case Token.NAME: //
        case Token.REGEXP: // 正则表达式类型
        case Token.STRING: // String类型,js程序中双引号或单引号括起来的字符串
          sb.setLength(0);
          offset = printSourceString(source, offset, sb);
          tokens.add(new JavaScriptToken(tt, sb.toString()));
          break;

        case Token.NUMBER: // Number类型
          sb.setLength(0);
          offset = printSourceNumber(source, offset, sb);
          tokens.add(new JavaScriptToken(tt, sb.toString()));
          break;

        default:
          String literal = literals.get(new Integer(tt));
          if (literal != null) { // 若不为空,说明哈希表literals中含有键new
            // Integer(tt)所对应的值
            tokens.add(new JavaScriptToken(tt, literal)); // 将此关键字保存到数组列表tokens中
          }
          break;
      }
    }

    /*
     * //begin Iterator<JavaScriptToken> iterator = tokens.iterator();
     * JavaScriptToken token; while(iterator.hasNext()) { token =
     * iterator.next();
     * System.out.println(token.getType()+"\t"+token.getValue()); } //end
     */
    return tokens;
  }
Beispiel #17
0
  /**
   * Parses identifiers until <code>extraChar</code> is encountered, returning the ending token,
   * which will be IDENTIFIER if extraChar is found.
   */
  private int parseIdentifiers(char extraChar, boolean wantsBlocks) throws IOException {
    int nextToken;
    int ubl;

    unitBuffer.setLength(0);
    for (; ; ) {
      nextToken = nextToken(extraChar);

      switch (nextToken) {
        case IDENTIFIER:
          if (tokenBufferLength > 0) {
            if (tokenBuffer[tokenBufferLength - 1] == extraChar) {
              if (--tokenBufferLength > 0) {
                if (readWS && unitBuffer.length() > 0) {
                  unitBuffer.append(' ');
                }
                unitBuffer.append(tokenBuffer, 0, tokenBufferLength);
              }
              return IDENTIFIER;
            }
            if (readWS && unitBuffer.length() > 0) {
              unitBuffer.append(' ');
            }
            unitBuffer.append(tokenBuffer, 0, tokenBufferLength);
          }
          break;

        case BRACKET_OPEN:
        case BRACE_OPEN:
        case PAREN_OPEN:
          ubl = unitBuffer.length();
          if (wantsBlocks) {
            unitBuffer.append(charMapping[nextToken]);
          }
          parseTillClosed(nextToken);
          if (!wantsBlocks) {
            unitBuffer.setLength(ubl);
          }
          break;

        case BRACE_CLOSE:
          // No need to throw for these two, we return token and
          // caller can do whatever.
        case BRACKET_CLOSE:
        case PAREN_CLOSE:
        case END:
          // Hit the end
          return nextToken;
      }
    }
  }
 public void rerunTest(String testId, String className, String testName) {
   if (isRunning()) {
     fActualResult.setLength(0);
     fExpectedResult.setLength(0);
     fWriter.println(
         MessageIds.TEST_RERUN
             + testId
             + " "
             + className
             + " "
             + testName); //$NON-NLS-1$ //$NON-NLS-2$
     fWriter.flush();
   }
 }
Beispiel #19
0
 /*
  * Returns the next element from a string with
  * the following format: next:restOfString
  */
 public static String nextElement(StringBuffer str) {
   String result = "";
   int i = str.indexOf(":", 0);
   if (i == -1) {
     result = str.toString();
     str.setLength(0);
   } else {
     result = str.substring(0, i).toString();
     String a = str.substring(i + 1);
     str.setLength(0);
     str.append(a);
   }
   return result;
 }
Beispiel #20
0
 private void printHeader(
     StringBuffer sb, List<String> columns, Map<String, Integer> columnSizes) {
   for (String column : columns) {
     sb.append(pad(column, columnSizes.get(column)));
     sb.append(" | ");
   }
   sb.setLength(sb.length() - " | ".length());
   sb.append("\n");
   for (String column : columns) {
     for (int i = 0; i < columnSizes.get(column); ++i) sb.append("-");
     sb.append("-+-");
   }
   sb.setLength(sb.length() - "-+-".length());
   sb.append("\n");
 }
  /**
   * Output the specified {@link Collection} in proper columns.
   *
   * @param stuff the stuff to print
   */
  public void printColumns(final Collection stuff) throws IOException {
    if ((stuff == null) || (stuff.size() == 0)) {
      return;
    }

    int width = getTermwidth();
    int maxwidth = 0;

    for (Iterator i = stuff.iterator();
        i.hasNext();
        maxwidth = Math.max(maxwidth, i.next().toString().length())) {;
    }

    StringBuffer line = new StringBuffer();

    int showLines;

    if (usePagination) showLines = getTermheight() - 1; // page limit
    else showLines = Integer.MAX_VALUE;

    for (Iterator i = stuff.iterator(); i.hasNext(); ) {
      String cur = (String) i.next();

      if ((line.length() + maxwidth) > width) {
        printString(line.toString().trim());
        printNewline();
        line.setLength(0);
        if (--showLines == 0) { // Overflow
          printString(loc.getString("display-more"));
          flushConsole();
          int c = readVirtualKey();
          if (c == '\r' || c == '\n') showLines = 1; // one step forward
          else if (c != 'q') showLines = getTermheight() - 1; // page forward

          back(loc.getString("display-more").length());
          if (c == 'q') break; // cancel
        }
      }

      pad(cur, maxwidth + 3, line);
    }

    if (line.length() > 0) {
      printString(line.toString().trim());
      printNewline();
      line.setLength(0);
    }
  }
Beispiel #22
0
  private String[] spritParamater(String param) {
    boolean inQuate = false;

    List commands = new ArrayList();
    StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < param.length(); i++) {
      char c = param.charAt(i);

      if (c == ' ' && !inQuate && buffer.length() > 0) {
        commands.add(buffer.toString());
        buffer.setLength(0);

        continue;
      }

      if (c == '\"') {
        inQuate = !inQuate;
        continue;
      }

      buffer.append(c);
    }

    if (buffer.length() > 0) {
      commands.add(buffer.toString());
    }

    return (String[]) commands.toArray(new String[0]);
  }
Beispiel #23
0
 /**
  * Write out all current attributes
  *
  * @throws IOException when writer.write() fails
  */
 private void writeAttributes() throws IOException {
   if (attrs != null) {
     writer.write(attrs.toString());
     attrs.setLength(0);
     empty = false;
   }
 }
    public void run() {
      StringBuffer data = new StringBuffer();
      Print.logDebug("Client:InputThread started");

      while (true) {
        data.setLength(0);
        boolean timeout = false;
        try {
          if (this.readTimeout > 0L) {
            this.socket.setSoTimeout((int) this.readTimeout);
          }
          ClientSocketThread.socketReadLine(this.socket, -1, data);
        } catch (InterruptedIOException ee) { // SocketTimeoutException ee) {
          // error("Read interrupted (timeout) ...");
          if (getRunStatus() != THREAD_RUNNING) {
            break;
          }
          timeout = true;
          // continue;
        } catch (Throwable t) {
          Print.logError("Client:InputThread - " + t);
          t.printStackTrace();
          break;
        }
        if (!timeout || (data.length() > 0)) {
          ClientSocketThread.this.handleMessage(data.toString());
        }
      }

      synchronized (this.threadLock) {
        this.isRunning = false;
        Print.logDebug("Client:InputThread stopped");
        this.threadLock.notify();
      }
    }
Beispiel #25
0
  /**
   * Glues the sentences back to paragraph.
   *
   * <p>As sentences are returned by {@link #segment(String, List)} without spaces before and after
   * them, this method adds spaces if needed:
   *
   * <ul>
   *   <li>For translation to Japanese does <b>not</b> add any spaces. <br>
   *       A special exceptions are the Break SRX rules that break on space, i.e. before and after
   *       patterns consist of spaces (they get trimmed to an empty string). For such rules all the
   *       spaces are added
   *   <li>For translation from Japanese adds one space
   *   <li>For all other language combinations adds those spaces as were in the paragraph before.
   * </ul>
   *
   * @param sentences list of translated sentences
   * @param spaces information about spaces in original paragraph
   * @param brules rules that account to breaks
   * @return glued translated paragraph
   */
  public static String glue(
      Language sourceLang,
      Language targetLang,
      List<String> sentences,
      List<StringBuffer> spaces,
      List<Rule> brules) {
    if (sentences.size() <= 0) return "";

    StringBuffer res = new StringBuffer();
    res.append(sentences.get(0));

    for (int i = 1; i < sentences.size(); i++) {
      StringBuffer sp = new StringBuffer();
      sp.append(spaces.get(2 * i - 1));
      sp.append(spaces.get(2 * i));

      if (CJK_LANGUAGES.contains(targetLang.getLanguageCode().toUpperCase(Locale.ENGLISH))) {
        Rule rule = brules.get(i - 1);
        char lastChar = res.charAt(res.length() - 1);
        if ((lastChar != '.')
            && (!PatternConsts.SPACY_REGEX.matcher(rule.getBeforebreak()).matches()
                || !PatternConsts.SPACY_REGEX.matcher(rule.getAfterbreak()).matches()))
          sp.setLength(0);
      } else if (CJK_LANGUAGES.contains(sourceLang.getLanguageCode().toUpperCase(Locale.ENGLISH))
          && sp.length() == 0) sp.append(" ");

      res.append(sp);
      res.append(sentences.get(i));
    }
    return res.toString();
  }
  Result decodeRow(int rowNumber, BitArray row, int rowOffset) throws NotFoundException {

    int[] extensionStartRange =
        UPCEANReader.findGuardPattern(row, rowOffset, false, EXTENSION_START_PATTERN);

    StringBuffer result = decodeRowStringBuffer;
    result.setLength(0);
    int end = decodeMiddle(row, extensionStartRange, result);

    String resultString = result.toString();
    Hashtable extensionData = parseExtensionString(resultString);

    Result extensionResult =
        new Result(
            resultString,
            null,
            new ResultPoint[] {
              new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, rowNumber),
              new ResultPoint(end, rowNumber),
            },
            BarcodeFormat.UPC_EAN_EXTENSION);
    if (extensionData != null) {
      extensionResult.putAllMetadata(extensionData);
    }
    return extensionResult;
  }
Beispiel #27
0
    /*
     *  The message and the newLine have been added to the buffer in the
     *  appropriate order so we can now update the Document and send the
     *  text to the optional PrintStream.
     */
    private void clearBuffer() {
      //  In case both the standard out and standard err are being redirected
      //  we need to insert a newline character for the first line only

      if (isFirstLine && document.getLength() != 0) {
        buffer.insert(0, "\n");
      }

      isFirstLine = false;
      final String line = buffer.toString();

      try {
        if (isAppend) {
          final int offset = document.getLength();
          document.insertString(offset, line, attributes);
          textComponent.setCaretPosition(document.getLength());
        } else {
          document.insertString(0, line, attributes);
          textComponent.setCaretPosition(0);
        }
      } catch (final BadLocationException ble) {
      }

      if (printStream != null) {
        printStream.print(line);
      }

      buffer.setLength(0);
    }
  /**
   * Cut or padd the string to the given size
   *
   * @param size the wanted length
   * @param padChar char to use for padding (must be of length()==1!)
   * @return the string with correct lenght, padded with pad if necessary
   */
  public static String forceToSizeLeft(final String str, final int size, final char padChar) {
    if (str != null && str.length() == size) {
      return str;
    }

    final StringBuffer tmp;
    if (str == null) {
      tmp = new StringBuffer(size);
    } else {
      tmp = new StringBuffer(str);
    }

    if (tmp.length() > size) {
      tmp.setLength(size);
      return tmp.toString(); // do cutting
    } else {
      final StringBuffer t2 = new StringBuffer(size);

      final int arsize = size - tmp.length();
      final char[] ar = new char[arsize];
      for (int i = 0; i < arsize; i++) {
        ar[i] = padChar;
      }
      t2.append(ar);
      t2.append(tmp);
      return t2.toString();
    }
  }
 /* (non-Javadoc)
  * @see org.apache.karaf.log.core.internal.LogEventFormatter#format(org.ops4j.pax.logging.spi.PaxLoggingEvent, java.lang.String, boolean)
  */
 @Override
 public String format(PaxLoggingEvent event, String overridenPattern, boolean noColor) {
   final PatternConverter cnv =
       new PatternParser(overridenPattern != null ? overridenPattern : pattern).parse();
   String color = getColor(event, noColor);
   StringBuffer sb = new StringBuffer();
   sb.setLength(0);
   if (color != null) {
     sb.append(FIRST_ESC_CHAR);
     sb.append(SECOND_ESC_CHAR);
     sb.append(color);
     sb.append(COMMAND_CHAR);
   }
   for (PatternConverter pc = cnv; pc != null; pc = pc.next) {
     pc.format(sb, event);
   }
   if (event.getThrowableStrRep() != null) {
     for (String r : event.getThrowableStrRep()) {
       sb.append(r).append('\n');
     }
   }
   if (color != null) {
     sb.append(FIRST_ESC_CHAR);
     sb.append(SECOND_ESC_CHAR);
     sb.append("0");
     sb.append(COMMAND_CHAR);
   }
   return sb.toString();
 }
  public String renderTool(HttpServletResponse response, Controller controller) {
    Hashtable jsImageProperties = new Hashtable();
    StringBuffer propertyValue = new StringBuffer();
    String fullEnabledImageLink = controller.getPathWithContext(enabledImageLink_);
    generateOnMouseValue(propertyValue, response, fullEnabledImageLink);
    int propertyValueLength = propertyValue.length();
    jsImageProperties.put("class", "normal");
    jsImageProperties.put("onMouseOut", propertyValue.append(";mouseout(this)").toString());
    propertyValue.delete(propertyValueLength, propertyValue.length());
    jsImageProperties.put("onMouseUp", propertyValue.append(";mouseup(this)").toString());
    propertyValue.setLength(0);
    generateOnMouseValue(
        propertyValue, response, controller.getPathWithContext(highlightedImageLink_));
    propertyValueLength = propertyValue.length();
    jsImageProperties.put("onMouseOver", propertyValue.append(";mouseover(this)").toString());
    propertyValue.delete(propertyValueLength, propertyValue.length());
    jsImageProperties.put("onMouseDOwn", propertyValue.append(";mousedown(this)").toString());

    String imageTag =
        HTMLUtils.getHTMLImageTag(
            response, fullEnabledImageLink, alt_, "16", "16", jsImageProperties);
    return HTMLUtils.getHTMLLinkTag(
        response,
        controller.getPathWithContext(getSelectToolActionHref(false)),
        getSelectToolActionTarget(),
        null,
        imageTag,
        null);
  }