예제 #1
1
    /** Returns true if the two InputStreams differ. */
    private static boolean differs(InputStream oldIS, InputStream newIS) throws IOException {
      int newSize = 0;
      int oldSize;
      int total = 0;
      boolean retVal = false;

      try {
        while (newSize != -1) {
          newSize = newIS.read(newBytes);
          oldSize = oldIS.read(oldBytes);

          if (newSize != oldSize) {
            if (_debug) {
              System.out.println(
                  "\tread sizes differ: " + newSize + " " + oldSize + " total " + total);
            }
            retVal = true;
            break;
          }
          if (newSize > 0) {
            while (--newSize >= 0) {
              total++;
              if (newBytes[newSize] != oldBytes[newSize]) {
                if (_debug) {
                  System.out.println("\tbytes differ at " + total);
                }
                retVal = true;
                break;
              }
              if (retVal) {
                // Jump out
                break;
              }
              newSize = 0;
            }
          }
        }
      } catch (IOException ioE) {
        throw ioE;
      } finally {
        try {
          oldIS.close();
        } catch (IOException e) {
          // Ignore
        }
        try {
          newIS.close();
        } catch (IOException e) {
          // Ignore
        }
      }
      return retVal;
    }
예제 #2
1
  // tokenizes a string for PBM and PGM headers and plain PBM and PGM data.  If oneChar is true,
  // then
  // rather than parsing a whole string, a single character is read (not including whitespace or
  // comments)
  static String tokenizeString(InputStream stream, boolean oneChar) throws IOException {
    final int EOF = -1;

    StringBuilder b = new StringBuilder();
    int c;
    boolean inComment = false;

    while (true) {
      c = stream.read();
      if (c == EOF)
        throw new IOException(
            "Stream ended prematurely, before table reading was completed."); // no more tokens
      else if (inComment) {
        if (c == '\r' || c == '\n') // escape the comment
        inComment = false;
        else {
        } // do nothing
      } else if (Character.isWhitespace((char) c)) {
      } // do nothing
      else if (c == '#') // start of a comment
      {
        inComment = true;
      } else // start of a string
      {
        b.append((char) c);
        break;
      }
    }

    if (oneChar) return b.toString();

    // at this point we have a valid string.  We read until whitespace or a #
    while (true) {
      c = stream.read();
      if (c == EOF) break;
      else if (c == '#') // start of comment, read until a '\n'
      {
        while (true) {
          c = stream.read(); // could hit EOF, which is fine
          if (c == EOF) break;
          else if (c == '\r' || c == '\n') break;
        }
        // break;   // comments are not delimiters
      } else if (Character.isWhitespace((char) c)) break;
      else b.append((char) c);
    }
    return b.toString();
  }
예제 #3
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;
   }
 }
예제 #4
1
  public void publicizeResources(File arscFile) throws AndrolibException {
    byte[] data = new byte[(int) arscFile.length()];

    InputStream in = null;
    OutputStream out = null;
    try {
      in = new FileInputStream(arscFile);
      in.read(data);

      publicizeResources(data);

      out = new FileOutputStream(arscFile);
      out.write(data);
    } catch (IOException ex) {
      throw new AndrolibException(ex);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ex) {
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException ex) {
        }
      }
    }
  }
  public AuthenticatedSocket(InetAddress ia, int port, MessageDigest md, byte[] secret)
      throws IOException, AuthenticationException {
    super(ia, port);

    try {
      OutputStream output = this.getOutputStream();
      InputStream input = this.getInputStream();

      // Get challenge length
      byte[] challengeSize = new byte[4];
      input.read(challengeSize);

      // Receive random challenge string
      byte[] challenge = new byte[Bytes.toInt(challengeSize)];
      input.read(challenge);

      // Generate MD5 hash
      byte[] append = Bytes.append(challenge, secret);
      byte[] hash = md.digest(append);

      // Send time and hash strings
      output.write(hash);
    } catch (Exception e) {
      throw new AuthenticationException("Authentication failed: " + e.getMessage());
    }
  }
