/**
  * Load UTF8withBOM or any ansi text file.
  *
  * @param filename
  * @return
  * @throws java.io.IOException
  */
 public static String loadFileAsString(String filename) throws java.io.IOException {
   final int BUFLEN = 1024;
   BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
     byte[] bytes = new byte[BUFLEN];
     boolean isUTF8 = false;
     int read, count = 0;
     while ((read = is.read(bytes)) != -1) {
       if (count == 0
           && bytes[0] == (byte) 0xEF
           && bytes[1] == (byte) 0xBB
           && bytes[2] == (byte) 0xBF) {
         isUTF8 = true;
         baos.write(bytes, 3, read - 3); // drop UTF8 bom marker
       } else {
         baos.write(bytes, 0, read);
       }
       count += read;
     }
     return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
   } finally {
     try {
       is.close();
     } catch (Exception ex) {
     }
   }
 }
示例#2
0
  /** execute method之后,取返回的inputstream */
  private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception {
    int statusCode = client.getResponseCode();
    if (statusCode != HttpURLConnection.HTTP_OK) {
      throw new EnvException("Method failed: " + statusCode);
    }
    InputStream in = client.getResponseStream();
    if (in == null) {
      return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      Utils.copyBinaryTo(in, out);

      // 看一下传过来的byte[]是不是DesignProcessor.INVALID,如果是的话,就抛Exception
      byte[] bytes = out.toByteArray();
      // carl:格式一致传中文
      String message = new String(bytes, EncodeConstants.ENCODING_UTF_8);
      if (ComparatorUtils.equals(message, RemoteDeziConstants.NO_SUCH_RESOURCE)) {
        return null;
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.INVALID_USER)) {
        throw new EnvException(RemoteDeziConstants.INVALID_USER);
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) {
        JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Designer_file-is-locked"));
        return null;
      } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) {
      }
      return new ByteArrayInputStream(bytes);
    } finally {
      in.close();
      out.close();
      client.release();
    }
  }
示例#3
0
  public void run() {

    byte[] tmp = new byte[10000];
    int read;
    try {
      FileInputStream fis = new FileInputStream(fileToSend.getFile());

      read = fis.read(tmp);
      while (read != -1) {
        baos.write(tmp, 0, read);
        read = fis.read(tmp);
        System.out.println(read);
      }
      fis.close();
      baos.writeTo(sWriter);
      sWriter.flush();
      baos.flush();
      baos.close();
      System.out.println("fileSent");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {

      this.closeSocket();
    }
  }
示例#4
0
  // callRestfulApi - Calls restful API and returns results as a string
  public String callRestfulApi(
      String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);

    try {
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      URL url = new URL(API_ROOT + addr);
      URLConnection urlConnection = url.openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
      }
      IOUtils.copy(urlConnection.getInputStream(), output);
      String newCookie = getConnectionInfiniteCookie(urlConnection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
      return output.toString();
    } catch (IOException e) {
      System.out.println(e.getMessage());
      return null;
    }
  } // TESTED
示例#5
0
 /**
  * Loads a resource from the classloader (e.g. the .jar file) into a byte array.
  *
  * @param cl Classloader resource comes from
  * @param sPath Path of resource (must begin with /)
  * @return Byte array containing file in memory
  * @throws IOException If it doesn't exist or there is any other error loading
  */
 public static byte[] loadResource(ClassLoader cl, String sPath) throws IOException {
   if (!sPath.startsWith("/"))
     throw new FileNotFoundException("Resource must be absolute path: " + sPath);
   sPath = sPath.substring(1);
   URL u = cl.getResource(sPath);
   if (u == null) throw new FileNotFoundException("Resource not found: " + sPath);
   URLConnection uc = u.openConnection();
   uc.connect();
   int iLength = uc.getContentLength();
   if (iLength > -1) // Sometimes getContentLength returns -1, sometimes it doesn't
   {
     byte[] abContent = new byte[iLength];
     InputStream is = uc.getInputStream();
     int iStart = 0;
     while (true) {
       int iRead = is.read(abContent, iStart, abContent.length - iStart);
       if (iRead == 0) throw new IOException("Resource length mismatch");
       iStart += iRead;
       if (iStart == abContent.length) break;
     }
     is.close();
     return abContent;
   } else {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     copy(uc.getInputStream(), baos, false);
     return baos.toByteArray();
   }
 }
  /** @throws IOException If failed. */
  private void initFavicon() throws IOException {
    assert favicon == null;

    InputStream in = getClass().getResourceAsStream("favicon.ico");

    if (in != null) {
      BufferedInputStream bis = new BufferedInputStream(in);

      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      try {
        byte[] buf = new byte[2048];

        while (true) {
          int n = bis.read(buf);

          if (n == -1) break;

          bos.write(buf, 0, n);
        }

        favicon = bos.toByteArray();
      } finally {
        U.closeQuiet(bis);
      }
    }
  }
  private Icon makeIcon(final String gifFile) throws IOException {
    /* Copy resource into a byte array.  This is
     * necessary because several browsers consider
     * Class.getResource a security risk because it
     * can be used to load additional classes.
     * Class.getResourceAsStream just returns raw
     * bytes, which we can convert to an image.
     */
    InputStream resource = MyImageView.class.getResourceAsStream(gifFile);

    if (resource == null) {
      System.err.println(MyImageView.class.getName() + "/" + gifFile + " not found!!.");
      return null;
    }
    BufferedInputStream in = new BufferedInputStream(resource);
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] buffer = new byte[1024];
    int n;
    while ((n = in.read(buffer)) > 0) {
      out.write(buffer, 0, n);
    }
    in.close();
    out.flush();

    buffer = out.toByteArray();
    if (buffer.length == 0) {
      System.err.println("warning: " + gifFile + " is zero-length");
      return null;
    }
    return new ImageIcon(buffer);
  }
 /**
  * compare the byte-array representation of two TaskObjects.
  *
  * @param f TaskObject
  * @param s TaskObject
  * @return true if the two arguments have the same byte-array
  */
 private boolean sameBytes(TaskObject f, TaskObject s) {
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   ObjectOutput out = null;
   try {
     out = new ObjectOutputStream(bos);
     out.writeObject(f);
     byte[] fs = bos.toByteArray();
     out.writeObject(s);
     byte[] ss = bos.toByteArray();
     if (fs.length != ss.length) return false;
     for (int i = 0; i < fs.length; i++) {
       if (fs[i] != ss[i]) return false;
     }
     return true;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
         // ignore
       }
       try {
         bos.close();
       } catch (IOException e) {
         // ignore
       }
     }
   }
 }
示例#9
0
  /**
   * 将用户反馈发送至服务器
   *
   * @param feedBackInfo 用户反馈
   * @return 发送成功返回true
   * @throws Exception 异常
   */
  public static boolean sendFeedBack(FeedBackInfo feedBackInfo) throws Exception {

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    // 把tableData写成xml文件到out
    DavXMLUtils.writeXMLFeedBackInfo(feedBackInfo, out);
    InputStream input = postBytes2ServerB(out.toByteArray());
    return input != null;
  }
示例#10
0
 /** Reads the chunk of data to be imported from the request's input stream. */
 private byte[] readChunk(HttpServletRequest req, int chunkSize) throws IOException {
   ServletInputStream requestStream = req.getInputStream();
   String contentType = req.getHeader(ProtocolConstants.HEADER_CONTENT_TYPE);
   if (contentType.startsWith("multipart")) // $NON-NLS-1$
   return readMultiPartChunk(requestStream, contentType);
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream(chunkSize);
   IOUtilities.pipe(requestStream, outputStream, false, false);
   return outputStream.toByteArray();
 }
示例#11
0
 /**
  * Read an InputStream into a byte array.
  *
  * @param is InputStream
  * @return byte array
  */
 public static byte[] inputStreamToByteArray(InputStream is) {
   try {
     final ByteArrayOutputStream os = new ByteArrayOutputStream();
     copyStream(new BufferedInputStream(is), os);
     os.close();
     return os.toByteArray();
   } catch (Exception e) {
     throw new OXFException(e);
   }
 }
示例#12
0
 /**
  * Computes the Base64 encoding of a string
  *
  * @param s a string
  * @return the Base 64 encoding of s
  */
 public static String base64Encode(String s) {
   ByteArrayOutputStream bOut = new ByteArrayOutputStream();
   Base64OutputStream out = new Base64OutputStream(bOut);
   try {
     out.write(s.getBytes());
     out.flush();
   } catch (IOException e) {
   }
   return bOut.toString();
 }
示例#13
0
 static byte[] Cmd_Finish() throws Exception {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream);
   writeInt(-1, dataoutputstream);
   dataoutputstream.writeByte(75);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeBytes("FINISH");
   dataoutputstream.writeByte(0);
   return bytearrayoutputstream.toByteArray();
 }
示例#14
0
 static byte[] Cmd_Challenge() throws Exception {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream);
   writeInt(-1, dataoutputstream);
   dataoutputstream.writeByte(74);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeBytes("CHALLENGE");
   dataoutputstream.writeByte(0);
   return bytearrayoutputstream.toByteArray();
 }
  public static int sizeInBytes(Object obj) throws IOException {
    ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteObject);
    objectOutputStream.writeObject(obj);
    objectOutputStream.flush();
    objectOutputStream.close();
    byteObject.close();

    return byteObject.toByteArray().length;
  }
示例#16
0
 static byte[] Cmd_Accept(int i) throws Exception {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream);
   writeInt(-1, dataoutputstream);
   dataoutputstream.writeByte(75);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeBytes("ACCEPT");
   dataoutputstream.writeByte(0);
   writeInt(i, dataoutputstream);
   return bytearrayoutputstream.toByteArray();
 }
示例#17
0
 static byte[] Cmd_Block(byte abyte0[]) throws Exception {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream);
   writeInt(-1, dataoutputstream);
   dataoutputstream.writeByte(75);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeBytes("BLOCK");
   dataoutputstream.writeByte(0);
   writeShort(abyte0.length, dataoutputstream);
   dataoutputstream.write(abyte0, 0, abyte0.length);
   return bytearrayoutputstream.toByteArray();
 }
示例#18
0
 static byte[] Cmd_File(int i, byte abyte0[]) throws Exception {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream);
   writeInt(-1, dataoutputstream);
   dataoutputstream.writeByte(75);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeBytes("FILE");
   dataoutputstream.writeByte(0);
   writeInt(i, dataoutputstream);
   dataoutputstream.write(abyte0, 0, abyte0.length);
   return bytearrayoutputstream.toByteArray();
 }
 private Class<?> getClassFromStream(
     final InputStream stream, final String classname, final File container)
     throws IOException, SecurityException {
   final ByteArrayOutputStream baos = new ByteArrayOutputStream();
   int bytesRead = -1;
   final byte[] buffer = new byte[8192];
   while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
     baos.write(buffer, 0, bytesRead);
   }
   final byte[] classData = baos.toByteArray();
   return this.defineClassFromData(container, classData, classname);
 }
示例#20
0
 static byte[] Cmd_Abort(String s) throws Exception {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream);
   writeInt(-1, dataoutputstream);
   dataoutputstream.writeByte(75);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeBytes("ABORT");
   dataoutputstream.writeByte(0);
   dataoutputstream.writeBytes(s);
   dataoutputstream.writeByte(0);
   return bytearrayoutputstream.toByteArray();
 }
示例#21
0
文件: IPCapture.java 项目: star003/sb
  public void run() {
    URL url;
    Base64Encoder base64 = new Base64Encoder();

    try {
      url = new URL(urlString);
    } catch (MalformedURLException e) {
      System.err.println("Invalid URL");
      return;
    }

    try {
      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass));
      httpIn = new BufferedInputStream(conn.getInputStream(), 8192);
    } catch (IOException e) {
      System.err.println("Unable to connect: " + e.getMessage());
      return;
    }

    int prev = 0;
    int cur = 0;

    try {
      while (keepAlive && (cur = httpIn.read()) >= 0) {
        if (prev == 0xFF && cur == 0xD8) {
          jpgOut = new ByteArrayOutputStream(8192);
          jpgOut.write((byte) prev);
        }
        if (jpgOut != null) {
          jpgOut.write((byte) cur);
        }
        if (prev == 0xFF && cur == 0xD9) {
          synchronized (curFrame) {
            curFrame = jpgOut.toByteArray();
          }
          frameAvailable = true;
          jpgOut.close();
        }
        prev = cur;
      }
    } catch (IOException e) {
      System.err.println("I/O Error: " + e.getMessage());
    }
    try {
      jpgOut.close();
      httpIn.close();
    } catch (IOException e) {
      System.err.println("Error closing streams: " + e.getMessage());
    }
    conn.disconnect();
  }
示例#22
0
  private byte[] readFully(InputStream istream) throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int num = 0;

    while ((num = istream.read(buf)) != -1) {
      bout.write(buf, 0, num);
    }

    byte[] ret = bout.toByteArray();

    return ret;
  }
示例#23
0
 public String getData() {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   try {
     getDrawing().getOutputFormats().get(0).write(out, getDrawing());
     return out.toString("UTF8");
   } catch (IOException e) {
     SVGTextFigure tf = new SVGTextFigure();
     tf.setText(e.getMessage());
     tf.setBounds(new Point2D.Double(10, 10), new Point2D.Double(100, 100));
     getDrawing().add(tf);
     e.printStackTrace();
     return "";
   }
 }
示例#24
0
文件: UDP.java 项目: NZDIS/jgroups
  byte[] messageToBuffer(Message msg) throws Exception {
    ObjectOutputStream out;
    // BufferedOutputStream bos;

    out_stream.reset();
    // bos=new BufferedOutputStream(out_stream);
    out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version
    // bos.write(Version.version_id, 0, Version.version_id.length); // write the version
    out = new ObjectOutputStream(out_stream);
    // out=new ObjectOutputStream(bos);
    msg.writeExternal(out);
    out.flush(); // needed if out buffers its output to out_stream
    return out_stream.toByteArray();
  }
示例#25
0
 static byte[] Cmd_AccessGranted(int i, byte byte0) throws Exception {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream);
   writeInt(-1, dataoutputstream);
   dataoutputstream.writeByte(78);
   dataoutputstream.writeByte(0);
   writeInt(i, dataoutputstream);
   dataoutputstream.writeByte(byte0);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeByte(0);
   dataoutputstream.writeByte(0);
   return bytearrayoutputstream.toByteArray();
 }
示例#26
0
 /** TIFF Adobe ZIP support contributed by Jason Newton. */
 public byte[] zipUncompress(byte[] input) {
   ByteArrayOutputStream imageBuffer = new ByteArrayOutputStream();
   byte[] buffer = new byte[1024];
   Inflater decompressor = new Inflater();
   decompressor.setInput(input);
   try {
     while (!decompressor.finished()) {
       int rlen = decompressor.inflate(buffer);
       imageBuffer.write(buffer, 0, rlen);
     }
   } catch (DataFormatException e) {
     IJ.log(e.toString());
   }
   decompressor.end();
   return imageBuffer.toByteArray();
 }
示例#27
0
  /** Internal method. Connect to searchd, send request, get response as DataInputStream. */
  private DataInputStream _DoRequest(int command, int version, ByteArrayOutputStream req) {
    /* connect */
    Socket sock = _Connect();
    if (sock == null) return null;

    /* send request */
    byte[] reqBytes = req.toByteArray();
    try {
      DataOutputStream sockDS = new DataOutputStream(sock.getOutputStream());
      sockDS.writeShort(command);
      sockDS.writeShort(version);
      sockDS.writeInt(reqBytes.length);
      sockDS.write(reqBytes);

    } catch (Exception e) {
      _error = "network error: " + e;
      _connerror = true;
      return null;
    }

    /* get response */
    byte[] response = _GetResponse(sock);
    if (response == null) return null;

    /* spawn that tampon */
    return new DataInputStream(new ByteArrayInputStream(response));
  }
 private Class findRawClass(String className) throws ClassNotFoundException {
   try {
     String resourcePath = className.replace('.', '/') + ".class";
     InputStream resourceStream = getResourceAsStream(resourcePath);
     ByteArrayOutputStream rawByteStream = new ByteArrayOutputStream();
     byte[] buf = new byte[4096];
     int bytesread = 0;
     while ((bytesread = resourceStream.read(buf)) >= 0) {
       rawByteStream.write(buf, 0, bytesread);
     }
     resourceStream.close();
     byte[] rawBytes = rawByteStream.toByteArray();
     return super.defineClass(className, rawBytes, 0, rawBytes.length);
   } catch (Exception exc) {
     throw new ClassNotFoundException(className, exc);
   }
 }
 /** Object: size = variable */
 public static byte[] objectToArray(Object s) {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     oos.writeObject(s);
     oos.close();
     baos.close();
     byte[] sb = baos.toByteArray();
     byte[] out = new byte[sb.length + 4];
     integerToArray(sb.length, out, 0);
     System.arraycopy(sb, 0, out, 4, sb.length);
     return out;
   } catch (IOException e) {
     e.printStackTrace();
     throw new RuntimeException("unable to serialize packet", e);
   }
 }
示例#30
0
 /**
  * Checks for the next item.
  *
  * @return result of check
  * @throws IOException I/O exception
  */
 public boolean more() throws IOException {
   if (cache == null) {
     out.write(4);
     send(id);
     cache = new ArrayList<byte[]>();
     final ByteArrayOutputStream os = new ByteArrayOutputStream();
     while (in.read() > 0) {
       receive(in, os);
       cache.add(os.toByteArray());
       os.reset();
     }
     if (!ok()) throw new IOException(receive());
     pos = 0;
   }
   if (pos < cache.size()) return true;
   cache = null;
   return false;
 }