Example #1
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;
 }
Example #2
1
    /**
     * look for a tag whose text is getStartTag() then read until it closes
     *
     * @return true if there is data
     * @throws java.io.IOException
     */
    public boolean nextKeyValue() throws IOException {
      String current = m_Sb.toString();
      if (current.contains("<scan num=\"67\"")) current = m_Sb.toString(); // break here

      if (readFromCurrentBuffer()) return true;
      int newSize;
      if (m_Current > m_End) { // we are the the end of the split
        m_Key = null;
        m_Value = null;
        m_Sb.setLength(0);
        return false;
      }

      newSize = m_Input.read(m_Buffer);

      while (newSize > 0) {
        m_Current += newSize;
        String read = new String(m_Buffer, 0, newSize);
        m_Sb.append(read);
        if (readFromCurrentBuffer()) return true;
        if (m_Current > m_End) { // we are the the end of the split
          String s = m_Sb.toString();
          if (bufferHasStartTag() == -1) { // not working on a tag
            m_Key = null;
            m_Value = null;
            m_Sb.setLength(0);
            return false;
          }
          if (m_Sb.length() > getMaxTagLength()) {
            m_Key = null;
            m_Value = null;
            m_Sb.setLength(0);
            return false;
          }
        }

        newSize = m_Input.read(m_Buffer);
      }
      // exit because we are at the m_End
      if (newSize <= 0) {
        m_Key = null;
        m_Value = null;
        m_Sb.setLength(0);
        return false;
      }
      if (m_Current > m_End) { // we are the the end of the split
        m_Key = null;
        m_Value = null;
        m_Sb.setLength(0);
        return false;
      }

      return true;
    }
Example #3
1
 /**
  * Convert all special tags in a string to local URL (e.g [sprite: NameOfPony] =&gt;
  * file://path/to/local/sprite.png); allowed special tags are: sprite, type, movetype
  *
  * @return The converted string
  */
 public static String toLocalURL(final String msg) {
   StringBuilder converted = new StringBuilder();
   boolean parsingTag = false;
   boolean inTagName = true;
   StringBuilder tagName = new StringBuilder(10);
   StringBuilder tagArg = new StringBuilder(30);
   for (int i = 0; i < msg.length(); ++i) {
     char c = msg.charAt(i);
     switch (c) {
       case '[':
         if (!parsingTag) {
           parsingTag = true;
         } else {
           if (inTagName) tagName.append(c);
           else tagArg.append(c);
         }
         break;
       case ']':
         if (parsingTag) {
           parsingTag = false;
           converted.append(
               convertLocalURLTag(tagName.toString().trim(), tagArg.toString().trim()));
           tagName.setLength(0);
           tagArg.setLength(0);
           inTagName = true;
         } else {
           converted.append(c);
         }
         break;
       case ':':
         if (parsingTag) {
           if (inTagName) inTagName = false;
           else tagArg.append(c);
         } else {
           converted.append(c);
         }
         break;
       default:
         if (parsingTag) {
           if (inTagName) tagName.append(c);
           else tagArg.append(c);
         } else {
           converted.append(c);
         }
     }
   }
   return converted.toString();
 }
Example #4
1
  /**
   * Maps blah file with a random offset and checks to see if read from the ByteBuffer gets the
   * right line number
   */
  private static void testRead() throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.setLength(4);

    for (int x = 0; x < 1000; x++) {
      try (FileInputStream fis = new FileInputStream(blah)) {
        FileChannel fc = fis.getChannel();

        long offset = generator.nextInt(10000);
        long expectedResult = offset / CHARS_PER_LINE;
        offset = expectedResult * CHARS_PER_LINE;

        MappedByteBuffer b = fc.map(MapMode.READ_ONLY, offset, 100);

        for (int i = 0; i < 4; i++) {
          byte aByte = b.get(i);
          sb.setCharAt(i, (char) aByte);
        }

        int result = Integer.parseInt(sb.toString());
        if (result != expectedResult) {
          err.println("I expected " + expectedResult);
          err.println("I got " + result);
          throw new Exception("Read test failed");
        }
      }
    }
  }
