Exemplo n.º 1
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;
    }
Exemplo n.º 2
0
 String readBodyChunked(BufferedReader br) throws IOException {
   StringBuilder body = new StringBuilder();
   String line;
   while ((line = br.readLine()) != null) {
     int hex = 2 * 2 * 2 * 2;
     int chunk = Integer.parseInt(line, hex);
     if (chunk == 0) {
       break;
     }
     int chr;
     for (int i = 0; i < chunk; i++) {
       chr = br.read();
       body.append((char) chr);
     }
     chr = br.read();
     if (chr != '\r') {
       fail("Chunk終了後のCRが無い");
     }
     chr = br.read();
     if (chr != '\n') {
       fail("Chunk終了後のLFが無い");
     }
   }
   return body.toString();
 }
Exemplo n.º 3
0
  private String ask(String cmd) {
    BufferedWriter out = null;
    BufferedReader in = null;
    Socket sock = null;
    String ret = "";
    try {
      System.out.println(server);
      sock = new Socket(server, ServerListener.PORT);
      out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      out.write(cmd, 0, cmd.length());
      out.flush();
      in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      int inr = in.read();
      while (inr != ';') {
        ret += Character.toString((char) inr);
        inr = in.read();
      }
    } catch (IOException io) {
      io.printStackTrace();
    } finally {
      try {
        out.close();
        in.close();
        sock.close();
      } catch (IOException io) {
        io.printStackTrace();
      }
    }

    return ret;
  }
  static void download(final DownloadJob job) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) job.url.openConnection();
    connection.setRequestMethod("GET");
    if (job.headers != null) {
      for (final Entry<String, String> e : job.headers.entrySet()) {
        connection.addRequestProperty(e.getKey(), e.getValue());
      }
    }
    connection.connect();

    job.responseCode = connection.getResponseCode();
    job.responseHeaders.clear();
    job.responseText = null;

    for (int i = 1; ; i++) {
      final String key = connection.getHeaderFieldKey(i);
      if (key == null) {
        break;
      }
      final String value = connection.getHeaderField(i);
      job.responseHeaders.put(key.toLowerCase(), value);
    }

    final StringBuilder sb = new StringBuilder();
    final BufferedReader r =
        new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    try {
      for (int ch = r.read(); ch != -1; ch = r.read()) {
        sb.append((char) ch);
      }
      job.responseText = sb.toString();
    } finally {
      r.close();
    }
  }
  /** @tests java.io.BufferedReader#read() */
  public void test_read() throws IOException {
    // Test for method int java.io.BufferedReader.read()
    try {
      br = new BufferedReader(new Support_StringReader(testString));
      int r = br.read();
      assertTrue("Char read improperly", testString.charAt(0) == r);
      br = new BufferedReader(new Support_StringReader(new String(new char[] {'\u8765'})));
      assertTrue("Wrong double byte character", br.read() == '\u8765');
    } catch (java.io.IOException e) {
      fail("Exception during read test");
    }

    char[] chars = new char[256];
    for (int i = 0; i < 256; i++) chars[i] = (char) i;
    Reader in = new BufferedReader(new Support_StringReader(new String(chars)), 12);
    try {
      assertEquals("Wrong initial char", 0, in.read()); // Fill the
      // buffer
      char[] buf = new char[14];
      in.read(buf, 0, 14); // Read greater than the buffer
      assertTrue("Wrong block read data", new String(buf).equals(new String(chars, 1, 14)));
      assertEquals("Wrong chars", 15, in.read()); // Check next byte
    } catch (IOException e) {
      fail("Exception during read test 2:" + e);
    }

    // regression test for HARMONY-841
    assertTrue(new BufferedReader(new CharArrayReader(new char[5], 1, 0), 2).read() == -1);
  }
  public void test_reset_IOException() throws Exception {
    int[] expected = new int[] {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', -1};
    br = new BufferedReader(new Support_StringReader("1234567890"), 9);
    br.mark(9);
    for (int i = 0; i < 11; i++) {
      assertEquals(expected[i], br.read());
    }
    try {
      br.reset();
      fail("should throw IOException");
    } catch (IOException e) {
      // Expected
    }
    for (int i = 0; i < 11; i++) {
      assertEquals(-1, br.read());
    }

    br = new BufferedReader(new Support_StringReader("1234567890"));
    br.mark(10);
    for (int i = 0; i < 10; i++) {
      assertEquals(expected[i], br.read());
    }
    br.reset();
    for (int i = 0; i < 11; i++) {
      assertEquals(expected[i], br.read());
    }
  }
Exemplo n.º 7
0
  // Executes UNIX command.
  private String exec(String command) {
    try {
      if (D) Log.d(TAG, "Exec command: " + command);
      Process process = Runtime.getRuntime().exec(command);
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
      BufferedReader errreader =
          new BufferedReader(new InputStreamReader(process.getErrorStream()));
      int read;
      char[] buffer = new char[4096];
      StringBuffer output = new StringBuffer();
      while ((read = reader.read(buffer)) > 0) {
        output.append(buffer, 0, read);
      }
      while ((read = errreader.read(buffer)) > 0) {
        output.append(buffer, 0, read);
      }
      errreader.close();
      process.waitFor();
      if (D) Log.d(TAG, output.toString());

      return output.toString();
    } catch (IOException e) {
      throw new RuntimeException(e);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 8
0
 public static void compareLines(String text, String[] lines) throws IOException {
   BufferedReader reader = new BufferedReader(new StringReader(text));
   for (int i = 0; i < lines.length - 1; i++) Assert.assertEquals(lines[i], reader.readLine());
   String lastLine = lines[lines.length - 1];
   char[] buffer = new char[lastLine.length()];
   reader.read(buffer, 0, buffer.length);
   Assert.assertEquals(lastLine, new String(buffer));
   Assert.assertEquals(-1, reader.read());
 }
Exemplo n.º 9
0
 public int read(char[] cbuf, int off, int len) throws IOException {
   // BOM (byte order mark) bugfix
   if (readFirstTime) {
     readFirstTime = false;
     reader.mark(1);
     int ch = reader.read();
     if (ch != 0xFEFF) reader.reset();
   }
   return reader.read(cbuf, off, len);
 }
Exemplo n.º 10
0
  private void ProcessData(DataHeader dataHeader, BufferedReader bufferedReader)
      throws IOException {
    char buffer[] = new char[dataHeader.NumBytes];

    int result = bufferedReader.read(buffer, 0, dataHeader.NumBytes);
    Log.i(LOGTAG_NETWORKING, "Received " + result + " bytes from server as expected.");
    while (result < dataHeader.NumBytes) {
      Log.i(
          LOGTAG_NETWORKING,
          "Received "
              + result
              + " bytes from server. Expected "
              + dataHeader.NumBytes
              + " bytes. Sleeping for a bit.");
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        Log.e(LOGTAG_NETWORKING, "Error during wait message sleep", e);
      }
      result += bufferedReader.read(buffer, result, dataHeader.NumBytes - result);
    }

    String data = new String(buffer);

    // No XML definition, so process as a string
    if (dataHeader.XmlDataType == null) {
      AmplifyRealityActivity.OnMessage(data, null);
    } else
    // Deserialize
    {
      try {
        String className = dataHeader.XmlDataType;

        Serializer serializer = new Persister();
        if (className.equals(ARObject.class.getCanonicalName())) // Update notification
        {
          ARObject arObject = serializer.read(ARObject.class, data);
          Log.i(LOGTAG_NETWORKING, "Received ARObject: " + arObject.toString());
          AmplifyRealityActivity.OnMessage("ARObjectUpdate", arObject);
        } else if (className.equals(Realm.class.getCanonicalName())) {
          Realm realm = serializer.read(Realm.class, data);
          Log.i(LOGTAG_NETWORKING, "Received new Realm: " + realm.toString());
          AmplifyRealityActivity.OnMessage("RealmObject", realm);
        } else if (className.equals(WavefrontObj.class.getCanonicalName())) {
          WavefrontObj wavefrontObj = serializer.read(WavefrontObj.class, data);
          Log.i(LOGTAG_NETWORKING, "Received new wavefront model: " + wavefrontObj.toString());
          AmplifyRealityActivity.OnMessage("WavefrontObject", wavefrontObj);
        } else {
          Log.w(LOGTAG_NETWORKING, "Received unknown XML object. Classname=" + className);
        }
      } catch (Exception e) {
        Log.e(LOGTAG_NETWORKING, "Error parsing message from server", e);
      }
    }
  }
Exemplo n.º 11
0
  /**
   * parse a field. It is assumed the leading '"' is already read. we stop at the first '"' that
   * isn't followed by a '"'.
   *
   * @param doubleQuotes is true if we're within a quoted string.
   * @param firstChar is the first character of the field unless its value is -1
   * @return the field, or null if the field was blank ("")
   * @throws IOException IOException from the reader.
   * @throws ParseException if we reach the end of file while parsing
   */
  private String parseField(BufferedReader reader, boolean doubleQuotes, int firstChar)
      throws IOException, ParseException {
    StringBuilder result = new StringBuilder();

    if (firstChar != -1) {
      result.append((char) firstChar);
    }
    int ch;
    reader.mark(1);
    while ((ch = reader.read()) != -1) {
      if (ch == '"' && doubleQuotes) {
        reader.mark(1);
        ch = reader.read();
        if (ch != '"') {
          reader.reset();
          if (result.length() == 0) {
            return null;
          } else {
            return result.toString();
          }
        }
        result.append((char) ch);
      } else if (!doubleQuotes && isFieldSeparator(ch)) {
        // reader.reset();
        return result.toString();
      } else if ((ch == '\r' || ch == '\n') && !doubleQuotes) {
        reader.reset();
        return result.toString();
      } else {
        result.append((char) ch);
        if (ch == '\r') {
          // peek for \n
          reader.mark(1);
          ch = reader.read();
          if (ch == '\n') {
            result.append((char) ch);
          } else {
            reader.reset();
          }
        }
        if ((ch == '\r') || (ch == '\n')) {
          lineNumber++;
        }
      }
      reader.mark(1);
    }
    if (doubleQuotes) {
      throw new ParseException(
          "End of stream reached while parsing field.\nCurrent contact definition started at line "
              + currContactStartLineNum);
    } else {
      return result.toString();
    }
  }
Exemplo n.º 12
0
  private void showWuxiaNovel() throws IOException {
    novelList = xmlFileReader.readXMLFile();

    int novelListLength = novelList.size();
    // 向client端传送novelList的长度
    printWriter.println(novelListLength);
    printWriter.flush();
    System.out.println(novelListLength);
    for (int i = 0; i < novelListLength; i++) {
      String title = null;
      String author = null;
      String introduction = null;
      Novel novel = novelList.get(i);
      if (novel.getCategory().equals("武侠")) {
        title = novel.getTitle();
        author = novel.getAuthor();
        introduction = novel.getIntroduction();
        // System.out.println(title + "\t\t" + author + "\t\t" +
        // introduction);
        String oneNovelInfo = i + 1 + "\t\t" + title + "\t\t" + author + "\t\t" + introduction;
        printWriter.println(oneNovelInfo.trim());
        printWriter.flush();
      }
      System.out.println(i);
    }

    // 接收client选择的书的序号
    int selectedBook = bufferedReader.read() - 48;
    // System.out.println("您选择的是第"+(select-1)+"本书。");

    // 接受对该书的操作,1在线阅读,2下载
    int selectOperation = bufferedReader.read() - 48;
    // do {
    switch (selectOperation) {
      case 1:
        // readOnline(novelList.get(selectedBook).getTitle());
        System.out.println("在线阅读写不出来先放在这里。");
        break;

      case 2:
        // 下载小说
        download(novelList.get(selectedBook).getTitle());

      default:
        break;
    }
    showUserPage();

    // System.out.println("是否继续阅读,继续阅读输入1,返回输入0");
    // selectOperation = bufferedReader.read() - 48;
    // } while (selectOperation != 0);

  }
Exemplo n.º 13
0
  @Test
  public void testGETThenSmallResponseContent() throws Exception {
    final byte[] data = "0123456789ABCDEF".getBytes("UTF-8");
    InetSocketAddress proxyAddress =
        startProxy(
            startServer(
                new ServerSessionFrameListener.Adapter() {
                  @Override
                  public StreamFrameListener onSyn(Stream stream, SynInfo synInfo) {
                    Assert.assertTrue(synInfo.isClose());
                    Fields requestHeaders = synInfo.getHeaders();
                    Assert.assertNotNull(requestHeaders.get("via"));

                    Fields responseHeaders = new Fields();
                    responseHeaders.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                    responseHeaders.put(HTTPSPDYHeader.STATUS.name(version), "200 OK");
                    ReplyInfo replyInfo = new ReplyInfo(responseHeaders, false);
                    stream.reply(replyInfo, new Callback.Adapter());
                    stream.data(new BytesDataInfo(data, true), new Callback.Adapter());

                    return null;
                  }
                }));

    Socket client = new Socket();
    client.connect(proxyAddress);
    OutputStream output = client.getOutputStream();

    String request =
        "" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + proxyAddress.getPort() + "\r\n" + "\r\n";
    output.write(request.getBytes("UTF-8"));
    output.flush();

    InputStream input = client.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
    String line = reader.readLine();
    Assert.assertTrue(line.contains(" 200 "));
    while (line.length() > 0) line = reader.readLine();
    for (byte datum : data) Assert.assertEquals(datum, reader.read());
    Assert.assertFalse(reader.ready());

    // Perform another request so that we are sure we reset the states of parsers and generators
    output.write(request.getBytes("UTF-8"));
    output.flush();

    line = reader.readLine();
    Assert.assertTrue(line.contains(" 200"));
    while (line.length() > 0) line = reader.readLine();
    for (byte datum : data) Assert.assertEquals(datum, reader.read());
    Assert.assertFalse(reader.ready());

    client.close();
  }
Exemplo n.º 14
0
 public String readWord() throws IOException {
   StringBuilder b = new StringBuilder();
   int c;
   c = br.read();
   while (c >= 0 && c <= ' ') c = br.read();
   if (c < 0) return "";
   while (c > ' ') {
     b.append((char) c);
     c = br.read();
   }
   return b.toString();
 }
Exemplo n.º 15
0
 /** read a line of fields into an array list. blank fields (,, or ,"",) will be null. */
 private boolean parseLine(BufferedReader reader, List<String> result, boolean parsingHeader)
     throws IOException, ParseException {
   currContactStartLineNum = lineNumber;
   if (parsingHeader && detectFieldSeparator) {
     knowFieldSeparator = false;
   }
   result.clear();
   int ch;
   boolean inField = false;
   while ((ch = reader.read()) != -1) {
     switch (ch) {
       case '"':
         inField = true;
         result.add(parseField(reader, true, -1));
         break;
       case '\n':
         lineNumber++;
         if (result.isEmpty()) {
           break;
         } else {
           return true;
         }
       case '\r':
         lineNumber++;
         // peek for \n
         reader.mark(1);
         ch = reader.read();
         if (ch != '\n') {
           reader.reset();
         }
         if (result.isEmpty()) {
           break;
         } else {
           return true;
         }
       default:
         if (isFieldSeparator(ch)) {
           if (inField) {
             inField = false;
           } else {
             result.add(null);
           }
         } else {
           // start of field
           result.add(parseField(reader, false, ch)); // eats trailing field separator
           inField = false;
         }
         break;
     }
   }
   return !result.isEmpty();
 }
Exemplo n.º 16
0
 private static String readErrorString(final HttpURLConnection connection) {
   try (InputStream stream = connection.getErrorStream()) {
     StringBuilder buffer = new StringBuilder();
     try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) {
       for (int ch = reader.read(); ch >= 0; ch = reader.read()) {
         buffer.append((char) ch);
       }
     }
     return buffer.toString();
   } catch (IOException e) {
     return e.getMessage();
   }
 }
Exemplo n.º 17
0
 /**
  * Read the contents of a reader and turn it into a string.
  *
  * @param fileReader where to get the string.
  * @return the contents of the file.
  * @throws IOException if an I/O error occurs.
  */
 public static String readerToString(final Reader fileReader) throws IOException {
   final StringBuilder sb = new StringBuilder();
   try (BufferedReader br = new BufferedReader(fileReader)) {
     final char[] buffer = FileUtils.makeBuffer();
     final int eof = -1;
     for (int len = br.read(buffer); len > eof; len = br.read(buffer)) {
       for (int i = 0; i < len; i++) {
         sb.append(buffer[i]);
       }
     }
   }
   return sb.toString();
 }
Exemplo n.º 18
0
 /** Utility method to load the contents of an InputStream as a String */
 private static String getInputStreamContents(InputStream inputStream) throws IOException {
   int chunksize = 512;
   BufferedReader reader =
       new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); // ?  // NOI18N
   StringBuffer output = new StringBuffer();
   char[] buff = new char[chunksize];
   int len = reader.read(buff);
   while (len > 0) {
     output.append(buff, 0, len);
     len = reader.read(buff);
   }
   return output.toString();
 }
