示例#1
1
 /**
  * Construct a frequency table from an InputStream. This will create a temporary file to copy the
  * InputStream in.
  *
  * @param source the Input Stream
  * @return an InputStream which is a copy of the source Stream, provided to re-Read the same Bytes
  *     for the actual compression process.
  */
 public InputStream constructTable(InputStream source, boolean copy) {
   freq = new int[TABLESIZE];
   try {
     File file = null;
     FileOutputStream fos = null;
     if (copy == true) {
       file = File.createTempFile("huf", "tmp");
       file.deleteOnExit();
       fos = new FileOutputStream(file);
     }
     while (source.available() != 0) {
       int c = source.read();
       freq[c]++;
       if (copy) fos.write(c);
     }
     source.close();
     if (copy) {
       fos.close();
       return new FileInputStream(file);
     }
     return null;
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
示例#2
1
 public void run(String local, String remote, InputStream pin, OutputStream pout) {
   try {
     microphone = SoundMixerEnumerator.getInputLine(pcmformat, DefaultPhonePCMBlockSize);
   } catch (LineUnavailableException lue) {
     System.out.println(
         "\3b"
             + getClass().getName()
             + ".<init>:\n\tCould not create microphone input stream.\n\t"
             + lue);
   }
   try {
     speaker = SoundMixerEnumerator.getOutputLine(pcmformat, DefaultPhonePCMBlockSize);
   } catch (LineUnavailableException lue) {
     microphone.close();
     System.out.println(
         "\3b"
             + getClass().getName()
             + ".<init>:\n\tCould not create speaker output stream.\n\t"
             + lue);
   }
   if ((speaker == null) || (microphone == null)) {
     super.run(local, remote, pin, pout);
     return;
   }
   try {
     recorder = new Recorder(pout);
     recorder.start();
     gui = openMonitorGUI("Remote " + remote + " Local " + local);
     pin.skip(pin.available()); // waste whatever we couldn't process in time
     super.run(local, remote, new PhoneCallMonitorInputStream(pin), pout);
     recorder.interrupt();
     gui.dispose();
   } catch (Exception e) {
     System.out.println("3\b" + getClass().getName() + ".run:\n\t" + e);
     e.printStackTrace();
   } finally {
     deactivate();
     microphone.close();
     speaker.close();
     if (gui != null) {
       gui.dispose();
     }
   }
 }
 private String getStringFromStreamSource(StreamSource src, int length) throws Exception {
   byte buf[] = null;
   if (src == null) return null;
   InputStream outStr = src.getInputStream();
   if (outStr != null) {
     int len = outStr.available();
     if (outStr.markSupported()) outStr.reset();
     buf = new byte[len];
     outStr.read(buf, 0, len);
     // System.out.println("From inputstream: "+new String(buf));
     return new String(buf);
   } else {
     char buf1[] = new char[length];
     Reader r = src.getReader();
     if (r == null) return null;
     r.reset();
     r.read(buf1);
     // System.out.println("From Reader: "+new String(buf));
     return new String(buf1);
   }
 }
示例#4
0
  private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name)
      throws IOException, FileNotFoundException {
    if (fileEntry == null) fileEntry = zip.getEntry(name);
    if (fileEntry == null)
      throw new FileNotFoundException("Can't find " + name + " in " + zip.getName());

    File outFile = new File(sGREDir, name);
    if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize())
      return false;

    File dir = outFile.getParentFile();
    if (!dir.exists()) dir.mkdirs();

    InputStream fileStream;
    fileStream = zip.getInputStream(fileEntry);

    OutputStream outStream = new FileOutputStream(outFile);

    while (fileStream.available() > 0) {
      int read = fileStream.read(buf, 0, buf.length);
      outStream.write(buf, 0, read);
    }

    fileStream.close();
    outStream.close();
    outFile.setLastModified(fileEntry.getTime());
    return true;
  }
 @Transactional
 public DeviceTestData parseAndSaveBBIFile(
     InputStream inputStream, String verificationID, String originalFileName)
     throws IOException, DecoderException {
   BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
   bufferedInputStream.mark(inputStream.available());
   DeviceTestData deviceTestData =
       bbiFileService.parseBbiFile(bufferedInputStream, originalFileName);
   bufferedInputStream.reset();
   calibratorService.uploadBbi(bufferedInputStream, verificationID, originalFileName);
   return deviceTestData;
 }