Example #5
1
  /**
   * Break on commas, except those inside quotes, e.g.: size(300, 200, PDF, "output,weirdname.pdf");
   * No special handling implemented for escaped (\") quotes.
   */
  private static StringList breakCommas(String contents) {
    StringList outgoing = new StringList();

    boolean insideQuote = false;
    // The current word being read
    StringBuilder current = new StringBuilder();
    char[] chars = contents.toCharArray();
    for (int i = 0; i < chars.length; i++) {
      char c = chars[i];
      if (insideQuote) {
        current.append(c);
        if (c == '\"') {
          insideQuote = false;
        }
      } else {
        if (c == ',') {
          if (current.length() != 0) {
            outgoing.append(current.toString());
            current.setLength(0);
          }
        } else {
          current.append(c);
          if (c == '\"') {
            insideQuote = true;
          }
        }
      }
    }
    if (current.length() != 0) {
      outgoing.append(current.toString());
    }
    return outgoing;
  }
    private synchronized boolean readAvailable() throws IOException {
      char[] buffer = myBuffer;
      StringBuilder token = new StringBuilder();
      while (myReader.ready()) {
        int n = myReader.read(buffer);
        if (n <= 0) break;

        for (int i = 0; i < n; i++) {
          char c = buffer[i];
          if (skipLF && c != '\n') {
            token.append('\r');
          }

          if (c == '\r') {
            skipLF = true;
          } else {
            skipLF = false;
            token.append(c);
          }

          if (c == '\n') {
            textAvailable(token.toString());
            token.setLength(0);
          }
        }
      }

      if (token.length() != 0) {
        textAvailable(token.toString());
        token.setLength(0);
      }

      if (myIsProcessTerminated) {
        try {
          myReader.close();
        } catch (IOException e1) {
          // supressed
        }

        return false;
      }

      return true;
    }
  /**
   * Joins array elements to string.
   *
   * @param arr Array.
   * @return String.
   */
  @Nullable
  public static String compactArray(Object[] arr) {
    if (arr == null || arr.length == 0) return null;

    String sep = ", ";

    StringBuilder sb = new StringBuilder();

    for (Object s : arr) sb.append(s).append(sep);

    if (sb.length() > 0) sb.setLength(sb.length() - sep.length());

    return U.compact(sb.toString());
  }