예제 #6
0
파일: GetVersion.java 프로젝트: fin-nick/fj
  // #sijapp cond.if (protocols_MRIM is "true") or (protocols_VK is "true") or (protocols_ICQ is
  // "true") #
  private byte[] read(InputStream in, int length) throws IOException {
    if (0 == length) {
      return null;
    }
    if (0 < length) {
      byte[] bytes = new byte[length];
      int readCount = 0;
      while (readCount < bytes.length) {
        int c = in.read(bytes, readCount, bytes.length - readCount);
        if (-1 == c) break;
        readCount += c;
      }
      return bytes;
    }

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    for (int i = 0; i < 100 * 1024; ++i) {
      int ch = in.read();
      if (-1 == ch) break;
      bytes.write(ch);
    }
    byte[] content = bytes.toByteArray();
    bytes.close();
    return content;
  }
예제 #7
0
 private static Object readValue(InputStream is, ClassLoader loader) throws Exception {
   byte type = (byte) is.read();
   if (type == -1) {
     return null;
   }
   Class vClass = null;
   if (type == 2) {
     int length = PDataStream.readInt(is);
     Vector v = new Vector(length);
     for (int i = 0; i < length; i++) {
       v.insertElementAt(readValue(is, loader), i);
     }
     return v;
   } else if (type == 0) {
     return readRealObject((byte) is.read(), is, loader);
   } else {
     int length = PDataStream.readInt(is);
     boolean primitive = PDataStream.readBoolean(is);
     if (primitive) {
       return readPrimitiveArray(length, is);
     }
     vClass =
         loader == null
             ? Class.forName(PDataStream.readUTF(is))
             : loader.loadClass(PDataStream.readUTF(is));
     Object array = Array.newInstance(vClass, length);
     for (int i = 0; i < length; i++) {
       Array.set(array, i, readValue(is, loader));
     }
     return array;
   }
 }
예제 #8
0
    /** Returns true if the two InputStreams differ. */
    private static boolean differs(InputStream oldIS, InputStream newIS) throws IOException {
      int newSize = 0;
      int oldSize;
      int total = 0;

      while (newSize != -1) {
        newSize = newIS.read(newBytes);
        oldSize = oldIS.read(oldBytes);

        if (newSize != oldSize) {
          if (_debug) {
            System.out.println(
                "\tread sizes differ: " + newSize + " " + oldSize + " total " + total);
          }
          return true;
        }
        if (newSize > 0) {
          while (--newSize >= 0) {
            total++;
            if (newBytes[newSize] != oldBytes[newSize]) {
              if (_debug) {
                System.out.println("\tbytes differ at " + total);
              }
              return true;
            }
          }
          newSize = 0;
        }
      }
      return false;
    }
예제 #9
0
  /**
   * Reads a base class overrride from a resource file
   *
   * @param binaryClassName
   * @param fileName
   */
  private void registerBaseClassOverride(String binaryClassName, String fileName) {
    try {
      Method mDefineClass =
          ClassLoader.class.getDeclaredMethod(
              "defineClass", String.class, byte[].class, int.class, int.class);
      mDefineClass.setAccessible(true);

      InputStream resourceInputStream =
          LiteLoader.class.getResourceAsStream("/classes/" + fileName + ".bin");

      if (resourceInputStream != null) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        for (int readBytes = resourceInputStream.read();
            readBytes >= 0;
            readBytes = resourceInputStream.read()) {
          outputStream.write(readBytes);
        }

        byte[] data = outputStream.toByteArray();

        outputStream.close();
        resourceInputStream.close();

        logger.info("Defining class override for " + binaryClassName);
        mDefineClass.invoke(
            Minecraft.class.getClassLoader(), binaryClassName, data, 0, data.length);
      } else {
        logger.info("Error defining class override for " + binaryClassName + ", file not found");
      }
    } catch (Throwable th) {
      logger.log(Level.WARNING, "Error defining class override for " + binaryClassName, th);
    }
  }