示例#6
0
 /**
  * compute a frequency table from an InputStream and save a compacted representation of this table
  * in the system preferences. (To be used later by @see #useStandardTable(String) )
  *
  * @param name name to give the table.
  * @param in InputStream
  * @return true on success
  * @throws Exception
  */
 public static boolean CreateStandardTableFromStream(String name, InputStream in)
     throws Exception {
   int[] tbl = new int[TABLESIZE];
   while (in.available() != 0) {
     int c = in.read();
     tbl[c]++;
   }
   byte[] dest = HuffmanTree.compactTable(tbl);
   Preferences pref = Preferences.userNodeForPackage(Huff.class);
   Preferences node = pref.node("StandardTables");
   node.putByteArray(name, dest);
   pref.flush();
   return true;
 }
  /**
   * Returns the byte representation of the image corresponding to the given identifier.
   *
   * @param imageID the identifier of the image
   * @return the byte representation of the image corresponding to the given identifier.
   */
  private static byte[] getImageInBytes(String imageID) {
    InputStream in = getResources().getImageInputStream(imageID);

    if (in == null) return null;
    byte[] image = null;
    try {
      image = new byte[in.available()];

      in.read(image);
    } catch (IOException e) {
      logger.error("Failed to load image:" + imageID, e);
    }

    return image;
  }
 private static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
     throws IOException {
   try {
     int bufferOffset = 0;
     long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
     while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
       int readLength = java.lang.Math.min(is.available(), b.length - bufferOffset);
       int readResult = is.read(b, bufferOffset, readLength);
       if (readResult == -1) break;
       bufferOffset += readResult;
     }
     return bufferOffset;
   } catch (IOException ex) {
     Loggers.SERVER.error("Error reading stream. Stream closed: " + ex);
     return -1;
   }
 }
 /** Write the given resource as an http response body. */
 public boolean write(String filename, HttpExchange t) throws IOException {
   InputStream stream = getInputStream(filename);
   if (stream != null) {
     Headers headers = t.getResponseHeaders();
     if (!headers.containsKey("Content-Type")) {
       String mime = getContentType(filename);
       if (mime != null) {
         headers.add("Content-Type", mime);
       }
     }
     // Note: available() isn't officially guaranteed to return the full
     // stream length but effectively seems to do so in our context.
     t.sendResponseHeaders(200, stream.available());
     dump(stream, t.getResponseBody());
     return true;
   }
   return false;
 }
 /**
  * Returns the given input stream as a byte array
  *
  * @param stream the stream to get as a byte array
  * @param length the length to read from the stream or -1 for unknown
  * @return the given input stream as a byte array
  * @throws IOException
  */
 public static byte[] getInputStreamAsByteArray(InputStream stream, int length)
     throws IOException {
   byte[] contents;
   if (length == -1) {
     contents = new byte[0];
     int contentsLength = 0;
     int amountRead = -1;
     do {
       // read at least 8K
       int amountRequested = Math.max(stream.available(), 8192);
       // resize contents if needed
       if (contentsLength + amountRequested > contents.length) {
         System.arraycopy(
             contents,
             0,
             contents = new byte[contentsLength + amountRequested],
             0,
             contentsLength);
       }
       // read as many bytes as possible
       amountRead = stream.read(contents, contentsLength, amountRequested);
       if (amountRead > 0) {
         // remember length of contents
         contentsLength += amountRead;
       }
     } while (amountRead != -1);
     // resize contents if necessary
     if (contentsLength < contents.length) {
       System.arraycopy(contents, 0, contents = new byte[contentsLength], 0, contentsLength);
     }
   } else {
     contents = new byte[length];
     int len = 0;
     int readSize = 0;
     while ((readSize != -1) && (len != length)) {
       // See PR 1FMS89U
       // We record first the read size. In this case length is the actual
       // read size.
       len += readSize;
       readSize = stream.read(contents, len, length - len);
     }
   }
   return contents;
 }