Example #8
1
  /**
   * Maps blah file with a random offset and checks to see if data written out to the file can be
   * read back in
   */
  private static void testWrite() throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.setLength(4);

    for (int x = 0; x < 1000; x++) {
      try (RandomAccessFile raf = new RandomAccessFile(blah, "rw")) {
        FileChannel fc = raf.getChannel();

        long offset = generator.nextInt(1000);
        MappedByteBuffer b = fc.map(MapMode.READ_WRITE, offset, 100);

        for (int i = 0; i < 4; i++) {
          b.put(i, (byte) ('0' + i));
        }

        for (int i = 0; i < 4; i++) {
          byte aByte = b.get(i);
          sb.setCharAt(i, (char) aByte);
        }
        if (!sb.toString().equals("0123")) throw new Exception("Write test failed");
      }
    }
  }
  /**
   * Keep track, collect and update the stats of all the <tt>MediaStreamStats</tt> this
   * <tt>HammerStats</tt> handles.
   *
   * <p>Also write the results in the stats files.
   */
  public void run() {
    PrintWriter writer = null;
    StringBuilder allBldr = new StringBuilder();
    String delim;
    String delim_ = "";
    synchronized (this) {
      threadStop = false;
    }

    logger.info("Running the main loop");
    System.out.println("Inside HammerStats run method.\n");

    while (!threadStop) {
      synchronized (this) {
        if (overallStatsLogging || allStatsLogging || summaryStatsLogging) {
          if (allStatsLogging || summaryStatsLogging) {
            if (writer == null) {
              try {
                writer = new PrintWriter(allStatsFile, "UTF-8");
                writer.print("[\n");
              } catch (FileNotFoundException e) {
                logger.fatal("HammerStats stopping due to FileNotFound", e);
                stop();
              } catch (UnsupportedEncodingException e) {
                logger.fatal("HammerStats stopping due to " + "UnsupportedEncoding", e);
              }
            }

            // Clear the StringBuilder
            allBldr.setLength(0);

            writer.print(delim_ + '\n');
            delim_ = ",";
            writer.print("{\n");
            writer.print("  \"timestamp\":" + System.currentTimeMillis() + ",\n");
          }

          delim = "";
          logger.info("Updating the MediaStreamStats");
          for (FakeUserStats stats : fakeUserStatsList) {
            // We update the stats before using/reading them.
            stats.updateStats();
          }

          for (FakeUserStats stats : fakeUserStatsList) {
            if (allStatsLogging) {
              allBldr.append(delim + stats.getStatsJSON(2) + '\n');
              delim = ",";
            }

            if (summaryStatsLogging || overallStatsLogging) {
              logger.info(
                  "Adding stats values from the"
                      + " MediaStreamStats to their"
                      + " HammerSummaryStats objects");
              audioSummaryStats.add(stats.getMediaStreamStats(MediaType.AUDIO));
              videoSummaryStats.add(stats.getMediaStreamStats(MediaType.VIDEO));
            }
          }

          if (allStatsLogging) {
            logger.info("Writing all stats to file");
            writer.print("  \"users\":\n");
            writer.print("  [\n");
            writer.print(allBldr.toString());
            writer.print("  ]");
            if (summaryStatsLogging) writer.print(',');
            writer.print('\n');
          }
          if (summaryStatsLogging) {
            logger.info("Writing summary stats to file");
            writer.print("  \"summary\":\n");
            writer.print("  {\n");

            writer.print("    \"max\":\n");
            writer.print("    {\n");
            writer.print("        \"audio\":");
            writer.print(audioSummaryStats.getMaxJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getMaxJSON() + '\n');
            writer.print("    },\n");

            writer.print("    \"mean\":\n");
            writer.print("    {\n");
            writer.print("       \"audio\":");
            writer.print(audioSummaryStats.getMeanJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getMeanJSON() + '\n');
            writer.print("    },\n");

            writer.print("    \"min\":\n");
            writer.print("    {\n");
            writer.print("        \"audio\":");
            writer.print(audioSummaryStats.getMinJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getMinJSON() + '\n');
            writer.print("    },\n");

            writer.print("    \"standard_deviation\":\n");
            writer.print("    {\n");
            writer.print("        \"audio\":");
            writer.print(audioSummaryStats.getStandardDeviationJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getStandardDeviationJSON() + '\n');
            writer.print("    }\n");

            writer.print("  }\n");
          }
          if (allStatsLogging || summaryStatsLogging) {
            writer.append("}");
            writer.flush();
          }
        }

        if (summaryStatsLogging || overallStatsLogging) {
          logger.info(
              "Clearing the HammerSummaryStats by creating new"
                  + " SummaryStats objects for each watched stats");
          audioSummaryStats.clear();
          videoSummaryStats.clear();
        }
      }

      try {
        Thread.sleep(timeBetweenUpdate * 1000);
      } catch (InterruptedException e) {
        logger.fatal("Error during sleep in main loop : " + e);
        stop();
      }
    }
    logger.info("Exiting the main loop");

    if (writer != null) {
      writer.print("]\n");
      writer.close();
    }

    if (overallStatsLogging) writeOverallStats();
  }