예제 #10
0
  /**
   * Gives the same basic functionality of File.exists but can be used to look for removable media
   * without showing a system dialog if the media is not present. Workaround pulled from the <A
   * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on
   * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start
   * requiring Java 6.
   */
  protected static boolean fileExists(File file) {
    try {
      Process process =
          Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()});

      // We need to consume all available output or the process will block.
      boolean haveExitCode = false;
      int exitCode = -1;
      InputStream out = process.getInputStream();
      InputStream err = process.getErrorStream();

      while (!haveExitCode) {
        while (out.read() >= 0) {}
        while (err.read() >= 0) {}

        try {
          exitCode = process.exitValue();
          haveExitCode = true;
        } catch (IllegalThreadStateException e) {
          // Not yet complete.
          Thread.sleep(100);
        }
      }
      // int exitCode = process.waitFor();
      return exitCode == 0;

    } catch (IOException e) {
      System.out.println("Unable to check for file: " + file + " : " + e);
      return false;

    } catch (InterruptedException e) {
      System.out.println("Unable to check for file.  Interrupted: " + file + " : " + e);
      return false;
    }
  }
예제 #11
0
  public static void ensureExists(File thing, String resource) {
    System.err.println("configfile = " + thing);
    if (!thing.exists()) {
      try {
        System.err.println("Creating: " + thing + " from " + resource);
        if (resource.indexOf("/") != 0) {
          resource = "/" + resource;
        }

        InputStream is = Config.class.getResourceAsStream(resource);
        if (is == null) {
          throw new NullPointerException("Can't find resource: " + resource);
        }
        getParentFile(thing).mkdirs();
        OutputStream os = new FileOutputStream(thing);

        for (int next = is.read(); next != -1; next = is.read()) {
          os.write(next);
        }

        os.flush();
        os.close();
      } catch (FileNotFoundException fnfe) {
        throw new Error("Can't create resource: " + fnfe.getMessage());
      } catch (IOException ioe) {
        throw new Error("Can't create resource: " + ioe.getMessage());
      }
    }
  }
예제 #12
0
 public static void saveURL(URL url, OutputStream os) throws IOException {
   InputStream is = url.openStream();
   byte[] buf = new byte[1048576];
   int n = is.read(buf);
   while (n != -1) {
     os.write(buf, 0, n);
     n = is.read(buf);
   }
 }
예제 #13
0
  // Loads raw PGM files after the first-line header is stripped
  static int[][] loadRawPGM(InputStream stream) throws IOException {
    int width = tokenizeInt(stream);
    int height = tokenizeInt(stream);
    int maxVal = tokenizeInt(stream);
    if (width < 0) throw new IOException("Invalid width: " + width);
    if (height < 0) throw new IOException("Invalid height: " + height);
    if (maxVal <= 0) throw new IOException("Invalid maximum value: " + maxVal);

    // this single whitespace character will have likely already been consumed by reading maxVal
    // stream.read();  // must be a whitespace

    int[][] field = new int[width][height];
    for (int i = 0; i < height; i++)
      for (int j = 0; j < width; j++) {
        if (maxVal < 256) // one byte
        field[j][i] = stream.read();
        else if (maxVal < 65536) // two bytes
        field[j][i] =
              (stream.read() << 8) & stream.read(); // two bytes, most significant byte first
        else if (maxVal < 16777216) // three bytes -- this is nonstandard
        field[j][i] =
              (stream.read() << 16)
                  & (stream.read() << 8)
                  & stream.read(); // three bytes, most significant byte first
        else // four bytes -- this is nonstandard
        field[j][i] =
              (stream.read() << 24)
                  & (stream.read() << 16)
                  & (stream.read() << 8)
                  & stream.read(); // three bytes, most significant byte first
      }

    return field;
  }
예제 #14
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String filePickerResult = "";
    if (data != null && resultCode == RESULT_OK) {
      try {
        ContentResolver cr = getContentResolver();
        Uri uri = data.getData();
        Cursor cursor =
            GeckoApp.mAppContext
                .getContentResolver()
                .query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null);
        String name = null;
        if (cursor != null) {
          try {
            if (cursor.moveToNext()) {
              name = cursor.getString(0);
            }
          } finally {
            cursor.close();
          }
        }
        String fileName = "tmp_";
        String fileExt = null;
        int period;
        if (name == null || (period = name.lastIndexOf('.')) == -1) {
          String mimeType = cr.getType(uri);
          fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType);
        } else {
          fileExt = name.substring(period);
          fileName = name.substring(0, period);
        }
        File file = File.createTempFile(fileName, fileExt, sGREDir);

        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = cr.openInputStream(uri);
        byte[] buf = new byte[4096];
        int len = is.read(buf);
        while (len != -1) {
          fos.write(buf, 0, len);
          len = is.read(buf);
        }
        fos.close();
        filePickerResult = file.getAbsolutePath();
      } catch (Exception e) {
        Log.e(LOG_FILE_NAME, "showing file picker", e);
      }
    }
    try {
      mFilePickerResult.put(filePickerResult);
    } catch (InterruptedException e) {
      Log.i(LOG_FILE_NAME, "error returning file picker result", e);
    }
  }