Exemplo n.º 19
0
  public static void main(String[] args) throws IOException {
    // Make sure that the reader does not wait for additional characters to
    // be read after reading a new line.
    BufferedReader reader;
    String[][] strings = {
      {"CR/LF\r\n", "CR/LF"},
      {"LF-Only\n", "LF-Only"},
      {"CR-Only\r", "CR-Only"},
      {"CR/LF line\r\nMore data", "More data"}
    };

    // test 0 "CR/LF\r\n"
    // test 1 "LF-Only\n"
    // test 2 "CR-Only\r"
    for (int i = 0; i < 3; i++) {
      reader = new BufferedReader(new BoundedReader(strings[i][0]), strings[i][0].length());
      if (!reader.readLine().equals(strings[i][1]))
        throw new RuntimeException("Read incorrect text");
    }

    // Now test the mark and reset operations. Consider two cases.
    // 1. For lines ending with CR only.
    markResetTest("Lot of textual data\rMore textual data\n", "More textual data");

    // 2. Now for lines ending with CR/LF
    markResetTest("Lot of textual data\r\nMore textual data\n", "More textual data");

    // 3. Now for lines ending with LF only
    markResetTest("Lot of textual data\nMore textual data\n", "More textual data");

    // Need to ensure behavior of read() after a readLine() read of a CR/LF
    // terminated line.
    // 1.  For lines ending with CR/LF only.

    // uses "CR/LF line\r\nMore data"
    reader = new BufferedReader(new BoundedReader(strings[3][0]), strings[3][0].length());
    reader.readLine();
    if (reader.read() != 'M') throw new RuntimeException("Read() failed");

    // Need to ensure that a read(char[], int, int) following a readLine()
    // read of a CR/LF terminated line behaves correctly.

    // uses "CR/LF line\r\nMore data"
    reader = new BufferedReader(new BoundedReader(strings[3][0]), strings[3][0].length());
    reader.readLine();

    char[] buf = new char[9];
    reader.read(buf, 0, 9);
    String newStr = new String(buf);
    if (!newStr.equals(strings[3][1])) throw new RuntimeException("Read(char[],int,int) failed");
  }
