/** Utility function for encoding a length as a BER byte sequence */ public static byte[] encodeLength(int length) { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); // see if can be represented in single byte // don't forget the first bit is the "long field test" bit!! if (length < 128) { byte[] len = {(byte) length}; outBytes.write(len, 0, 1); } else { // too big for one byte // see how many are needed: int numBytes = 0; int temp = length; while (temp > 0) { ++numBytes; temp = (int) Math.floor(temp / 256); } byte num = (byte) numBytes; num += 128; // set the "long format" bit outBytes.write(num); byte[] len = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; --i) { len[i] = (byte) (length % 256); length = (int) Math.floor(length / 256); } outBytes.write(len, 0, numBytes); } return outBytes.toByteArray(); }
/** * 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) { } } }
private byte[] readJpegData(DataInputStream in, byte marker) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(1024); // add the SOI marker back into it bout.write(0xFF); bout.write(SOI); boolean foundFF = false; while (in.available() > 0) { byte d = in.readByte(); if (foundFF) { if (d == marker) break; else { bout.write(0xFF); bout.write(d); foundFF = false; } } else if (d == (byte) 0xFF) { foundFF = true; } else { bout.write(d); } } return bout.toByteArray(); }
public void addPart(final String key, final String value) { writeFirstBoundaryIfNeeds(); try { out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n").getBytes()); out.write(value.getBytes()); out.write(("\r\n--" + boundary + "\r\n").getBytes()); } catch (final IOException e) { e.printStackTrace(); } }
public static byte[] decode(String str) { byte[] data = str.getBytes(); int len = data.length; ByteArrayOutputStream buf = new ByteArrayOutputStream(len); int i = 0; int b1, b2, b3, b4; while (i < len) { /* b1 */ do { b1 = base64DecodeChars[data[i++]]; } while (i < len && b1 == -1); if (b1 == -1) { break; } /* b2 */ do { b2 = base64DecodeChars[data[i++]]; } while (i < len && b2 == -1); if (b2 == -1) { break; } buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4))); /* b3 */ do { b3 = data[i++]; if (b3 == 61) { return buf.toByteArray(); } b3 = base64DecodeChars[b3]; } while (i < len && b3 == -1); if (b3 == -1) { break; } buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); /* b4 */ do { b4 = data[i++]; if (b4 == 61) { return buf.toByteArray(); } b4 = base64DecodeChars[b4]; } while (i < len && b4 == -1); if (b4 == -1) { break; } buf.write((int) (((b3 & 0x03) << 6) | b4)); } return buf.toByteArray(); }
/** * Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"}, this end of line marker * is not included in the result. * * @return the next line from the input. * @throws java.io.IOException for underlying {@code InputStream} errors. * @throws java.io.EOFException for the end of source stream. */ public String readLine() throws IOException { synchronized (in) { if (buf == null) { throw new IOException("LineReader is closed"); } // Read more data if we are at the end of the buffered data. // Though it's an error to read after an exception, we will let {@code fillBuf()} // throw again if that happens; thus we need to handle end == -1 as well as end == pos. if (pos >= end) { fillBuf(); } // Try to find LF in the buffered data and return the line if successful. for (int i = pos; i != end; ++i) { if (buf[i] == LF) { int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i; String res = new String(buf, pos, lineEnd - pos, charset.name()); pos = i + 1; return res; } } // Let's anticipate up to 80 characters on top of those already read. ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) { @Override public String toString() { int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count; try { return new String(buf, 0, length, charset.name()); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); // Since we control the charset this will never happen. } } }; while (true) { out.write(buf, pos, end - pos); // Mark unterminated line in case fillBuf throws EOFException or IOException. end = -1; fillBuf(); // Try to find LF in the buffered data and return the line if successful. for (int i = pos; i != end; ++i) { if (buf[i] == LF) { if (i != pos) { out.write(buf, pos, i - pos); } pos = i + 1; return out.toString(); } } } } }
/** * Convert binary data to a hex-encoded String * * @param b An array containing binary data * @return A String containing the encoded data */ public static String toString(byte[] b) { ByteArrayOutputStream os = new ByteArrayOutputStream(); for (int i = 0; i < b.length; i++) { short value = (short) (b[i] & 0xFF); byte high = (byte) (value >> 4); byte low = (byte) (value & 0xF); os.write(Base16.charAt(high)); os.write(Base16.charAt(low)); } return new String(os.toByteArray()); }
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(); }
/** Converts a String into a byte array. */ protected static byte[] byteArrayFromString(String s) throws TextParseException { byte[] array = s.getBytes(); boolean escaped = false; boolean hasEscapes = false; for (int i = 0; i < array.length; i++) { if (array[i] == '\\') { hasEscapes = true; break; } } if (!hasEscapes) { if (array.length > 255) { throw new TextParseException("text string too long"); } return array; } ByteArrayOutputStream os = new ByteArrayOutputStream(); int digits = 0; int intval = 0; for (int i = 0; i < array.length; i++) { byte b = array[i]; if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw new TextParseException("bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); os.write(b); escaped = false; } else if (array[i] == '\\') { escaped = true; digits = 0; intval = 0; } else os.write(array[i]); } if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); array = os.toByteArray(); if (array.length > 255) { throw new TextParseException("text string too long"); } return os.toByteArray(); }
/** * reads the content of an existing file using the current domain * * @param domain The namespace used to identify the application domain (1st level directory) to * use * @param path The path relative to the domain for the file * @param block The sequential block number for the data to be read starting with 1 * @param len The length of the block in bytes * @return The contents of the file */ public byte[] readFromFile(String path, int block, int len) { byte[] buffer = null; try { if (_isLocal) { File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path); if (tmpFile.isFile()) { RandomAccessFile in = new RandomAccessFile(tmpFile, "r"); in.seek((block - 1) * len); int result = -1; buffer = new byte[len]; if (in.getFilePointer() < in.length()) { result = in.read(buffer); ByteArrayOutputStream out = new ByteArrayOutputStream(result); out.write(buffer, 0, result); in.close(); return out.toByteArray(); } else { in.close(); } } } else { buffer = _remote.readFromFile(_domain, path, block, len); } } catch (Exception ex) { ex.printStackTrace(); } return buffer; }
/** Return the BER encoding of this object. */ protected byte[] getBEREncoding() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); byte type = SNMPBERCodec.SNMPUNKNOWNOBJECT; // calculate encoding for length of data byte[] len = SNMPBERCodec.encodeLength(data.length); // encode T,L,V info outBytes.write(type); outBytes.write(len, 0, len.length); outBytes.write(data, 0, data.length); return outBytes.toByteArray(); }
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(); } }
public static String postXml(String url, String xmlData) { HttpPost post = new HttpPost(url); InputStream is = null; ByteArrayOutputStream baos = null; try { StringEntity entity = new StringEntity(xmlData); post.setEntity(entity); post.setHeader("Content-Type", "text/xml;charset=UTF-8"); HttpResponse response = httpClient.execute(post); is = response.getEntity().getContent(); baos = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int count = is.read(data); while (count != -1) { baos.write(data, 0, count); count = is.read(data); } return baos.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (Exception ignore) { } if (baos != null) try { baos.close(); } catch (Exception ignore) { } } return null; }
public BufferedRequestWrapper(HttpServletRequest req, String body) throws IOException { super(req); InputStream is = req.getInputStream(); baos = new ByteArrayOutputStream(); baos.write(body.getBytes()); buffer = baos.toByteArray(); }
public static byte[] parse(String s) { if (s.equals("(null)")) { return null; } try { int n = s.length(); ByteArrayOutputStream out = new ByteArrayOutputStream(n / 3); StringReader r = new StringReader(s); while (true) { int b1 = nextNibble(r); if (b1 < 0) { break; } int b2 = nextNibble(r); if (b2 < 0) { throw new RuntimeException("Invalid string " + s); } int b = (b1 << 4) | b2; out.write(b); } return out.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } }
private static void copy(InputStream in, ByteArrayOutputStream buff) throws IOException { byte[] tmp = new byte[8]; int count; while ((count = in.read(tmp)) != -1) { buff.write(tmp, 0, count); } }
/** * Add the entries from the supplied {@link ZipInputStream} to this archive instance. * * @param zipStream The zip stream. * @return This archive instance. * @throws IOException Error reading zip stream. */ public Archive addEntries(ZipInputStream zipStream) throws IOException { AssertArgument.isNotNull(zipStream, "zipStream"); try { ZipEntry zipEntry = zipStream.getNextEntry(); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); byte[] byteReadBuffer = new byte[512]; int byteReadCount; while (zipEntry != null) { if (zipEntry.isDirectory()) { addEntry(zipEntry.getName(), (byte[]) null); } else { while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) { outByteStream.write(byteReadBuffer, 0, byteReadCount); } addEntry(zipEntry.getName(), outByteStream.toByteArray()); outByteStream.reset(); } zipEntry = zipStream.getNextEntry(); } } finally { try { zipStream.close(); } catch (IOException e) { logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e); } } return this; }
protected Object exec(Object[] args, Context context) { int nargs = args.length; if (nargs != 1 && nargs != 2) { undefined(args, context); return null; } HttpServletRequest request = (HttpServletRequest) args[0]; String enc; if (nargs == 1) { enc = ServletEncoding.getDefaultInputEncoding(context); } else { enc = (String) args[1]; } String contentType = request.getContentType(); if (contentType != null && contentType.startsWith("multipart/form-data")) { throw new RuntimeException("not yet implemented"); } else { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[512]; int n; InputStream in = request.getInputStream(); while ((n = in.read(buf, 0, buf.length)) != -1) { bout.write(buf, 0, n); } in.close(); String qs = new String(bout.toByteArray()); Map map = URLEncoding.parseQueryString(qs, enc); return new ServletParameter(map); } catch (IOException e) { throw new PnutsException(e, context); } } }
/** @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); } } }
/** Restores the content of this cipher to the previous saved one. */ void restore() { processed = processedSave; sizeOfAAD = sizeOfAADSave; if (aadBuffer != null) { aadBuffer.reset(); if (aadBufferSave != null) { aadBuffer.write(aadBufferSave, 0, aadBufferSave.length); } } if (gctrPAndC != null) gctrPAndC.restore(); if (ghashAllToS != null) ghashAllToS.restore(); if (ibuffer != null) { ibuffer.reset(); ibuffer.write(ibufferSave, 0, ibufferSave.length); } }
@Override public boolean write(String uri, List<InputStream> streams) { boolean result = false; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { for (InputStream stream : streams) { int size = stream.available(); byte[] bytes = new byte[size]; int readBytes = stream.read(bytes); if (readBytes != size) { log.error( "Could not read all the bytes from the inputStream. Read " + readBytes + " instead of " + size); return false; } outputStream.write(bytes); } HDFSByteChunk byteChunk = new HDFSByteChunk(outputStream.toByteArray(), uri); SequenceFile.Writer writer = getWriterFor(uri); writer.append(new IntWritable(0), byteChunk); writer.close(); } catch (IOException e) { e.printStackTrace(); } return result; }
/** * Test method for {@link * org.alfresco.deployment.transformers.EncryptionTransformer#addFilter(java.io.OutputStream, * org.alfresco.deployment.DeploymentTransportTransformer.Direction, java.lang.String)}. This test * compresses a message with one transformation. Then sends the results through another instance * to give us plain text again. */ public void testAddFilter() { SampleEncryptionTransformer transformer = new SampleEncryptionTransformer(); transformer.setPassword("Welcome To Hades"); transformer.setCipherName("PBEWithMD5AndDES"); String path = "wibble"; ByteArrayOutputStream compressed = new ByteArrayOutputStream(); // A sender should encrypt the stream OutputStream out = null; // out = (OutputStream)transformer.addFilter(compressed, Direction.SENDER, path); out = (OutputStream) transformer.addFilter(compressed, path, null, null); assertNotNull("null output stream returned", compressed); String clearText = "hello world"; try { out.write(clearText.getBytes()); } catch (IOException ie) { fail("unexpected exception thrown" + ie.toString()); } try { out.flush(); out.close(); } catch (IOException ie) { fail("unexpected exception thrown, " + ie.toString()); } assert (compressed.size() > 0); // Now set up another instance to decrypt the message InputStream decompress = null; ByteArrayInputStream compressedStream = new ByteArrayInputStream(compressed.toByteArray()); ByteArrayOutputStream result = new ByteArrayOutputStream(); decompress = (InputStream) transformer.addFilter(compressedStream, "wibble", null, null); try { byte[] readBuffer = new byte[1002]; while (true) { int readLen = decompress.read(readBuffer); if (readLen > 0) { result.write(readBuffer, 0, readLen); } else { break; } } } catch (IOException ie) { fail("unexpected exception thrown, " + ie.toString()); } // now uncompress should equal clearText assertTrue(result.toString().equalsIgnoreCase(clearText)); }
/** * reads the content of an existing file using the current domain * * @param domain The namespace used to identify the application domain (1st level directory) to * use * @param path The path relative to the domain for the file * @param offset the offset from the beginning of the file. * @param len The length of the block in bytes * @return The contents of the file */ public byte[] readByteFromFile(String path, long offset, int len) throws EOFException, FileAccessException { try { if (_isLocal) { File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path); if (tmpFile.isFile()) { RandomAccessFile raf = new RandomAccessFile(tmpFile, "r"); byte[] buffer = new byte[len]; raf.seek(offset); int totalByteRead = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); int result = 0; while (totalByteRead < len && raf.getFilePointer() < raf.length()) { result = raf.read(buffer, 0, (len - totalByteRead)); if (result != -1) { out.write(buffer, 0, result); totalByteRead += result; } else if (totalByteRead == 0) throw new EOFException("End of file reached!"); else break; } raf.close(); out.flush(); out.close(); return out.toByteArray(); } else throw new FileAccessException("Path is not a file"); } else return _remote.readByteFromFile(_domain, path, offset, len); } catch (EOFException eofe) { throw eofe; } catch (FileAccessException fae) { throw fae; } catch (Exception e) { throw new FileAccessException(e); } }
public static void main(String[] args) throws Exception { // create the keys KeyPair pair = Utils.generateRSAKeyPair(); // create the input stream ByteArrayOutputStream bOut = new ByteArrayOutputStream(); if (outputFormat.equals(DER)) { bOut.write(X509V1CreateExample.generateV1Certificate(pair).getEncoded()); } else if (outputFormat.equals(PEM)) { PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(bOut)); pemWriter.writeObject(X509V1CreateExample.generateV1Certificate(pair)); pemWriter.close(); } bOut.close(); // Print the contents of bOut System.out.println(outputFormat.equals(DER) ? "DER-format:" : "PEM-format:"); System.out.println(Utils.toString(bOut.toByteArray())); InputStream in = new ByteArrayInputStream(bOut.toByteArray()); // create the certificate factory CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); // read the certificate X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in); System.out.println("issuer: " + x509Cert.getIssuerX500Principal()); }
/** * 根据文件以byte[]形式返回文件的数据 * * @param file * @return */ public static byte[] getFileData(File file) { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(file); out = new ByteArrayOutputStream(BUFFER_SIZE); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return out.toByteArray(); }
private void processEncrypt(final ServletRequest servletRequest ,final HttpServletRequest httpRequest,final ServletResponse servletResponse, final FilterChain filterChain)throws IOException, ServletException{ InputStream inputStream = servletRequest.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti=-1; while ((letti = inputStream.read(buf)) > 0){ byteArrayOutputStream.write(buf, 0, letti); } final BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest,doEncrypt(byteArrayOutputStream)); final HttpServletResponse response = (HttpServletResponse) servletResponse; final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(); HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) { public PrintWriter getWriter() { return pw.getWriter(); } public ServletOutputStream getOutputStream() { return pw.getStream(); } }; filterChain.doFilter(bufferedRequest, wrappedResp); }
public static MessageHeader readHeader(InputStream in) throws IOException, MessageFormatException { int match = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); int i; try { do { i = in.read(); if (i == -1) { if (out.size() > 0) throw new MessageFormatException("Unexpected end of stream", out.toByteArray()); return null; } out.write(i); if (i == CRLF[match % 2]) match++; } while (match < 4); } catch (IOException e) { if (out.size() > 0) throw new MessageFormatException("Incomplete message header", e, out.toByteArray()); throw e; } MutableMessageHeader header = new MutableMessageHeader.Impl(); header.setHeader(out.toByteArray()); return header; }
private Image getImage(String str) throws IOException { String url = "http://" + controller.selectedCity.URL + "/cameras/images/" + str + ".jpg"; System.out.println(url); InputStream iStrm = (InputStream) Connector.openInputStream(url); Image im = null; try { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); // Place into image array byte imageData[] = bStrm.toByteArray(); // Create the image from the byte array im = Image.createImage(imageData, 0, imageData.length); } finally { // Clean up if (iStrm != null) iStrm.close(); } return (im == null ? null : im); }
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(); } }
public static byte[] getByteFromURL(URL url) { ByteArrayOutputStream bais = new ByteArrayOutputStream(); InputStream is = null; try { is = url.openStream(); byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time. int n; while ((n = is.read(byteChunk)) > 0) { bais.write(byteChunk, 0, n); } } catch (IOException e) { System.err.printf( "Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage()); e.printStackTrace(); // Perform any other exception handling that's appropriate. } finally { if (is != null) { try { is.close(); } catch (IOException ex) { Logger.getLogger(QQImageUtil.class.getName()).log(Level.SEVERE, null, ex); } } } return bais.toByteArray(); }