예제 #15
0
 private static Object readPrimitiveArray(int length, InputStream is) throws IOException {
   byte type = (byte) is.read();
   if (type == 1) {
     int[] ints = new int[length];
     for (int i = 0; i < length; i++) {
       ints[i] = PDataStream.readInt(is);
     }
     return ints;
   } else if (type == 2) {
     long[] longs = new long[length];
     for (int i = 0; i < length; i++) {
       longs[i] = PDataStream.readLong(is);
     }
     return longs;
   } else if (type == 3) {
     byte[] bytes = new byte[length];
     is.read(bytes);
     return bytes;
   } else if (type == 4) {
     boolean[] booleans = new boolean[length];
     for (int i = 0; i < length; i++) {
       booleans[i] = PDataStream.readBoolean(is);
     }
     return booleans;
   } else if (type == 5) {
     char[] chars = new char[length];
     for (int i = 0; i < length; i++) {
       chars[i] = PDataStream.readChar(is);
     }
     return chars;
   } else if (type == 6) {
     short[] shorts = new short[length];
     for (int i = 0; i < length; i++) {
       shorts[i] = PDataStream.readShort(is);
     }
     return shorts;
   } else if (type == 7) {
     float[] floats = new float[length];
     for (int i = 0; i < length; i++) {
       floats[i] = PDataStream.readFloat(is);
     }
     return floats;
   } else if (type == 8) {
     double[] doubles = new double[length];
     for (int i = 0; i < length; i++) {
       doubles[i] = PDataStream.readDouble(is);
     }
     return doubles;
   } else {
     throw new IllegalArgumentException("Trying to read unsupported primitive type: " + type);
   }
 }
예제 #16
0
파일: Signer.java 프로젝트: JSlain/bnd
 private void digest(MessageDigest[] algorithms, Resource r) throws Exception {
   InputStream in = r.openInputStream();
   byte[] data = new byte[BUFFER_SIZE];
   int size = in.read(data);
   while (size > 0) {
     for (int a = 0; a < algorithms.length; a++) {
       if (algorithms[a] != null) {
         algorithms[a].update(data, 0, size);
       }
     }
     size = in.read(data);
   }
 }
예제 #17
0
  private static void writeEntry(JarOutputStream jos, JarEntry entry, InputStream data)
      throws IOException {
    jos.putNextEntry(entry);

    // Read the entry
    int size = data.read(newBytes);

    while (size != -1) {
      jos.write(newBytes, 0, size);
      size = data.read(newBytes);
    }
    data.close();
  }
  /**
   * Puts the uninstaller.
   *
   * @exception Exception Description of the Exception
   */
  private void putUninstaller() throws Exception {
    // Me make the .uninstaller directory
    String dest = translatePath("$INSTALL_PATH") + File.separator + "Uninstaller";
    String jar = dest + File.separator + "uninstaller.jar";
    File pathMaker = new File(dest);
    pathMaker.mkdirs();

    // We log the uninstaller deletion information
    UninstallData udata = UninstallData.getInstance();
    udata.setUninstallerJarFilename(jar);
    udata.setUninstallerPath(dest);

    // We open our final jar file
    FileOutputStream out = new FileOutputStream(jar);
    ZipOutputStream outJar = new ZipOutputStream(out);
    idata.uninstallOutJar = outJar;
    outJar.setLevel(9);
    udata.addFile(jar);

    // We copy the uninstaller
    InputStream in = getClass().getResourceAsStream("/res/IzPack.uninstaller");
    ZipInputStream inRes = new ZipInputStream(in);
    ZipEntry zentry = inRes.getNextEntry();
    while (zentry != null) {
      // Puts a new entry
      outJar.putNextEntry(new ZipEntry(zentry.getName()));

      // Byte to byte copy
      int unc = inRes.read();
      while (unc != -1) {
        outJar.write(unc);
        unc = inRes.read();
      }

      // Next one please
      inRes.closeEntry();
      outJar.closeEntry();
      zentry = inRes.getNextEntry();
    }
    inRes.close();

    // We put the langpack
    in = getClass().getResourceAsStream("/langpacks/" + idata.localeISO3 + ".xml");
    outJar.putNextEntry(new ZipEntry("langpack.xml"));
    int read = in.read();
    while (read != -1) {
      outJar.write(read);
      read = in.read();
    }
    outJar.closeEntry();
  }