Exemplo n.º 20
0
  public static char[] readData(BufferedReader in) throws IOException {
    char[] c1 = new char[PACKET_SIZE];
    int i;
    int c_temp = in.read(); // c_temp is an int and not a char;
    if (c_temp != -1) {
      c1[0] = (char) c_temp;
    }

    for (i = 1; i < PACKET_SIZE && c_temp != -1; i++) {
      c_temp = in.read();
      c1[i] = (char) c_temp;
    }
    return c1;
  }
Exemplo n.º 21
0
  private static char[] readResponseData(InputStream stream, String encoding) {
    BufferedReader in = null;
    char[] data = null;
    try {
      StringBuffer buf = new StringBuffer();
      data = new char[1024];

      in = new BufferedReader(new InputStreamReader(stream, encoding));
      int charsRead;
      while ((charsRead = in.read(data)) != -1) {
        buf.append(data, 0, charsRead);
      }
      data = new char[buf.length()];
      buf.getChars(0, data.length, data, 0);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return data != null ? data : null;
  }
Exemplo n.º 22
0
 /** @tests java.io.BufferedReader#reset() */
 public void test_reset() {
   // Test for method void java.io.BufferedReader.reset()
   try {
     br = new BufferedReader(new Support_StringReader(testString));
     br.skip(500);
     br.mark(900);
     br.skip(500);
     br.reset();
     char[] buf = new char[testString.length()];
     br.read(buf, 0, 500);
     assertTrue(
         "Failed to reset properly",
         testString.substring(500, 1000).equals(new String(buf, 0, 500)));
   } catch (java.io.IOException e) {
     fail("Exception during reset test");
   }
   try {
     br = new BufferedReader(new Support_StringReader(testString));
     br.skip(500);
     br.reset();
     fail("Reset succeeded on unmarked stream");
   } catch (IOException x) {
     return;
   }
 }
  private void parse(String filename) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
    StringBuffer sb = new StringBuffer();

    int j;
    while ((j = br.read()) != -1) {
      char next = (char) j;

      if (next >= 'A' && next <= 'z') {
        sb.append(next);
      }

      if (sb.length() == 4) {
        String qGram = sb.toString().toUpperCase();
        sb = new StringBuffer();

        int frequency = 0;

        if (map.containsKey(qGram)) {
          frequency = map.get(qGram);
        }

        frequency++;
        map.put(qGram, frequency);
      }
    }
    br.close();
  }
Exemplo n.º 24
0
 private void solve() throws Exception {
   int next;
   int state = STATE_NO_WORD;
   int tramCount = 0;
   int trolleybusCount = 0;
   while ((next = bufferedReader.read()) != -1) {
     char ch = (char) next;
     boolean isLetter = ch >= 'a' && ch <= 'z';
     if (!isLetter) {
       if (state == STATE_TRAM) {
         tramCount++;
       } else if (state == STATE_TROLLEYBUS) {
         trolleybusCount++;
       }
       state = STATE_NO_WORD;
     } else {
       int i = 0;
       while (i < rules.length && (rules[i].state != state || rules[i].ch != ch)) {
         i++;
       }
       if (i < rules.length) {
         state = rules[i].next;
       } else {
         state = STATE_UNK_WORD;
       }
     }
   }
   if (tramCount > trolleybusCount) {
     out.println("Tram driver");
   } else if (tramCount < trolleybusCount) {
     out.println("Trolleybus driver");
   } else {
     out.println("Bus driver");
   }
 }
Exemplo n.º 25
0
    public void run() {
      if (Thread.currentThread() == this) {
        //                    Environment.setThreadEnvironment(launcherEnvironment);
        Job.setUserInterface(userInterface);
      }
      try {
        PrintWriter pw = null;
        if (redirect != null) pw = new PrintWriter(redirect);

        // read from stream
        InputStreamReader input = new InputStreamReader(in);
        BufferedReader reader = new BufferedReader(input);
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
          if (pw != null) {
            pw.write(buf, 0, read);
            pw.flush();
          }
        }

        reader.close();
        input.close();

      } catch (java.io.IOException e) {
        ActivityLogger.logException(e);
      }
    }
Exemplo n.º 26
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
  private static String readString(InputStream is, String encoding) {
    if (is == null) {
      return null;
    }
    BufferedReader reader = null;
    try {
      StringBuffer buffer = new StringBuffer();
      char[] part = new char[2048];
      int read = 0;
      reader = new BufferedReader(new InputStreamReader(is, encoding));
      while ((read = reader.read(part)) != -1) {
        buffer.append(part, 0, read);
      }
      return buffer.toString();

    } catch (IOException ex) {
      // NeedWork
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException ex) {
          // silently ignored
        }
      }
    }
    return null;
  }
Exemplo n.º 28
0
 public String readRequestBody(BufferedReader in, int length) throws IOException {
   StringBuilder bodyContent = new StringBuilder();
   char[] chars = new char[length];
   in.read(chars, 0, length);
   bodyContent.append(chars);
   return bodyContent.toString();
 }
Exemplo n.º 29
0
  private String getData(String url, String data) throws WasabiNetClientException {

    StringBuffer sb = new StringBuffer();

    try {
      URL dest = new URL(url);
      URLConnection conn = dest.openConnection();

      conn.setDoOutput(true);

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF8");
      System.out.println(writer.getEncoding());
      writer.write(data);
      writer.flush();

      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

      char[] buf = new char[MAX_READ];
      int readed = 0;
      while ((readed = reader.read(buf)) > 0) {
        sb.append(buf, 0, readed);
      }

    } catch (MalformedURLException ex) {
      Logger.getLogger(WasabiNetClient.class.getName()).log(Level.SEVERE, null, ex);
      throw new WasabiNetClientException(
          "Error al conectar con la url <" + url + ">:" + ex.getMessage());
    } catch (IOException ex) {
      Logger.getLogger(WasabiNetClient.class.getName()).log(Level.SEVERE, null, ex);
      throw new WasabiNetClientException("Error de lectura/escritura:" + ex.getMessage());
    }

    return sb.toString();
  }
Exemplo n.º 30
0
  /**
   * Method to read the content of a file into a String and return it
   *
   * @param file a File to be read
   * @return a String object containing the content of the file
   */
  protected String readFileIntoString(File file) {
    StringBuilder fileContentsBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
      char[] buffer = new char[32767];
      bufferedReader = new BufferedReader(new FileReader(file));
      int read = 0;

      do {
        read = bufferedReader.read(buffer);
        if (read > 0) {
          fileContentsBuilder.append(buffer, 0, read);
        }
      } while (read > 0);
    } catch (Exception e) {
      log.error("Failed to read file " + file.getPath(), e);
    } finally {
      if (bufferedReader != null) {
        try {
          bufferedReader.close();
        } catch (IOException e) {
          log.error("Unable to close BufferedReader for " + file.getPath(), e);
        }
      }
    }

    return fileContentsBuilder.toString();
  }