Example #10
1
  /// <summary>
  /// FileStreamから読み込みながらコンストラクト
  /// </summary>
  /// <param name="sr">読み込み対象</param>
  public VsqHandle(TextMemoryStream sr, int value, StringBuilder last_line) {
    try {
      this.index = value;
      String[] spl;
      String[] spl2;

      // default値で梅
      m_type = VsqHandleType.Vibrato;
      iconID = "";
      IDS = "normal";
      L0 = new Lyric("");
      original = 0;
      caption = "";
      length = 0;
      startDepth = 0;
      depthBP = null;
      int depth_bp_num = 0;
      startRate = 0;
      rateBP = null;
      int rate_bp_num = 0;
      language = 0;
      program = 0;
      duration = 0;
      depth = 64;

      String tmpDepthBPX = "";
      String tmpDepthBPY = "";
      String tmpRateBPX = "";
      String tmpRateBPY = "";

      // "["にぶち当たるまで読込む
      last_line.setLength(0);
      last_line.append(sr.readLine());
      while (!last_line.toString().startsWith("[")) {
        spl = Misc.splitString(last_line.toString(), "=");
        if (spl[0].equals("Language")) {
          m_type = VsqHandleType.Singer;
          language = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("Program")) {
          program = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("IconID")) {
          iconID = spl[1];
        } else if (spl[0].equals("IDS")) {
          IDS = spl[1];
        } else if (spl[0].equals("Original")) {
          original = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("Caption")) {
          caption = spl[1];
          for (int i = 2; i < spl.length; i++) {
            caption += "=" + spl[i];
          }
        } else if (spl[0].equals("Length")) {
          length = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("StartDepth")) {
          startDepth = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("DepthBPNum")) {
          depth_bp_num = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("DepthBPX")) {
          tmpDepthBPX = spl[1];
        } else if (spl[0].equals("DepthBPY")) {
          tmpDepthBPY = spl[1];
        } else if (spl[0].equals("StartRate")) {
          m_type = VsqHandleType.Vibrato;
          startRate = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("RateBPNum")) {
          rate_bp_num = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("RateBPX")) {
          tmpRateBPX = spl[1];
        } else if (spl[0].equals("RateBPY")) {
          tmpRateBPY = spl[1];
        } else if (spl[0].equals("L0")) {
          m_type = VsqHandleType.Lyric;
          L0 = new Lyric(spl[1]);
        } else if (spl[0].equals("Duration")) {
          m_type = VsqHandleType.NoteHeadHandle;
          duration = Integer.parseInt(spl[1]);
        } else if (spl[0].equals("Depth")) {
          duration = Integer.parseInt(spl[1]);
        }
        if (sr.peek() < 0) {
          break;
        }
        last_line.setLength(0);
        last_line.append(sr.readLine());
      }
      /*if ( IDS != "normal" ) {
          m_type = VsqHandleType.Singer;
      } else if ( IconID != "" ) {
          m_type = VsqHandleType.Vibrato;
      } else {
          m_type = VsqHandleType.Lyric;
      }*/

      // RateBPX, RateBPYの設定
      if (m_type == VsqHandleType.Vibrato) {
        if (rate_bp_num > 0) {
          float[] rate_bp_x = new float[rate_bp_num];
          spl2 = tmpRateBPX.split(",");
          for (int i = 0; i < rate_bp_num; i++) {
            rate_bp_x[i] = Float.parseFloat(spl2[i]);
          }

          int[] rate_bp_y = new int[rate_bp_num];
          spl2 = tmpRateBPY.split(",");
          for (int i = 0; i < rate_bp_num; i++) {
            rate_bp_y[i] = Integer.parseInt(spl2[i]);
          }
          rateBP = new VibratoBPList(rate_bp_x, rate_bp_y);
        } else {
          // m_rate_bp_x = null;
          // m_rate_bp_y = null;
          rateBP = new VibratoBPList();
        }

        // DepthBPX, DepthBPYの設定
        if (depth_bp_num > 0) {
          float[] depth_bp_x = new float[depth_bp_num];
          spl2 = tmpDepthBPX.split(",");
          for (int i = 0; i < depth_bp_num; i++) {
            depth_bp_x[i] = Float.parseFloat(spl2[i]);
          }

          int[] depth_bp_y = new int[depth_bp_num];
          spl2 = tmpDepthBPY.split(",");
          for (int i = 0; i < depth_bp_num; i++) {
            depth_bp_y[i] = Integer.parseInt(spl2[i]);
          }
          depthBP = new VibratoBPList(depth_bp_x, depth_bp_y);
        } else {
          depthBP = new VibratoBPList();
          // m_depth_bp_x = null;
          // m_depth_bp_y = null;
        }
      } else {
        depthBP = new VibratoBPList();
        rateBP = new VibratoBPList();
      }
    } catch (Exception ex) {
      System.out.println("VsqHandle(TextMemoryStream,int,StringBuilder); ex=" + ex);
    }
  }