예제 #19
0
 /**
  * Reloads a frequency table as saved by saveTable
  *
  * @return the table
  */
 public static int[] loadTable(InputStream in) {
   try {
     int l = in.read();
     l |= (in.read() << 8);
     byte[] tbl = new byte[l];
     for (int i = 0; i < tbl.length; i++) {
       tbl[i] = (byte) in.read();
     }
     return expandTable(tbl);
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
예제 #20
0
파일: IOUtil.java 프로젝트: jajorda/jbenchx
  /**
   * Compares the contents of two streams by reading them.
   *
   * <p>NOTE: The streams get closed in any case.
   *
   * @param contents1 the first content stream
   * @param contents2 the second content stream
   * @return true iff both stream had the same length and the same data
   * @throws IOException if an I/O exception occurs while reading one of the streams
   */
  public static boolean hasSameContents(InputStream contents1, InputStream contents2)
      throws IOException {
    try {
      int bufSize = 10000;
      byte[] buffer1 = new byte[bufSize];
      byte[] buffer2 = new byte[bufSize];

      boolean eof1 = false;
      boolean eof2 = false;
      while (!eof1 && !eof2) {

        int pos1 = 0;
        while (pos1 != bufSize) {
          int count = contents1.read(buffer1, pos1, bufSize - pos1);
          if (count == -1) {
            eof1 = true;
            break;
          }
          pos1 += count;
        }

        int pos2 = 0;
        while (pos2 != bufSize) {
          int count = contents2.read(buffer2, pos2, bufSize - pos2);
          if (count == -1) {
            eof2 = true;
            break;
          }
          pos2 += count;
        }

        if (eof1 || eof2) {
          if (pos1 != pos2 || !firstBytesEquals(buffer1, buffer2, pos1)) {
            return false;
          }
        } else {
          if (!Arrays.equals(buffer1, buffer2)) {
            return false;
          }
        }
      }

      return true;
    } finally {
      IOUtil.closeSilently(contents1);
      IOUtil.closeSilently(contents2);
    }
  }
예제 #21
0
 byte[] getJar(String address) {
   // System.out.println("getJar: "+address);
   byte[] data;
   try {
     URL url = new URL(address);
     IJ.showStatus("Connecting to " + IJ.URL);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len);
     if (len <= 0) return null;
     String name = address.contains("wsr") ? "daily build (" : "ij.jar (";
     IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     if (IJ.debugMode) IJ.log("" + e);
     return null;
   }
   if (IJ.debugMode) IJ.wait(6000);
   return data;
 }
예제 #22
0
  public static String getResTxtContent(ClassLoader cl, String p) throws IOException {
    String s = res2txt_cont.get(p);
    if (s != null) return s;

    InputStream is = null;
    try {
      is = cl.getResourceAsStream(p);
      // is = this.getClass().getResourceAsStream(p);
      if (is == null) return null;

      byte[] buf = new byte[1024];
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len;
      while ((len = is.read(buf)) >= 0) {
        baos.write(buf, 0, len);
      }

      byte[] cont = baos.toByteArray();
      s = new String(cont, "UTF-8");

      res2txt_cont.put(p, s);
      return s;
    } finally {
      if (is != null) is.close();
    }
  }
예제 #23
0
  public static void renderFile(
      HttpServletResponse resp,
      String filename,
      InputStream cont_stream,
      boolean showpic,
      boolean ignorespace)
      throws IOException {
    if (cont_stream == null) return;

    if (ignorespace) filename = filename.replace(" ", "");

    if (!showpic)
      resp.addHeader(
          "Content-Disposition",
          "attachment; filename=" + new String(filename.getBytes(), "iso8859-1"));

    resp.setContentType(Mime.getContentType(filename));
    ServletOutputStream os = resp.getOutputStream();
    byte[] buf = new byte[1024];
    int len = 0;
    while ((len = cont_stream.read(buf)) != -1) {
      os.write(buf, 0, len);
    }

    os.flush();
  }
예제 #24
0
 /**
  * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a
  * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string
  * buffer to use ** @throws IOException if an error occurs or the server has stopped
  */
 protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb)
     throws IOException {
   if (socket != null) {
     int dataLen = 0;
     StringBuffer data = (sb != null) ? sb : new StringBuffer();
     InputStream input = socket.getInputStream();
     while ((maxLen < 0) || (maxLen > dataLen)) {
       int ch = input.read();
       // Print.logInfo("ReadLine char: " + ch);
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else if (ch == LineTerminatorChar) {
         // include line terminator in String
         data.append((char) ch);
         dataLen++;
         break;
       } else {
         // append character
         data.append((char) ch);
         dataLen++;
       }
     }
     return data.toString();
   } else {
     return null;
   }
 }