示例#11
0
 public byte[] getBytes(String className) {
   try {
     Tracer.mark();
     String realName = className.replace(".", "/");
     realName += ".class";
     JarEntry je = jf.getJarEntry(realName);
     InputStream is = jf.getInputStream(je);
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     byte[] buff = new byte[4096];
     while (is.available() > 0) {
       int read = is.read(buff);
       baos.write(buff, 0, read);
     }
     is.close();
     return baos.toByteArray();
   } catch (Exception e) {
   } finally {
     Tracer.unmark();
   }
   return null;
 }
示例#12
0
  /*
   * Read a single pair of (X,Y) values from the ADXL202EVB board.
   * TODO: Better return value, or declare as throwing exception for errs
   */
  public static double[] chipRead() {
    double[] retval = {0.0, 0.0};
    byte[] rawBuf = {0, 0, 0, 0};
    int[] vals = {0, 0};

    try {
      // Read is triggered by sending 'G' to board
      outputStream.write('G');

      // Wait for all 4 result bytes to arrive
      // TODO: Finite wait w/error return if data never arrives
      while (inputStream.available() < 4) {
        Thread.sleep(1);
      }

      inputStream.read(rawBuf, 0, 4);

      // Convert from raw bytes to 16-bit signed integers, carefully
      Byte bTmp = new Byte(rawBuf[0]);
      vals[0] = bTmp.intValue() * 256;
      bTmp = new Byte(rawBuf[1]);
      vals[0] += bTmp.intValue();

      bTmp = new Byte(rawBuf[2]);
      vals[1] = bTmp.intValue() * 256;
      bTmp = new Byte(rawBuf[3]);
      vals[1] += bTmp.intValue();

      // See ADXL202EVB specs for details on conversion
      retval[0] = (((vals[0] / 100.0) - 50.0) / 12.5);
      retval[1] = (((vals[1] / 100.0) - 50.0) / 12.5);

      System.out.println("X: " + retval[0] + " Y: " + retval[1]);

    } catch (Exception ioe) {
      System.out.println("Error on data transmission");
    }
    return (retval);
  }
示例#13
0
 public int available() throws IOException {
   return is.available();
 }
示例#14
0
 @Override
 public int available() throws IOException {
   return in.available();
 }
示例#15
0
 String ReadFromStream() throws IOException {
   String s = new String("");
   while ((is.available() > 0) && (s.length() < 255)) s = s + String.valueOf((char) is.read());
   System.out.println("Read: " + s);
   return s;
 }
示例#16
0
 /*////////////////////////////
 private AssetManager getAssets() {
 	// TODO Auto-generated method stub
 	return null;
 }
 */
 static int VxCopyAsssetToSdcard(
     String strFileSrc,
     String strFileDest,
     AssetManager assetmanager,
     boolean bDontCopyIfExistsAndSameSize) {
   int iSrcFileSize = 0;
   int iDestFileSize = 0;
   InputStream oInputStream = null;
   OutputStream oOutputStream = null;
   // get src file size and stream
   try {
     oInputStream = assetmanager.open(strFileSrc);
     if (null != oInputStream) {
       iSrcFileSize = oInputStream.available();
     } else {
       Log.e("", "ERROR: VxCopyResourceToSdcard could not open file " + strFileSrc);
       return -1;
     }
   } catch (IOException e) {
     Log.e("", "ERROR: VxCopyResourceToSdcard could not open file " + strFileSrc);
     // TODO Auto-generated catch block
     e.printStackTrace();
     return -1;
   }
   if (bDontCopyIfExistsAndSameSize) {
     // get dest file size and stream
     try {
       InputStream oTmpStream = null;
       File readFile = new File(strFileDest);
       oTmpStream = new FileInputStream(readFile);
       ;
       if (null != oTmpStream) {
         iDestFileSize = oTmpStream.available();
         oTmpStream.close();
       } else {
         Log.e("", "ERROR: VxCopyAsssetToSdcard could not get size of file " + strFileDest);
         return -1;
       }
     } catch (IOException e) {
       Log.e("", "VxCopyAsssetToSdcard dest file doesnt exist.. will copy " + strFileSrc);
     }
   }
   if (bDontCopyIfExistsAndSameSize && (iSrcFileSize == iDestFileSize)) {
     Log.i("", "VxCopyAsssetToSdcard file exists " + strFileDest);
     return 0;
   }
   // Read the entire asset into a local byte buffer.
   byte[] buffer = new byte[iSrcFileSize];
   try {
     oInputStream.read(buffer);
     oInputStream.close();
   } catch (IOException e) {
     Log.e("", "ERROR: VxCopyAsssetToSdcard could not read file " + strFileSrc);
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   // write buffer to destination file
   try {
     File oWriteFile = new File(strFileDest);
     try {
       oWriteFile.createNewFile();
     } catch (IOException e) {
       Log.e("", "error creating file " + strFileDest, e);
       e.printStackTrace();
       return -1;
     }
     oOutputStream = new FileOutputStream(oWriteFile);
     // Don’t forget to close stream
     if (oOutputStream != null) {
       try {
         oOutputStream.write(buffer);
         oOutputStream.flush();
         oOutputStream.close();
         Log.i("", "Success copying file " + strFileDest + " size " + iSrcFileSize);
       } catch (IOException e) {
         Log.e("", "ERROR: VxCopyResourceToSdcard could not write file " + strFileDest);
         e.printStackTrace();
         return -1;
       }
     }
   } catch (IOException e) {
     Log.e("", "ERROR: VxCopyAsssetToSdcard could not read file " + strFileSrc);
     // TODO Auto-generated catch block
     e.printStackTrace();
     return -1;
   }
   return 0;
 }
示例#17
0
 /** Parse a manifest from a stream */
 public Manifest(InputStream is) throws IOException {
   while (is.available() != 0) {
     MessageHeader m = new MessageHeader(is);
     entries.addElement(m);
   }
 }
  public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
      try {
        int available = input.available();
        if (count < BUF_SIZE) {
          count =
              count
                  + input.read(
                      buf, count, (available > BUF_SIZE - count) ? BUF_SIZE - count : available);
        }

        start = newline;
        for (int i = newline; i <= count; i++) {
          if (buf[i] == 'U' || buf[i] == '$') { // start byte
            start = i;
            break;
          }
        }
        for (int i = start; i <= count; i++) {
          if (buf[i] == '\n') { // end byte
            newline = i;
            break;
          }
        }

        if (newline <= start) {
          if (count == BUF_SIZE) { // buf full an no valid datagram found, clear the buffer
            // need to copy the stuff after the start byte to the beginning
            if ((count - start) <= 128) {
              System.arraycopy(buf, start, buf, 0, count - start);
              count = count - start;
              start = 0;
              newline = 0;
            } else { // buf full and last start byte is more than max packet size clear all of the
                     // buffer
              count = 0; // no need to copy since the buf is grabage
              start = 0;
              newline = 0;
            }
          }
          return;
        }

        if (buf[start] == '$') {
          buf[newline] = '\0';
          System.out.println(new String(buf, start + 1, newline - start));
        }

        // found valid datagram
        // parse datagram comma delimited
        buf[newline] = ',';
        String newbuf = new String(buf, start, newline - start);
        StringTokenizer st = new StringTokenizer(newbuf, ",");
        int[] data = new int[5];

        int i = 0;
        while (st.hasMoreElements() && i < 5) {
          String temp = st.nextToken();
          try {
            data[i] = Integer.parseInt(temp, 16);
          } catch (NumberFormatException e) {
          }
          i++;
        }

        RobotEvent ev = new RobotEvent();
        int checksum;

        ev.setCommand(EventEnum.getEvent(data[1]));
        ev.setIndex((short) data[2]);
        ev.setValue((int) data[3]);
        checksum = data[4];

        int checksum2 =
            (int)
                (((int) (ev.getCommand().getValue() & 0x000000FF)
                        + (int) (ev.getIndex() & 0x000000FF)
                        + (int) (ev.getValue() & 0x000000FF)
                        + (int) ((ev.getValue() & 0x0000FF00) >> 8))
                    % 256);

        if (checksum2 == checksum) {
          // log event received
          recv.put(ev);
        }
      } catch (Exception e) {
      }
    }
  }