Example #11
0
    public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException {
      FileSplit split = (FileSplit) genericSplit;
      Configuration job = context.getConfiguration();
      m_Sb.setLength(0);
      m_Start = split.getStart();
      m_End = m_Start + split.getLength();
      final Path file = split.getPath();
      compressionCodecs = new CompressionCodecFactory(job);
      final CompressionCodec codec = compressionCodecs.getCodec(file);

      // open the file and seek to the m_Start of the split
      FileSystem fs = file.getFileSystem(job);
      //  getFileStatus fileStatus = fs.getFileStatus(split.getPath());
      //noinspection deprecation
      @SuppressWarnings(value = "deprecated")
      long length = fs.getLength(file);
      FSDataInputStream fileIn = fs.open(split.getPath());
      if (m_Start > 0) fileIn.seek(m_Start);
      if (codec != null) {
        CompressionInputStream inputStream = codec.createInputStream(fileIn);
        m_Input = new BufferedReader(new InputStreamReader(inputStream));
        m_End = length;
      } else {
        m_Input = new BufferedReader(new InputStreamReader(fileIn));
      }
      m_Current = m_Start;
      m_Key = split.getPath().getName();
    }
  /** Convert the HTML document back to a string. */
  @Override
  public String toString() {
    try {
      StringBuilder result = new StringBuilder();

      int ch = 0;
      StringBuilder text = new StringBuilder();
      do {
        ch = read();
        if (ch == 0) {
          if (text.length() > 0) {
            System.out.println("Text:" + text.toString());
            text.setLength(0);
          }
          System.out.println("Tag:" + getTag());
        } else if (ch != -1) {
          text.append((char) ch);
        }
      } while (ch != -1);
      if (text.length() > 0) {
        System.out.println("Text:" + text.toString().trim());
      }
      return result.toString();
    } catch (IOException e) {
      return "[IO Error]";
    }
  }
Example #13
0
  /**
   * When data is available on the socket, this method is called to run the command or throw an
   * error if it can't.
   *
   * @throws SocketServerException
   */
  private void handleClientData() throws SocketServerException {
    try {
      input.setLength(0); // clear

      String res;
      int a;
      // (char) -1 is not equal to -1.
      // ready is checked to ensure the read call doesn't block.
      while ((a = in.read()) != -1 && in.ready()) {
        input.append((char) a);
      }
      String inputString = input.toString();
      Logger.debug("Got data from client: " + inputString);
      try {
        AndroidCommand cmd = getCommand(inputString);
        Logger.debug("Got command of type " + cmd.commandType().toString());
        res = runCommand(cmd);
        Logger.debug("Returning result: " + res);
      } catch (final CommandTypeException e) {
        res = new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()).toString();
      } catch (final JSONException e) {
        res =
            new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, "Error running and parsing command")
                .toString();
      }
      out.write(res);
      out.flush();
    } catch (final IOException e) {
      throw new SocketServerException(
          "Error processing data to/from socket (" + e.toString() + ")");
    }
  }
  private static void takeLine(
      final Project project,
      String line,
      StringBuilder sb,
      GitLogParser parser,
      SymbolicRefsI refs,
      VirtualFile root,
      VcsException[] exc,
      GitLineHandler h,
      AsynchConsumer<GitCommit> gitCommitConsumer) {
    final String text = sb.toString();
    sb.setLength(0);
    sb.append(line);
    if (text.length() == 0) return;
    GitLogRecord record = parser.parseOneRecord(text);

    final GitCommit gitCommit;
    try {
      gitCommit = createCommit(project, refs, root, record);
    } catch (VcsException e) {
      exc[0] = e;
      h.cancel();
      return;
    }
    gitCommitConsumer.consume(gitCommit);
  }
 public static ArrayList<String> validateSamplesDirectoryStructureIdentifyVersions(
     String samplesDirPath, ArrayList<String> versionArr) {
   String samplesDir[] = getDirectoryNames(samplesDirPath);
   StringBuilder builder = new StringBuilder();
   ArrayList<String> tempArr = new ArrayList<String>();
   Pattern numeric = Pattern.compile("[0-9_.-]");
   for (String dir : samplesDir) {
     for (int item = dir.length() - 1; item >= 0; item--) {
       char singleChar = dir.charAt(item);
       Matcher matcher = numeric.matcher(Character.toString(singleChar));
       // Find all matches
       if (matcher.find()) {
         // Get the matching string
         builder.append(singleChar);
       } else {
         if (builder.length() > 1) {
           tempArr.add(builder.toString());
           builder.setLength(0);
         } else {
           builder.setLength(0);
         }
       }
       if (item == 0 && builder.length() != 0) {
         tempArr.add(builder.toString());
         builder.setLength(0);
       }
     }
     int max;
     int previousMax = 0;
     String[] version = new String[1];
     for (String element : tempArr) {
       max = element.length();
       if (max > previousMax) {
         previousMax = max;
         version[0] = element;
       }
     }
     if (version[0] != null) {
       if (version[0].length() >= 2) {
         versionArr.add(dir);
       }
     }
     tempArr.clear();
   }
   return versionArr;
 }