예제 #25
0
 void handleRequest(InputStream in, OutputStream out) throws IOException {
   boolean newline = false;
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       throw new EOFException();
     }
     sb.append((char) ch);
     if (ch == '\r') {
       // empty
     } else if (ch == '\n') {
       if (newline) {
         // 2nd newline in a row, end of request
         break;
       }
       newline = true;
     } else {
       newline = false;
     }
   }
   String request = sb.toString();
   if (request.startsWith("GET / HTTP/1.") == false) {
     throw new IOException("Invalid request: " + request);
   }
   out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
 }
예제 #26
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
예제 #27
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;
  }
 @NotNull
 public static byte[] adaptiveLoadBytes(@NotNull InputStream stream) throws IOException {
   byte[] bytes = new byte[4096];
   List<byte[]> buffers = null;
   int count = 0;
   int total = 0;
   while (true) {
     int n = stream.read(bytes, count, bytes.length - count);
     if (n <= 0) break;
     count += n;
     if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + stream);
     total += n;
     if (count == bytes.length) {
       if (buffers == null) {
         buffers = new ArrayList<byte[]>();
       }
       buffers.add(bytes);
       int newLength = Math.min(1024 * 1024, bytes.length * 2);
       bytes = new byte[newLength];
       count = 0;
     }
   }
   byte[] result = new byte[total];
   if (buffers != null) {
     for (byte[] buffer : buffers) {
       System.arraycopy(buffer, 0, result, result.length - total, buffer.length);
       total -= buffer.length;
     }
   }
   System.arraycopy(bytes, 0, result, result.length - total, total);
   return result;
 }
예제 #29
0
 private void copy(InputStream in, OutputStream out) throws IOException {
   final byte[] buf = new byte[10000];
   int read;
   while ((read = in.read(buf)) > 0) {
     out.write(buf, 0, read);
   }
 }
예제 #30
0
  /**
   * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file.
   *
   * @param f The jar file to extract from.
   * @return a temporary file to which the plugin.xml file has been copied.
   */
  public static File unpackPluginXML(File f) {
    InputStream in = null;
    OutputStream out = null;

    try {
      JarFile jar = new JarFile(f);
      ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE);
      if (entry == null) {
        return null;
      }
      File dest = File.createTempFile("jabref_plugin", ".xml");
      dest.deleteOnExit();

      in = new BufferedInputStream(jar.getInputStream(entry));
      out = new BufferedOutputStream(new FileOutputStream(dest));
      byte[] buffer = new byte[2048];
      for (; ; ) {
        int nBytes = in.read(buffer);
        if (nBytes <= 0) break;
        out.write(buffer, 0, nBytes);
      }
      out.flush();
      return dest;
    } catch (IOException ex) {
      ex.printStackTrace();
      return null;
    } finally {
      try {
        if (out != null) out.close();
        if (in != null) in.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }