List of usage examples for java.io PushbackInputStream unread
public void unread(byte[] b) throws IOException
From source file:de.unisb.cs.st.javaslicer.traceResult.TraceResult.java
public TraceResult(File filename) throws IOException { final MultiplexedFileReader file = new MultiplexedFileReader(filename); if (file.getStreamIds().size() < 2) throw new IOException("corrupted data"); final MultiplexInputStream readClassesStream = file.getInputStream(0); if (readClassesStream == null) throw new IOException("corrupted data"); PushbackInputStream pushBackInput = new PushbackInputStream( new BufferedInputStream(new GZIPInputStream(readClassesStream, 512), 512), 1); final DataInputStream readClassesInputStream = new DataInputStream(pushBackInput); final ArrayList<ReadClass> readClasses0 = new ArrayList<ReadClass>(); final StringCacheInput stringCache = new StringCacheInput(); int testRead; while ((testRead = pushBackInput.read()) != -1) { pushBackInput.unread(testRead); readClasses0.add(ReadClass.readFrom(readClassesInputStream, stringCache)); }//from w w w .j a va 2 s. com readClasses0.trimToSize(); Collections.sort(readClasses0); this.readClasses = readClasses0; this.instructions = getInstructionArray(readClasses0); final MultiplexInputStream threadTracersStream = file.getInputStream(1); if (threadTracersStream == null) throw new IOException("corrupted data"); pushBackInput = new PushbackInputStream( new BufferedInputStream(new GZIPInputStream(threadTracersStream, 512), 512), 1); final DataInputStream threadTracersInputStream = new DataInputStream(pushBackInput); final ArrayList<ThreadTraceResult> threadTraces0 = new ArrayList<ThreadTraceResult>(); while ((testRead = pushBackInput.read()) != -1) { pushBackInput.unread(testRead); threadTraces0.add(ThreadTraceResult.readFrom(threadTracersInputStream, this, file)); } threadTraces0.trimToSize(); Collections.sort(threadTraces0); this.threadTraces = threadTraces0; }
From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java
private InputStream stripUtf8Bom(InputStream inputStream) throws IOException { PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3); byte[] bom = new byte[3]; if (pushbackInputStream.read(bom) != -1) { if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) { pushbackInputStream.unread(bom); }//w w w.j a v a 2 s . c om } return pushbackInputStream; }
From source file:com.zimbra.cs.pop3.Pop3Handler.java
private void sendMessage(InputStream is, int maxNumBodyLines) throws IOException { boolean inBody = false; int numBodyLines = 0; PushbackInputStream stream = new PushbackInputStream(is); int c;/*from w ww . ja v a2 s .c o m*/ boolean startOfLine = true; int lineLength = 0; while ((c = stream.read()) != -1) { if (c == '\r' || c == '\n') { if (c == '\r') { int peek = stream.read(); if (peek != '\n' && peek != -1) stream.unread(peek); } if (!inBody) { if (lineLength == 0) inBody = true; } else { numBodyLines++; } startOfLine = true; lineLength = 0; output.write(LINE_SEPARATOR); if (inBody && numBodyLines >= maxNumBodyLines) { break; } continue; } else if (c == TERMINATOR_C && startOfLine) { output.write(c); // we'll end up writing it twice } if (startOfLine) startOfLine = false; lineLength++; output.write(c); } if (lineLength != 0) { output.write(LINE_SEPARATOR); } output.write(TERMINATOR_BYTE); output.write(LINE_SEPARATOR); output.flush(); }
From source file:libepg.ts.reader.Reader2.java
/** * ??????<br>/*from www . j a v a 2s.c o m*/ * 1:???????????1??????<br> * 2:?????????????<br> * 3:??????1??????<br> * ???????????<br> * 4:1?<br> * * @return ??? */ public synchronized List<TsPacket> getPackets() { ByteBuffer packetBuffer = ByteBuffer.allocate(TsPacket.TS_PACKET_BYTE_LENGTH.PACKET_LENGTH.getByteLength()); byte[] byteData = new byte[1]; //? List<TsPacket> packets = new ArrayList<>(); FileInputStream fis = null; PushbackInputStream pis = null; try { fis = new FileInputStream(this.TSFile); pis = new PushbackInputStream(fis); boolean tipOfPacket = false;//? long count = 0; //??????1?????? while (pis.read(byteData) != EOF) { //??????????????? if ((byteData[0] == TsPacket.TS_SYNC_BYTE) && (tipOfPacket == false)) { tipOfPacket = true; if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) { LOG.trace( "???????????1????"); } pis.unread(byteData); } if (tipOfPacket == true) { byte[] tsPacketData = new byte[TsPacket.TS_PACKET_BYTE_LENGTH.PACKET_LENGTH.getByteLength()]; if (pis.read(tsPacketData) != EOF) { if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) { LOG.trace( "??????????????"); } packetBuffer.put(tsPacketData); } else { break; } } if (packetBuffer.remaining() == 0) { byte[] BeforeCutDown = packetBuffer.array(); byte[] AfterCutDown = new byte[packetBuffer.position()]; System.arraycopy(BeforeCutDown, 0, AfterCutDown, 0, AfterCutDown.length); //?????????? TsPacket tsp = new TsPacket(AfterCutDown); // LOG.debug(Hex.encodeHexString(tsp.getData())); if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) { LOG.trace( "1???????? "); LOG.trace(tsp.toString()); } if (tsp.getTransport_error_indicator() != 0) { if (LOG.isWarnEnabled()) { LOG.warn( "??1????????????????????"); LOG.warn(tsp); LOG.warn(TSFile); } tipOfPacket = false; } else { packets.add(tsp); count++; } packetBuffer.clear(); tipOfPacket = false; if (this.readLimit != null && count >= this.readLimit) { if (LOG.isInfoEnabled()) { LOG.info( "????????????? ?? = " + this.readLimit); } break; } } } if (LOG.isTraceEnabled() && NOT_DETERRENT_READ_TRACE_LOG) { LOG.trace("?????????"); LOG.trace(" = " + Hex.encodeHexString(packetBuffer.array())); } pis.close(); fis.close(); LOG.info("??? = " + count); } catch (FileNotFoundException e) { LOG.fatal("?????", e); } catch (IOException e) { LOG.fatal("???", e); } return Collections.unmodifiableList(packets); }
From source file:com.handywedge.binarystore.store.gcs.BinaryStoreManagerImpl.java
@SuppressWarnings("unused") @Override/*from ww w . ja va 2 s . co m*/ public BinaryInfo upload(StorageInfo storage, BinaryInfo binary, InputStream inStream) throws StoreException { logger.info("GCS update method: start."); logger.debug("" + storage.toString()); logger.debug("?" + binary.toString()); long startSingle = System.currentTimeMillis(); Storage gStorage = getGCSClient(binary.getBucketName(), true); File tempFile = null; logger.info("Uploading a new binary to GCS from a file\n"); BinaryInfo rtnBinary = new BinaryInfo(); BlobId blobId = BlobId.of(binary.getBucketName(), binary.getFileName()); List<Acl> acls = new ArrayList<>(); acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER)); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(binary.getContentType()) .setStorageClass(StorageClass.COLDLINE).setAcl(acls).build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); long written = -1L; try { written = IOUtils.copyLarge(inStream, baos, 0, BINARY_PART_SIZE_5MB); } catch (IOException e) { logger.error("IOUtils.copyLarge ?"); throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.OUT_OF_RESOURCE, e); } byte[] data = baos.toByteArray(); InputStream gcsInputStream = new ByteArrayInputStream(data); if (written < BINARY_PART_SIZE_5MB) { Blob blob = gStorage.create(blobInfo, data); rtnBinary = createReturnBinaryInfo(blob); } else { int firstByte = 0; int partNumber = 1; Boolean isFirstChunck = true; Boolean overSizeLimit = false; InputStream firstChunck = new ByteArrayInputStream(data); PushbackInputStream chunckableInputStream = new PushbackInputStream(inStream, 1); try { tempFile = File.createTempFile(UUID.randomUUID().toString().concat(binary.getFileName()), "tmp"); } catch (IOException e) { logger.error("File.createTempFile ???={}", UUID.randomUUID().toString().concat(binary.getFileName())); throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.DISK_IO_ERROR, e, UUID.randomUUID().toString().concat(binary.getFileName())); } try { while (-1 != (firstByte = chunckableInputStream.read())) { long partSize = 0; chunckableInputStream.unread(firstByte); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(tempFile.getAbsolutePath(), true)); if (isFirstChunck == true) { partSize = IOUtils.copyLarge(firstChunck, os, 0, (BINARY_PART_SIZE_5MB)); isFirstChunck = false; } else { partSize = IOUtils.copyLarge(chunckableInputStream, os, 0, (BINARY_PART_SIZE_5MB)); } written += partSize; if (written > BINARY_PART_SIZE_5MB * 1024) { // 5GB overSizeLimit = true; logger.error("OVERSIZED FILE ({}). STARTING ABORT", written); break; } } finally { IOUtils.closeQuietly(os); } Boolean isLastPart = -1 == (firstByte = chunckableInputStream.read()); if (!isLastPart) { chunckableInputStream.unread(firstByte); } } } catch (IOException e) { logger.error("??????={}", UUID.randomUUID().toString().concat(binary.getFileName())); throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.DISK_IO_ERROR, e, UUID.randomUUID().toString().concat(binary.getFileName())); } try { WriteChannel writer = gStorage.writer(blobInfo); byte[] buffer = new byte[1024]; InputStream input = new FileInputStream(tempFile); int limit; while ((limit = input.read(buffer)) >= 0) { try { writer.write(ByteBuffer.wrap(buffer, 0, limit)); } catch (Exception ex) { logger.error("?????"); throw ex; } } } catch (IOException e) { logger.error("Upload???={}", blobInfo.toString()); throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.UPLOAD_FAIL, e, blobInfo.toString()); } if (null != tempFile && tempFile.exists()) { tempFile.delete(); } } Blob blob = gStorage.get(blobInfo.getBlobId()); rtnBinary = createReturnBinaryInfo(blob); long endSingle = System.currentTimeMillis(); logger.info("{} Geted : {} ms\n", binary.getFileName(), (endSingle - startSingle)); logger.info("GCS update method: end."); return binary; }
From source file:com.temenos.interaction.media.hal.HALProvider.java
/** * Reads a Hypertext Application Language (HAL) representation of * {@link EntityResource} from the input stream. * // w w w. j a va 2 s. c o m * @precondition {@link InputStream} contains a valid HAL <resource/> document * @postcondition {@link EntityResource} will be constructed and returned. * @invariant valid InputStream */ @Override public RESTResource readFrom(Class<RESTResource> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { /* To detect if the stream is empty (a valid case since an input entity is * sometimes optional), wrap in a PushbackInputStream before passing on */ PushbackInputStream wrappedStream = new PushbackInputStream(entityStream); int firstByte = wrappedStream.read(); uriInfo = new UriInfoImpl(uriInfo); if (firstByte == -1) { // No data provided return null; } else { // There is something in the body, so we will parse it. It is required // to be a valid JSON object. First replace the byte we borrowed. wrappedStream.unread(firstByte); //Parse hal+json into an Entity object Entity entity; try { entity = buildEntityFromHal(wrappedStream, mediaType); } catch (MethodNotAllowedException e) { if (logger.isDebugEnabled()) { logger.debug("Error building the entity.", e); } StringBuilder allowHeader = new StringBuilder(); Set<String> allowedMethods = new HashSet<String>(e.getAllowedMethods()); allowedMethods.add("HEAD"); allowedMethods.add("OPTIONS"); for (String method : allowedMethods) { allowHeader.append(method); allowHeader.append(", "); } Response response = Response.status(405) .header("Allow", allowHeader.toString().substring(0, allowHeader.length() - 2)).build(); throw new WebApplicationException(response); } return new EntityResource<Entity>(entity); } }
From source file:com.maverick.ssl.https.HttpsURLConnection.java
void readResponse(PushbackInputStream in) throws IOException { DataInputStream data = new DataInputStream(in); String line;/*from w ww. j a v a 2s. co m*/ while (((line = data.readLine()) != null) && (line.length() > 0)) { headers.addElement(line); int index = line.indexOf(':'); if (index >= 0) { String key = line.substring(0, index); String value = line.substring(index + 1).trim(); headerKeys.addElement(key); headerValues.put(key.toLowerCase(), value); } else { // If the first line back is not a header, the unread as the // rest is going to be content if (headerValues.size() == 0) { // This is a response code if (line.startsWith("HTTP/")) { //$NON-NLS-1$ try { int idx = line.indexOf(' '); while (line.charAt(++idx) == ' ') { ; } responseMessage = line.substring(idx + 4); responseCode = Integer.parseInt(line.substring(idx, idx + 3)); } catch (Throwable t) { responseCode = 200; } } else { // Just content responseCode = 200; byte[] unread = line.getBytes(); in.unread(unread); break; } } } } }
From source file:net.stuxcrystal.simpledev.configuration.parser.generators.xml.XMLParser.java
/** * Checks if a stream is actually empty. * @param pis The input stream.//w w w . j a v a 2 s . com * @return {@code true} if so. */ private static boolean isEmpty(PushbackInputStream pis) throws IOException { int b = pis.read(); boolean empty = (b == -1); pis.unread(b); return empty; }
From source file:org.apache.abdera.protocol.server.multipart.AbstractMultipartCollectionAdapter.java
private MultipartInputStream getMultipartStream(RequestContext request) throws IOException, ParseException, IllegalArgumentException { String boundary = request.getContentType().getParameter(BOUNDARY_PARAM); if (boundary == null) { throw new IllegalArgumentException("multipart/related stream invalid, boundary parameter is missing."); }// w w w.j a v a 2 s.com boundary = "--" + boundary; String type = request.getContentType().getParameter(TYPE_PARAM); if (!(type != null && MimeTypeHelper.isAtom(type))) { throw new ParseException( "multipart/related stream invalid, type parameter should be " + Constants.ATOM_MEDIA_TYPE); } PushbackInputStream pushBackInput = new PushbackInputStream(request.getInputStream(), 2); pushBackInput.unread("\r\n".getBytes()); return new MultipartInputStream(pushBackInput, boundary.getBytes()); }