Example #16
0
  private static int findNextParameter(
      int pos, String contentType, StringBuilder paramName, StringBuilder paramValue) {
    if (pos >= contentType.length()) {
      return -1;
    }
    paramName.setLength(0);
    paramValue.setLength(0);
    int separator = contentType.indexOf("=", pos);
    if (separator < 0) {
      separator = contentType.length();
    }
    paramName.append(contentType.substring(pos, separator).trim());
    if (separator >= contentType.length() - 1) {
      return contentType.length();
    }

    int startValue = separator + 1;
    int endValue;
    if (contentType.charAt(startValue) == '"') {
      startValue++;
      int i = startValue;
      while (i < contentType.length()) {
        char ch = contentType.charAt(i);
        if (ch == '\\' && i < contentType.length() - 1 && contentType.charAt(i + 1) == '"') {
          paramValue.append('"');
          i += 2;
        } else if (ch == '"') {
          break;
        } else {
          paramValue.append(ch);
          i++;
        }
      }
      endValue = i + 1;
    } else {
      endValue = contentType.indexOf(';', startValue);
      if (endValue < 0) {
        endValue = contentType.length();
      }
      paramValue.append(contentType.substring(startValue, endValue));
    }
    if (endValue < contentType.length() && contentType.charAt(endValue) == ';') {
      endValue++;
    }
    return endValue;
  }
Example #17
0
 @Override
 public String _stringValue(final IScope scope) throws GamaRuntimeException {
   getContents(scope);
   StringBuilder sb = new StringBuilder(getBuffer().length(scope) * 200);
   for (IList s : getBuffer().iterable(scope)) {
     sb.append(s).append("\n"); // TODO Factorize the different calls to "new line" ...
   }
   sb.setLength(sb.length() - 1);
   return sb.toString();
 }
Example #18
0
 String nextWord() throws IOException {
   int c;
   _buf.setLength(0);
   while ((c = nextChar()) <= 32 && c != -1) ;
   if (c == -1) return null;
   while (c > 32) {
     _buf.append((char) c);
     c = nextChar();
   }
   return _buf.toString();
 }
Example #19
0
  private static void testHighOffset() throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.setLength(4);

    for (int x = 0; x < 1000; x++) {
      try (RandomAccessFile raf = new RandomAccessFile(blah, "rw")) {
        FileChannel fc = raf.getChannel();
        long offset = 66000;
        MappedByteBuffer b = fc.map(MapMode.READ_WRITE, offset, 100);
      }
    }
  }
Example #20
0
 /**
  * Build the class path string that contain a list of files pointing to each file needed to
  * include to this application.
  *
  * @return the string that represents the class path
  */
 @Nonnull
 private String buildClassPathString(@Nonnull final Collection<File> classpath) {
   if (classpath.isEmpty()) {
     return "";
   }
   final StringBuilder builder = new StringBuilder();
   for (final File classPathFile : classpath) {
     builder.append(classPathFile.getAbsolutePath());
     builder.append(File.pathSeparatorChar);
   }
   builder.setLength(builder.length() - 1);
   return escapePath(builder.toString());
 }
Example #21
0
  /**
   * Takes the path array and converts to a path string for use in the Properties file
   *
   * @param taPath the path array to convert
   * @return the string version of the path array
   */
  private String denormalise(String[] taPath) {
    StringBuilder loBuilder = new StringBuilder();
    for (String lcString : taPath) {
      loBuilder.append(lcString);
      loBuilder.append(".");
    }

    // Remove the last delimiter
    if (loBuilder.length() > 0) {
      loBuilder.setLength(loBuilder.length() - 1);
    }
    return loBuilder.toString();
  }
Example #22
0
  public void generate(int nconstraints) throws Exception {
    StringBuilder constraint = new StringBuilder();
    for (int i = 0; i < nconstraints; i++) {
      // Parse the DDS to produce a ServerDDS object
      ServerDDS sdds = new ServerDDS(new test_ServerFactory());

      StringBufferInputStream teststream = new StringBufferInputStream(testDDS);
      if (!sdds.parse(teststream)) throw new ParseException("Cannot parse DDS");
      collectnodes(sdds);
      constraint.setLength(0);
      genconstraint(constraint);
      System.out.println(constraint.toString());
    }
  }
Example #23
0
    protected boolean readFromCurrentBuffer() {
      String endTag = getEndTag();
      String startText = m_Sb.toString();
      if (!startText.contains(endTag)) return false; // need more read
      int index = bufferHasStartTag();
      if (index == -1) return false;
      startText = startText.substring(index);
      m_Sb.setLength(0);
      m_Sb.append(startText);

      String s = m_Sb.toString();
      ;
      index = s.indexOf(endTag);
      if (index == -1) return false; // need more read
      // throw new IllegalStateException("unmatched tag " + getBaseTag());
      index += endTag.length();
      m_Value = s.substring(0, index).trim();

      // keep the remaining text to add to the next tag
      m_Sb.setLength(0);
      String rest = s.substring(index);
      m_Sb.append(rest);
      return true;
    }
Example #24
0
 String readToken() throws IOException {
   if (cur == -1) {
     throw new EOFException();
   }
   while (whitespace()) {
     cur = read();
   }
   if (cur == -1) {
     throw new EOFException();
   }
   sb.setLength(0);
   while (!whitespace()) {
     sb.append((char) cur);
     cur = read();
   }
   return sb.toString();
 }
Example #25
0
 String readLine() throws IOException {
   if (cur == -1) {
     throw new EOFException();
   }
   sb.setLength(0);
   while (cur != -1 && cur != '\r' && cur != '\n') {
     sb.append((char) cur);
     cur = read();
   }
   if (cur == '\r') {
     cur = read();
   }
   if (cur == '\n') {
     cur = read();
   }
   return sb.toString();
 }
    @Nullable
    public GitLogRecord acceptLine(String s) {
      final boolean lineEnd = s.startsWith(GitLogParser.RECORD_START);
      if (lineEnd && (!myNotStarted)) {
        final String line = myBuffer.toString();
        myBuffer.setLength(0);
        myBuffer.append(s.substring(GitLogParser.RECORD_START.length()));

        return processResult(line);
      } else {
        myBuffer.append(lineEnd ? s.substring(GitLogParser.RECORD_START.length()) : s);
        myBuffer.append("\n");
      }
      myNotStarted = false;

      return null;
    }
Example #27
0
  private static void initTestData() throws IOException {
    long lTime = System.currentTimeMillis();
    boolean isStable = false;
    long l = 0;
    Pattern pattern = Pattern.compile("([=][-|0-9|\\s]{10}[\\D])");
    StringBuilder receivedData = new StringBuilder();
    BufferedReader br = new BufferedReader(new FileReader("cp.log"));
    String strLine;
    while ((strLine = br.readLine()) != null) {

      int count = strLine.length();
      try {
        if (count > 0) {
          receivedData.append(strLine);
          Matcher m = pattern.matcher(receivedData);
          if (m.find()) {
            String val = m.group(0);
            System.out.println((l++) + val);
            Integer newValue = Integer.valueOf(prs(val, false));
            long cTime = System.currentTimeMillis();

            if (weight != null && newValue != null && Math.abs(weight - newValue) <= 20) {
              isStable = cTime - lTime > 999;
            } else {
              isStable = false;
              lTime = cTime;
            }

            weight = newValue;

            System.out.println(weight);
            receivedData.setLength(0);
          }

          // fireScaleEvent();
        }
      } catch (Exception e) {
        weight = null;
        // receivedData.setLength(0);
        e.printStackTrace();
      }
    }
  }
  @Override
  public final void writeStartArray() throws IOException {
    _verifyValueWrite("start an array");
    /* Ok to create root-level array to contain Objects/Arrays, but
     * can not nest arrays in objects
     */
    if (_writeContext.inObject()) {
      if (!_skipValue) {
        // First: column may have its own separator
        int sep;

        if (_nextColumnByName >= 0) {
          CsvSchema.Column col = _schema.column(_nextColumnByName);
          sep = col.isArray() ? col.getArrayElementSeparator() : -1;
        } else {
          sep = -1;
        }
        if (sep <= 0) {
          if (!_schema.hasArrayElementSeparator()) {
            _reportMappingError(
                "CSV generator does not support Array values for properties without setting 'arrayElementSeparator' in schema");
          }
          sep = _schema.getArrayElementSeparator();
        }
        _arraySeparator = sep;
        if (_arrayContents == null) {
          _arrayContents = new StringBuilder();
        } else {
          _arrayContents.setLength(0);
        }
        _arrayElements = 0;
      }
    } else if (_arraySeparator >= 0) {
      // also: no nested arrays, yet
      _reportMappingError("CSV generator does not support nested Array values");
    }

    _writeContext = _writeContext.createChildArrayContext();
    // and that's about it, really
  }
  /**
   * @param antPattern ant-style path pattern
   * @return java regexp pattern. Note that no matter whether forward or backward slashes were used
   *     in the antPattern the returned regexp pattern will use forward slashes ('/') as file
   *     separators. Paths containing windows-style backslashes must be converted before matching
   *     against the resulting regexp
   * @see com.intellij.openapi.util.io.FileUtil#toSystemIndependentName
   */
  @RegExp
  @NotNull
  public static String convertAntToRegexp(@NotNull String antPattern, boolean ignoreStartingSlash) {
    final StringBuilder builder = new StringBuilder();
    int asteriskCount = 0;
    boolean recursive = true;
    final int start =
        ignoreStartingSlash
                && (StringUtil.startsWithChar(antPattern, '/')
                    || StringUtil.startsWithChar(antPattern, '\\'))
            ? 1
            : 0;
    for (int idx = start; idx < antPattern.length(); idx++) {
      final char ch = antPattern.charAt(idx);

      if (ch == '*') {
        asteriskCount++;
        continue;
      }

      final boolean foundRecursivePattern =
          recursive && asteriskCount == 2 && (ch == '/' || ch == '\\');
      final boolean asterisksFound = asteriskCount > 0;

      asteriskCount = 0;
      recursive = ch == '/' || ch == '\\';

      if (foundRecursivePattern) {
        builder.append("(?:[^/]+/)*?");
        continue;
      }

      if (asterisksFound) {
        builder.append("[^/]*?");
      }

      if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '^' || ch == '$' || ch == '.'
          || ch == '{' || ch == '}' || ch == '+' || ch == '|') {
        // quote regexp-specific symbols
        builder.append('\\').append(ch);
        continue;
      }
      if (ch == '?') {
        builder.append("[^/]{1}");
        continue;
      }
      if (ch == '\\') {
        builder.append('/');
        continue;
      }
      builder.append(ch);
    }

    // handle ant shorthand: mypackage/test/ is interpreted as if it were mypackage/test/**
    final boolean isTrailingSlash =
        builder.length() > 0 && builder.charAt(builder.length() - 1) == '/';
    if (asteriskCount == 0 && isTrailingSlash || recursive && asteriskCount == 2) {
      if (isTrailingSlash) {
        builder.setLength(builder.length() - 1);
      }
      if (builder.length() == 0) {
        builder.append(".*");
      } else {
        builder.append("(?:$|/.+)");
      }
    } else if (asteriskCount > 0) {
      builder.append("[^/]*?");
    }
    return builder.toString();
  }
Example #30
0
  private static String canonicalURI(String s) {
    if (s == null) {
      return null;
    }
    StringBuilder result = new StringBuilder();
    final int len = s.length();
    int pos = 0;
    while (pos < len) {
      char c = s.charAt(pos);
      if (isPathSeparator(c)) {
        /*
         * multiple path separators.
         * 'foo///bar' -> 'foo/bar'
         */
        while (pos + 1 < len && isPathSeparator(s.charAt(pos + 1))) {
          ++pos;
        }

        if (pos + 1 < len && s.charAt(pos + 1) == '.') {
          /*
           * a single dot at the end of the path - we are done.
           */
          if (pos + 2 >= len) {
            break;
          }

          switch (s.charAt(pos + 2)) {
              /*
               * self directory in path
               * foo/./bar -> foo/bar
               */
            case '/':
            case '\\':
              pos += 2;
              continue;

              /*
               * two dots in a path: go back one hierarchy.
               * foo/bar/../baz -> foo/baz
               */
            case '.':
              // only if we have exactly _two_ dots.
              if (pos + 3 < len && isPathSeparator(s.charAt(pos + 3))) {
                pos += 3;
                int separatorPos = result.length() - 1;
                while (separatorPos >= 0 && !isPathSeparator(result.charAt(separatorPos))) {
                  --separatorPos;
                }
                if (separatorPos >= 0) {
                  result.setLength(separatorPos);
                }
                continue;
              }
          }
        }
      }
      result.append(c);
      ++pos;
    }
    return result.toString();
  }