private void onOK() {
    try {
      InputStream in = new FileInputStream(inputFile);
      if (outputFile == null) {
        outputFile = new File(inputFile.getAbsolutePath() + "_");
      }
      OutputStream out = new FileOutputStream(outputFile);

      ANSIUnicodeConverter converter = new ANSIUnicodeConverter();
      converter.setDirection(ANSIUnicodeConverter.ANSI2UNICODE);
      StringBuffer output = new StringBuffer();

      final int BUFFER_SIZE = 1024 * 1024; // 1M
      byte[] buffer = new byte[BUFFER_SIZE];
      int currentPosition = 0;
      while (in.available() != 0) {
        int currentBufferSize = BUFFER_SIZE;
        if (in.available() < BUFFER_SIZE) {
          currentBufferSize = in.available();
        }
        in.read(buffer, currentPosition, currentBufferSize);
        currentBufferSize = currentBufferSize + currentBufferSize;
        converter.setInput(new String(buffer));

        out.write(converter.convert().getBytes());
      }

      in.close();
      out.close();
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
Exemplo n.º 2
2
 public String sendCommand(Session session, String Command) {
   StringBuilder result = new StringBuilder();
   try {
     Channel channel = session.openChannel("exec");
     ((ChannelExec) channel).setCommand(Command);
     InputStream in = channel.getInputStream();
     channel.connect();
     byte[] tmp = new byte[1024];
     boolean allow = true;
     while (allow) {
       while (in.available() > 0) {
         int i = in.read(tmp, 0, 1024);
         if (i < 0) break;
         result.append(new String(tmp, 0, i));
       }
       if (channel.isClosed()) {
         if (in.available() > 0) continue;
         System.out.println("exit-status: " + channel.getExitStatus());
         break;
       }
     }
     channel.disconnect();
     return result.toString();
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Exemplo n.º 3
1
 public void imprimePrompt() throws IOException {
   try {
     byte[] tmp = new byte[1024];
     while (true) {
       while (in.available() > 0) {
         int i = in.read(tmp, 0, 1024);
         if (i < 0) {
           break;
         }
         System.out.print(new String(tmp, 0, i));
       }
       if (this.channel.isClosed()) {
         if (in.available() > 0) {
           continue;
         }
         System.out.println("exit-status: " + this.channel.getExitStatus());
         break;
       }
       try {
         Thread.sleep(1000);
       } catch (Exception ee) {
       }
     }
   } catch (Exception e) {
     System.out.println(e);
   }
 }
Exemplo n.º 4
1
  public String receive(long timeout) throws IOException {

    if (inputStream == null) {
      String msg =
          "This device ("
              + this.getName()
              + ") is not working because IO objects are null. "
              + "You should restart the device!";
      Logger.getLogger(SerialDevice.class.getName()).log(Level.SEVERE, msg);
      throw new IOException(msg);
    } else {
      long time = System.currentTimeMillis();
      while (inputStream.available() == 0 && System.currentTimeMillis() - time < timeout) ;

      int available = inputStream.available();
      if (available == 0) {
        // inputStream.close();
        return null;
      } else {
        byte chunk[] = new byte[available];
        inputStream.read(chunk, 0, available);
        String retorno = new String(chunk);
        inputStream.close();
        return retorno;
      }
    }
  }
    @Override
    public WindowedValue<T> next() throws IOException {
      Windmill.Message message =
          context.getWork().getMessageBundles(bundleIndex).getMessages(messageIndex);
      if (messageIndex >= context.getWork().getMessageBundles(bundleIndex).getMessagesCount() - 1) {
        messageIndex = 0;
        bundleIndex++;
      } else {
        messageIndex++;
      }
      Instant timestampMillis = new Instant(TimeUnit.MICROSECONDS.toMillis(message.getTimestamp()));
      InputStream data = message.getData().newInput();
      InputStream metadata = message.getMetadata().newInput();
      Collection<? extends BoundedWindow> windows =
          WindmillSink.decodeMetadataWindows(windowsCoder, message.getMetadata());
      PaneInfo pane = WindmillSink.decodeMetadataPane(message.getMetadata());
      if (valueCoder instanceof KvCoder) {
        KvCoder<?, ?> kvCoder = (KvCoder<?, ?>) valueCoder;
        InputStream key = context.getSerializedKey().newInput();
        notifyElementRead(key.available() + data.available() + metadata.available());

        @SuppressWarnings("unchecked")
        T result =
            (T) KV.of(decode(kvCoder.getKeyCoder(), key), decode(kvCoder.getValueCoder(), data));
        return WindowedValue.of(result, timestampMillis, windows, pane);
      } else {
        notifyElementRead(data.available() + metadata.available());
        return WindowedValue.of(decode(valueCoder, data), timestampMillis, windows, pane);
      }
    }
  public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    int size;
    InputStream f = new FileInputStream("FileInputStreamDemo.java");

    System.out.println("Total Available Bytes: " + (size = f.available()));
    int n = size / 40;
    System.out.println("First " + n + "bytes of the file one read() at a time");

    for (int i = 0; i < n; i++) {
      System.out.print(f.read());
    }

    System.out.println("\nStill Available: " + f.available());
    System.out.println("Reading the next " + n + "with one read(b[])");

    byte b[] = new byte[n];
    if (f.read(b) != n) {
      System.err.println("couldn't read " + n + "bytes.");
    }
    System.out.println(new String(b, 0, n));
    System.out.println("\nStill Available: " + n + (size = f.available()));
    System.out.println("Skipping half of remaining bytes with skip()");
    f.skip(size / 2);
    System.out.println("Still Available: " + (size = f.available()));
    System.out.println("Reading " + n / 2 + "into the end of array");
    if (f.read(b, n / 2, n / 2) != n / 2) {
      System.err.println("couldn't read " + n / 2 + " bytes");
    }
    System.out.println(new String(b, 0, b.length));
    System.out.println("\nStill Available: " + f.available());
    f.close();
  }
Exemplo n.º 7
1
 /**
  * Parses a property list from an InputStream. It can either be in XML or binary format.
  *
  * @param is The InputStream delivering the property list data
  * @return The root object of the property list
  * @throws Exception If an error occurred while parsing.
  */
 public static NSObject parse(InputStream is) throws Exception {
   if (is.markSupported()) {
     is.mark(10);
     byte[] magic = new byte[8];
     is.read(magic);
     is.reset();
     String magic_string = new String(magic);
     if (magic_string.startsWith("bplist00")) {
       return BinaryPropertyListParser.parse(is);
     } else if (magic_string.startsWith("<?xml")) {
       return XMLPropertyListParser.parse(is);
     } else {
       throw new UnsupportedOperationException(
           "The given data is neither a binary nor a XML property list. ASCII property lists are not supported.");
     }
   } else {
     if (is.available() > Runtime.getRuntime().freeMemory()) {
       throw new Exception(
           "To little heap space available! Wanted to read "
               + is.available()
               + " bytes, but only "
               + Runtime.getRuntime().freeMemory()
               + " are available.");
     }
     byte[] buf = new byte[is.available()];
     is.read(buf);
     is.close();
     return parse(buf);
   }
 }
Exemplo n.º 8
0
  @Override
  public synchronized void readInputStream(InputStream inputStream) throws Exception {
    List<Byte> listStream = new ArrayList<Byte>();

    this.dataInputStream = new StringBuilder();

    int sizeStream = inputStream.available();

    while (sizeStream > 0) {

      while (sizeStream > 0) {
        final int ready = inputStream.read();
        this.dataInputStream.append((char) (byte) ready);
        listStream.add((byte) ready);

        sizeStream--;
      }

      sizeStream = inputStream.available();
    }

    this.byteStream = new byte[listStream.size()];

    for (int i = 0; i < listStream.size(); i++) {
      this.byteStream[i] = listStream.get(i);
    }
  }
Exemplo n.º 9
0
  /**
   * Requests data from RaspberryPi
   *
   * @return String returned from RaspberryPi
   * @throws IOException
   */
  public synchronized String getRawData() throws IOException {
    byte[] input;

    if (m_connected) {
      m_os.write('G'); // request Data
      System.out.println("Requested Data");

      if (m_is.available() <= bufferSize) {
        input = new byte[m_is.available()]; // storage space sized to fit!
        m_receivedData = new byte[m_is.available()];
        m_is.read(input);
        for (int i = 0; (i < input.length) && (input != null); i++) {
          m_receivedData[i] = input[i]; // transfer input to full size storage
        }
      } else {
        System.out.println("PI OVERFLOW");
        m_is.skip(m_is.available()); // reset if more is stored than buffer
        return null;
      }

      m_rawData = ""; // String to transfer received data to
      System.out.println("Raw Data: " + m_receivedData.length);
      for (int i = 0; i < m_receivedData.length; i++) {
        m_rawData +=
            (char) m_receivedData[i]; // Cast bytes to chars and concatenate them to the String
      }
      System.out.println(m_rawData);
      return m_rawData;
    } else {
      connect();
      return null;
    }
  }
  private byte[] toBytes(InputStream is) {
    byte[] retval = new byte[0];
    try {
      int a = is.available();
      while (a > 0) {
        byte[] buffer = new byte[a];
        is.read(buffer);

        byte[] newretval = new byte[retval.length + a];

        for (int i = 0; i < retval.length; i++) {
          newretval[i] = retval[i]; // old part
        }
        for (int i = 0; i < a; i++) {
          newretval[retval.length + i] = buffer[i]; // new part
        }

        retval = newretval;

        a = is.available(); // see what's left
      }
      return retval;
    } catch (Exception e) {
      System.out.println(
          BaseMessages.getString(PKG, "KettleURLClassLoader.Exception.UnableToReadClass")
              + e.toString());
      return null;
    }
  }
Exemplo n.º 11
0
 public String streamtostring(InputStream is) {
   // convert response to string
   try {
     int length;
     if (is.available() > 0) length = is.available();
     else length = 1;
     BufferedReader reader = new BufferedReader(new InputStreamReader(is), length);
     StringBuilder sb = new StringBuilder();
     String line = null;
     while ((line = reader.readLine()) != null) {
       sb.append(line);
     }
     String result = sb.toString();
     is.close();
     reader = null;
     sb = null;
     Log.e("Received data", "" + result);
     this.result = result;
     return result;
   } catch (Exception e) {
     Log.e("log_tag", "Error converting result " + e.toString());
     e.printStackTrace();
     return null;
   }
 }
Exemplo n.º 12
0
  /**
   * Read the next chunk. This method always tries to create an item of size maxMsgSize (taking
   * encoding into account). This behavior is justified by the assumption that the engine does not
   * try to split an item on a message partially filled.
   *
   * @return the number of bytes read, or -1 on end of file.
   */
  public int read() throws IOException {

    if (Log.isLoggable(Log.TRACE)) {
      Log.trace(TAG_LOG, "read");
    }

    if (is == null) {
      throw new IOException("Cannot read from null input stream");
    }

    chunkNumber++;

    // Now read chunkSize bytes
    int available = (int) is.available();
    if (available < chunkMaxSize) {
      chunkContent = new byte[available];
    } else {
      chunkContent = new byte[chunkMaxSize];
    }

    if (Log.isLoggable(Log.TRACE)) {
      Log.trace(TAG_LOG, "reading " + chunkContent.length);
    }
    int chunkSize = is.read(chunkContent);
    if (Log.isLoggable(Log.TRACE)) {
      Log.trace(TAG_LOG, "actually read " + chunkSize);
    }
    if (is.available() == 0) {
      last = true;
    }
    return chunkSize;
  }
Exemplo n.º 13
0
    public OutputStream ExecuteHttpAsStream(KZHttpMethod method) throws Exception
    {
        HttpURLConnection con = CreateConnectionThatHandlesRedirects(method);
        if (method ==KZHttpMethod.POST || method ==KZHttpMethod.PUT && mBodyAsStream !=null) {
            con.setDoOutput(true);

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;

            DataOutputStream dos = new DataOutputStream( con.getOutputStream() );
            bytesAvailable = mBodyAsStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = mBodyAsStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = mBodyAsStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = mBodyAsStream.read(buffer, 0, bufferSize);
            }
            mBodyAsStream.close();
            dos.flush();
            dos.close();
        }


        LastResponseCode = con.getResponseCode();
        LastResponseMessage = con.getResponseMessage();

        if (LastResponseCode>= HttpStatus.SC_BAD_REQUEST)
        {
            LastResponseBody = Utilities.convertStreamToString(con.getErrorStream());
            return null;
        }
        else
        {
            int dataRead = 0;
            int CHUNK_SIZE = 8192;                   // TCP/IP packet size
            byte[] dataChunk = new byte[CHUNK_SIZE]; // byte array for storing temporary data.

            OutputStream fos = new ByteArrayOutputStream();

            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
            InputStreamReader isr = new InputStreamReader( bis );
            while (dataRead >= 0)
            {
                dataRead = bis.read(dataChunk,0,CHUNK_SIZE);
                // only write out if there is data to be read
                if ( dataRead > 0 ) {
                    fos.write(dataChunk, 0, dataRead);
                }
            }
            bis.close();
            fos.close();
            return fos;
        }
    }
Exemplo n.º 14
0
 /**
  * First checks that in.available <= lengthMax, throwing an IllegalStateException if that
  * constraint is not obeyed, since otherwise drain cannot work. Then checks that
  * bufferSizeDrainMin <= lengthMax, returning lengthMax if that condition is not obeyed, since the
  * result should never exceed lengthMax.
  *
  * <p>Assuming those checks are passed, then returns <code>
  * Math.max(in.available(), {@link #bufferSizeDrainMin})</code>. In other words, the result is
  * normally the amount of data available on the stream except when that value is too small, in
  * which case a min value is returned instead.
  *
  * <p>The reason why the amount of data available on the stream should normally be returned is to
  * handle InputStreams where the length should static and fully determinable by calling the
  * InputStream's available method (e.g. InputStreams from files). In this case, {@link
  * #drain(InputStream)} should be extremely efficient because only a single buffer need be used
  * with no further allocations or copying.
  *
  * <p>The reason why you need bufferSizeDrainMin to establish a lower bound is because some
  * InputStreams (e.g. from sockets) cannot return an accurate value for the eventual amount of
  * data that will be read.
  *
  * <p>
  *
  * @throws IOException if an I/O problem occurs
  * @throws IllegalStateException if in.available() > lengthMax
  */
 private static int calcBufferSize(InputStream in, int lengthMax)
     throws IOException, IllegalStateException {
   if (in.available() > lengthMax)
     throw new IllegalStateException(
         "in.available() = " + in.available() + " > lengthMax = " + lengthMax);
   else if (bufferSizeDrainMin > lengthMax) return lengthMax;
   else return Math.max(in.available(), bufferSizeDrainMin);
 }
Exemplo n.º 15
0
 @Test
 public void getInputStream() throws Exception {
   InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("1.dat"));
   assertThat(inputStream.available()).isEqualTo(1);
   assertThat(inputStream.read()).isEqualTo(1);
   assertThat(inputStream.available()).isEqualTo(0);
   assertThat(inputStream.read()).isEqualTo(-1);
 }
  // add ---wangzhixin----2009/07/21  start
  public boolean processFile() {
    if (checkData()) {
      try {
        long time = System.currentTimeMillis();
        // BaseConfig tBaseConfig=new BaseConfig();
        // ProductCombinationDef
        // tProductCombinationDef=(ProductCombinationDef)tBaseConfig.getValue("productCombinationDef", "requestScope");
        // String fileName =tProductCombinationDef.getRiskCode()+".jpg";
        // String fileName = new File(upfile.getName()).getName();
        String fileName = new File(upfile.getName()).getName();
        String endwith = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        fileName = simpleDateFormat.format(new Date()) + "." + endwith;

        this.myFile = fileName;
        System.out.println(fileName);
        InputStream in = upfile.getInputStream();
        if (limitSize(in.available())) {
          return false;
        }
        // (double)((double)in.available()/1024/1024)
        System.out.println(".............." + in.available());
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpSession hs = (HttpSession) ctx.getExternalContext().getSession(true);
        String directory = hs.getServletContext().getRealPath("/") + "/upload";
        directory.replace("\\", "/");
        System.out.println("directory....." + directory);
        directory.replace("\\", "/");
        File fileDir = new File(directory);
        if (!fileDir.exists()) {
          if (!fileDir.mkdir()) {
            System.out.println("文件夹创建失败");
          }
        }
        String file = hs.getServletContext().getRealPath("/") + "/upload/" + fileName;
        // this.action(fileName, file);
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buffer = new byte[1024 * 2];
        int length;
        while ((length = in.read(buffer, 0, buffer.length)) > 0) {
          out.write(buffer, 0, length);
        }
        out.flush();
        out.close();
        copyFileToFront(fileName, file); // 将条款拷贝到前台一份  add by fengzg 2009-06-16

        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    } else {
      return false;
    }
  }
  private void acceptUpload() throws IOException {
    try {
      Socket sock = UploadGateKeeper.accept();
      sock.setReceiveBufferSize(BufferSize);
      sock.setSendBufferSize(BufferSize);
      sock.setSoTimeout(1000);
      System.out.println("client connected");
      InputStream in_stream = sock.getInputStream();
      while (in_stream.available() == 0) {
        Thread.sleep(10);
      }
      if (in_stream.available() == 23) {
        // Policy file...
        byte[] req = new byte[in_stream.available()];
        in_stream.read(req);
        String request = new String(req, "UTF-8");
        OutputStream out = sock.getOutputStream();
        out.write(CrossDomainFile.getBytes("UTF-8"));
        out.flush();
        out.close();
        sock.close();
        System.out.println("policy done");
        return;
      }
      byte[] size_buff = new byte[8];
      in_stream.read(size_buff);
      // Size...
      long size = Helper.bytesToLong(size_buff);
      System.out.println("File size: " + size);
      byte[] name_size_buff = new byte[2];
      in_stream.read(name_size_buff);
      int name_size = Helper.bytesToInt(name_size_buff);
      byte[] name_buff = new byte[name_size];
      in_stream.read(name_buff);
      // Name...
      String name = new String(name_buff, "UTF-8");
      System.out.println("File name: " + name);

      byte[] param_size_buff = new byte[2];
      in_stream.read(param_size_buff);
      int param_size = Helper.bytesToInt(param_size_buff);
      byte[] param_buff = new byte[param_size];
      in_stream.read(param_buff);
      // Params...
      String params = new String(param_buff, "UTF-8");
      System.out.println("File params: " + params);
      FileUploadProcessorItem item =
          new FileUploadProcessorItem(sock, Path, size, name, params, StartID);
      UploadItems.put(StartID, item);
      StartID++;
    } catch (SocketTimeoutException toex) {
      // System.out.println("Time out");
    } catch (Exception ex) {
      System.out.println(Helper.getStackTraceString(ex));
    }
  }
 @Test
 public void getInputStreamReadAll() throws Exception {
   this.os.write(helloBytes);
   InputStream inputStream = this.os.getInputStream();
   byte[] actual = new byte[inputStream.available()];
   int bytesRead = inputStream.read(actual);
   assertEquals(bytesRead, helloBytes.length);
   assertArrayEquals(actual, helloBytes);
   assertEquals(0, inputStream.available());
 }
Exemplo n.º 19
0
  public int read() throws IOException {
    if (m_Record == null) {
      if (m_Stream.available() == 0) {
        return -1;
      }
      Vector<Integer> v = new Vector<Integer>();
      if (m_bHeaderVariable) {
        m_tbyHeader[0] = (byte) m_Stream.read();
        m_tbyHeader[1] = (byte) m_Stream.read();
        m_tbyHeader[2] = (byte) m_Stream.read();
        m_tbyHeader[3] = (byte) m_Stream.read();
        int nLengthExcludingHeader = LittleEndingSignBinaryBufferStorage.readInt(m_tbyHeader, 0);
        for (int i = 0; i < nLengthExcludingHeader; i++) {
          v.add(m_Stream.read());
        }
        m_Stream.read();
      } else {
        if (m_nLength == 0) {
          int b = m_Stream.read();
          while (b != '\n' && b != -1) {
            v.add(b);
            b = m_Stream.read();
          }
        } else {
          for (int i = 0; i < m_nLength; i++) {
            v.add(m_Stream.read());
          }
          m_Stream.read();
        }
      }

      m_Record = new int[v.size() + 3];
      if (m_Stream.available() == 0) {
        m_Record[0] = 64;
      } else {
        m_Record[0] = 128;
      }
      m_Record[1] = v.size() / 256;
      m_Record[2] = v.size() % 256;
      for (int i = 0; i < v.size(); i++) {
        m_Record[i + 3] = v.get(i);
      }
      m_nCurrentRecordRead = 0;
    }

    int b = m_Record[m_nCurrentRecordRead];
    m_nCurrentRecordRead++;
    if (m_nCurrentRecordRead == m_Record.length) {
      m_Record = null;
      m_nCurrentRecordRead = 0;
    }

    return b;
  }
 @Override
 public int available() throws IOException {
   if (currentStream != null) {
     return currentStream.available();
   }
   moveToNextInputStream();
   if (currentStream != null) {
     return currentStream.available();
   }
   return 4096;
 }
Exemplo n.º 21
0
  @Test
  public void availableAtEnd() throws IOException {
    int i;

    for (i = 0; i < m_expect.length; i++) {
      assertEquals(m_expect.length - i, m_input.available());
      assertEquals(m_expect[i] & 0x0FF, m_input.read());
    }

    assertEquals(0, m_input.available());
  }
Exemplo n.º 22
0
  private static Message readMessage(final InputStream socketInput) throws Exception {

    for (int i = 0; socketInput.available() == 0 && i < 5; ++i) {
      Thread.sleep(i * i * 10);
    }

    if (socketInput.available() == 0) {
      return null;
    }

    return (Message) new ObjectInputStream(socketInput).readObject();
  }
Exemplo n.º 23
0
  private int readCmdAck(InputStream is) throws IOException {
    int sz = 0;
    String s = "";
    long startTime = System.currentTimeMillis();
    do {
      int len = is.available();
      if (len > 0) {
        int c = is.read();
        if (isTokenChar(c)) {
          s = "" + (char) c;
          sz = 1;
          break;
        }
      }

      if ((System.currentTimeMillis() - startTime) > timeout) {
        throw new IOException("response timeouted");
      }
    } while (true);

    do {
      int len = is.available();
      if (len > 0) {
        s += (char) is.read();
        sz++;
        if (sz == RESP_DONE_SZ && s.equals(RESP_DONE_STR)) {
          return RESP_DONE;
        }
        if (sz == RESP_OUT_OF_RANGE_SZ && s.equals(RESP_OUT_OF_RANGE_STR)) {
          return RESP_OUT_OF_RANGE;
        }
        if (sz == RESP_UNKNOWN_COMMAND_SZ && s.equals(RESP_UNKNOWN_COMMAND_STR)) {
          return RESP_UNKNOWN_COMMAND;
        }
        if (sz == RESP_ALERT_LEFT_SZ && s.equals(RESP_ALERT_LEFT_STR)) {
          return RESP_ALERT_LEFT;
        }
        if (sz == RESP_ALERT_RIGHT_SZ && s.equals(RESP_ALERT_RIGHT_STR)) {
          return RESP_ALERT_RIGHT;
        }
        if (sz == RESP_ALERT_BACK_SZ && s.equals(RESP_ALERT_BACK_STR)) {
          return RESP_ALERT_BACK;
        }
        if (sz == RESP_ALERT_FRONT_SZ && s.equals(RESP_ALERT_FRONT_STR)) {
          return RESP_ALERT_FRONT;
        }
        if (sz == RESP_ERROR_SZ && s.equals(RESP_ERROR_STR)) {
          return RESP_ERROR;
        }
      }
    } while ((System.currentTimeMillis() - startTime) < timeout);
    throw new IOException("response timeouted");
  }
Exemplo n.º 24
0
 @Test
 public void testAvailable() throws Exception {
   Message m = new Message();
   m.i = 10;
   InputStream is = marshaller.stream(m);
   assertEquals(is.available(), new TSerializer().serialize(m).length);
   is.read();
   assertEquals(is.available(), new TSerializer().serialize(m).length - 1);
   while (is.read() != -1) {}
   assertEquals(-1, is.read());
   assertEquals(0, is.available());
 }
Exemplo n.º 25
0
  /**
   * 从本地文件加载图片
   *
   * @author [email protected] 2014-5-19 下午2:15:23
   * @param filename
   * @param reqWidth
   * @param reqHeight
   * @param cache
   * @return Bitmap
   */
  public Bitmap decodeSampledBitmapFromFile(
      String url, String filename, int reqWidth, int reqHeight, ImageCache cache) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Coding coding = ImageLoadManager.instance().getCoding();
    if (coding == null || isDecode == false) {
      BitmapFactory.decodeFile(filename, options);
    } else if (isDecode && coding != null) {
      try {
        InputStream in = new FileInputStream(filename);
        byte[] buffer;
        if (url.toLowerCase().indexOf(".jpg") != -1) {
          buffer = coding.decodeJPG(in.available(), in);
        } else {
          buffer = coding.decodePNG(in.available(), in);
        }
        in.close();
        BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
        buffer = null;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    if (Utils.hasHoneycomb()) {
      addInBitmapOptions(options, cache);
    }

    options.inJustDecodeBounds = false;

    if (coding == null || isDecode == false) {
      return BitmapFactory.decodeFile(filename, options);
    } else if (isDecode && coding != null) {
      try {
        InputStream in = new FileInputStream(filename);
        byte[] buffer;
        if (url.toLowerCase().indexOf(".jpg") != -1) {
          buffer = coding.decodeJPG(in.available(), in);
        } else {
          buffer = coding.decodePNG(in.available(), in);
        }
        in.close();
        return BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return null;
  }
Exemplo n.º 26
0
  public void drainErrorStream() {
    try {
      while (processErrorStream.available() > 0) {
        int bufferSize = processErrorStream.available();
        byte[] errorReadingBuffer = new byte[bufferSize];

        processErrorStream.read(errorReadingBuffer, 0, bufferSize);

        LOG.info("Got error from shell process: " + new String(errorReadingBuffer));
      }
    } catch (Exception e) {
    }
  }
Exemplo n.º 27
0
  public static int doWaitFor(Process p) {
    int exitValue = -1; // returned to caller when p is finished
    try {

      InputStream in = p.getInputStream();
      InputStream err = p.getErrorStream();
      boolean finished = false; // Set to true when p is finished

      while (!finished) {
        try {
          while (in.available() > 0) {
            // Print the output of our system call
            Character c = new Character((char) in.read());
            if (log.isDebugEnabled()) {
              log.debug(c);
            }
          }
          while (err.available() > 0) {
            // Print the output of our system call
            Character c = new Character((char) err.read());
            if (log.isDebugEnabled()) {
              log.debug(c);
            }
          }

          // Ask the process for its exitValue. If the process
          // is not finished, an IllegalThreadStateException
          // is thrown. If it is finished, we fall through and
          // the variable finished is set to true.
          exitValue = p.exitValue();
          finished = true;
        } catch (IllegalThreadStateException e) {
          Thread.currentThread();
          // Process is not finished yet;
          // Sleep a little to save on CPU cycles
          Thread.sleep(500);
        }
      }
    } catch (Exception e) {
      // unexpected exception! print it out for debugging...
      if (log.isErrorEnabled()) {
        log.error("doWaitFor(): unexpected exception - " + e.getMessage());
      }
      if (log.isErrorEnabled()) {
        log.error(e.getMessage());
      }
    }
    // return completion status to caller
    return exitValue;
  }
Exemplo n.º 28
0
  /**
   * Get an internal response to a crafted URL
   *
   * @param rawUrl the raw url with encoded GET params
   */
  public static String getResponseForUrl(String rawUrl) throws Exception {
    URL url = new URL(rawUrl);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    while (is.available() != 0) {
      byte[] data = new byte[is.available()];
      is.read(data);
      bos.write(data);
      // do more here like check the syntax of the output
    }
    return bos.toString();
  }
Exemplo n.º 29
0
 private String getVersions() throws Exception {
   String rawURL = "http://localhost:8080" + Service.PREFIX + "/list";
   String urn = Utils.escape(docID);
   rawURL = calliope.URLEncoder.append(rawURL, urn);
   URL url = new URL(rawURL);
   URLConnection conn = url.openConnection();
   InputStream is = conn.getInputStream();
   StringBuilder sb = new StringBuilder();
   while (is.available() != 0) {
     byte[] data = new byte[is.available()];
     is.read(data);
     sb.append(new String(data));
   }
   return sb.toString();
 }
  /**
   * Load an entire resource text file into {@link String}.
   *
   * @param path the path to the resource file.
   * @return the entire content of the resource text file.
   */
  private String getResourceDocumentContent(String path) {
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);

    if (in != null) {
      try {
        StringBuffer content = new StringBuffer(in.available());

        InputStreamReader isr = new InputStreamReader(in);
        try {
          BufferedReader reader = new BufferedReader(isr);
          for (String str = reader.readLine(); str != null; str = reader.readLine()) {
            content.append(str);
            content.append('\n');
          }
        } finally {
          isr.close();
        }

        return content.toString();
      } catch (IOException e) {
        // No resource file as been found or there is a problem when read it.
      }
    }

    return null;
  }