Example usage for java.io EOFException EOFException

List of usage examples for java.io EOFException EOFException

Introduction

In this page you can find the example usage for java.io EOFException EOFException.

Prototype

public EOFException(String s) 

Source Link

Document

Constructs an EOFException with the specified detail message.

Usage

From source file:org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader.java

@Override
protected boolean readNext(HLog.Entry entry) throws IOException {
    while (true) {
        // OriginalPosition might be < 0 on local fs; if so, it is useless to us.
        long originalPosition = this.inputStream.getPos();
        if (trailerPresent && originalPosition > 0 && originalPosition == this.walEditsStopOffset) {
            return false;
        }/*from  www.ja  v a2 s  . c  om*/
        WALKey.Builder builder = WALKey.newBuilder();
        long size = 0;
        try {
            long available = -1;
            try {
                int firstByte = this.inputStream.read();
                if (firstByte == -1) {
                    throw new EOFException("First byte is negative");
                }
                size = CodedInputStream.readRawVarint32(firstByte, this.inputStream);
                // available may be < 0 on local fs for instance.  If so, can't depend on it.
                available = this.inputStream.available();
                if (available > 0 && available < size) {
                    throw new EOFException(
                            "Available stream not enough for edit, " + "inputStream.available()= "
                                    + this.inputStream.available() + ", " + "entry size= " + size);
                }
                final InputStream limitedInput = new LimitInputStream(this.inputStream, size);
                builder.mergeFrom(limitedInput);
            } catch (InvalidProtocolBufferException ipbe) {
                throw (EOFException) new EOFException("Invalid PB, EOF? Ignoring; originalPosition="
                        + originalPosition + ", currentPosition=" + this.inputStream.getPos() + ", messageSize="
                        + size + ", currentAvailable=" + available).initCause(ipbe);
            }
            if (!builder.isInitialized()) {
                // TODO: not clear if we should try to recover from corrupt PB that looks semi-legit.
                //       If we can get the KV count, we could, theoretically, try to get next record.
                throw new EOFException(
                        "Partial PB while reading WAL, " + "probably an unexpected EOF, ignoring");
            }
            WALKey walKey = builder.build();
            entry.getKey().readFieldsFromPb(walKey, this.byteStringUncompressor);
            if (!walKey.hasFollowingKvCount() || 0 == walKey.getFollowingKvCount()) {
                LOG.trace("WALKey has no KVs that follow it; trying the next one");
                continue;
            }
            int expectedCells = walKey.getFollowingKvCount();
            long posBefore = this.inputStream.getPos();
            try {
                int actualCells = entry.getEdit().readFromCells(cellDecoder, expectedCells);
                if (expectedCells != actualCells) {
                    throw new EOFException("Only read " + actualCells); // other info added in catch
                }
            } catch (Exception ex) {
                String posAfterStr = "<unknown>";
                try {
                    posAfterStr = this.inputStream.getPos() + "";
                } catch (Throwable t) {
                    LOG.trace("Error getting pos for error message - ignoring", t);
                }
                String message = " while reading " + expectedCells + " WAL KVs; started reading at " + posBefore
                        + " and read up to " + posAfterStr;
                IOException realEofEx = extractHiddenEof(ex);
                throw (EOFException) new EOFException("EOF " + message)
                        .initCause(realEofEx != null ? realEofEx : ex);
            }
            if (trailerPresent && this.inputStream.getPos() > this.walEditsStopOffset) {
                LOG.error("Read WALTrailer while reading WALEdits. hlog: " + this.path
                        + ", inputStream.getPos(): " + this.inputStream.getPos() + ", walEditsStopOffset: "
                        + this.walEditsStopOffset);
                throw new EOFException("Read WALTrailer while reading WALEdits");
            }
        } catch (EOFException eof) {
            LOG.trace("Encountered a malformed edit, seeking back to last good position in file", eof);
            // If originalPosition is < 0, it is rubbish and we cannot use it (probably local fs)
            if (originalPosition < 0)
                throw eof;
            // Else restore our position to original location in hope that next time through we will
            // read successfully.
            seekOnFs(originalPosition);
            return false;
        }
        return true;
    }
}

From source file:com.zimbra.soap.SoapServlet.java

private void doWork(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int len = req.getContentLength();
    byte[] buffer;
    boolean isResumed = true;

    // resuming from a Jetty Continuation does *not* reset the HttpRequest's input stream -
    // therefore we store the read buffer in the Continuation, and use the stored buffer
    // if we're resuming
    buffer = (byte[]) req.getAttribute("com.zimbra.request.buffer");
    if (buffer == null) {
        isResumed = false;//from   w w w  . j  a  v a 2 s .c om

        // Look up max request size
        int maxSize = 0;
        try {
            maxSize = Provisioning.getInstance().getLocalServer()
                    .getIntAttr(Provisioning.A_zimbraSoapRequestMaxSize, 0);
        } catch (ServiceException e) {
            ZimbraLog.soap.warn("Unable to look up %s.  Not limiting the request size.",
                    Provisioning.A_zimbraSoapRequestMaxSize, e);
        }
        if (maxSize <= 0) {
            maxSize = Integer.MAX_VALUE;
        }

        // Read the request
        boolean success;
        if (len > maxSize) {
            success = false;
        } else {
            BufferStream bs = null;

            try {
                bs = new BufferStream(len, maxSize, maxSize);
                int in = (int) bs.readFrom(req.getInputStream(), len >= 0 ? len : Integer.MAX_VALUE);

                if (len > 0 && in < len)
                    throw new EOFException("SOAP content truncated " + in + "!=" + len);
                success = in <= maxSize;
                buffer = bs.toByteArray();
            } finally {
                ByteUtil.closeStream(bs);
            }
        }

        // Handle requests that exceed the size limit
        if (!success) {
            String sizeString = (len < 0 ? "" : " size " + len);
            String msg = String.format("Request%s exceeded limit of %d bytes set for %s.", sizeString, maxSize,
                    Provisioning.A_zimbraSoapRequestMaxSize);
            ServiceException e = ServiceException.INVALID_REQUEST(msg, null);
            ZimbraLog.soap.warn(null, e);
            Element fault = SoapProtocol.Soap12.soapFault(e);
            Element envelope = SoapProtocol.Soap12.soapEnvelope(fault);
            sendResponse(req, resp, envelope);
            return;
        }

        req.setAttribute("com.zimbra.request.buffer", buffer);
    }

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put(SERVLET_CONTEXT, getServletContext());
    context.put(SERVLET_REQUEST, req);
    context.put(SERVLET_RESPONSE, resp);

    try {
        Boolean isAdminReq = isAdminRequest(req);
        context.put(IS_ADMIN_REQUEST, isAdminReq);
    } catch (ServiceException se) {
        ZimbraLog.soap.warn("unable to determine isAdminReq", se);
    }

    // setup IPs in the context and add to logging context
    RemoteIP remoteIp = new RemoteIP(req, ZimbraServlet.getTrustedIPs());
    context.put(SoapEngine.SOAP_REQUEST_IP, remoteIp.getClientIP());
    context.put(SoapEngine.ORIG_REQUEST_IP, remoteIp.getOrigIP());
    context.put(SoapEngine.REQUEST_IP, remoteIp.getRequestIP());
    remoteIp.addToLoggingContext();

    //checkAuthToken(req.getCookies(), context);
    context.put(SoapEngine.REQUEST_PORT, req.getServerPort());
    Element envelope = null;
    try {
        envelope = mEngine.dispatch(req.getRequestURI(), buffer, context);
        if (context.containsKey(INVALIDATE_COOKIES)) {
            ZAuthToken.clearCookies(resp);
        }
    } catch (Throwable e) {
        if (e instanceof OutOfMemoryError) {
            Zimbra.halt("handler exception", e);
        }

        if (ZimbraLog.soap.isTraceEnabled() && !context.containsKey(SoapEngine.SOAP_REQUEST_LOGGED)) {
            ZimbraLog.soap.trace(!isResumed ? "C:\n%s" : "C: (resumed)\n%s",
                    new String(buffer, Charsets.UTF_8));
        }

        // don't interfere with Jetty Continuations -- pass the exception right up
        if (e.getClass().getName().equals("org.eclipse.jetty.continuation.ContinuationThrowable"))
            throw (Error) e;

        ZimbraLog.soap.warn("handler exception", e);
        Element fault = SoapProtocol.Soap12.soapFault(ServiceException.FAILURE(e.toString(), e));
        envelope = SoapProtocol.Soap12.soapEnvelope(fault);
    }

    if (ZimbraLog.soap.isTraceEnabled()) {
        ZimbraLog.soap.trace("S:\n%s", envelope.prettyPrint());
    }
    sendResponse(req, resp, envelope);
}

From source file:org.apache.hadoop.hdfs.server.datanode.BlockReceiver.java

/**
 * reads upto toRead byte to buf at buf.limit() and increments the limit.
 * throws an IOException if read does not succeed.
 *///from   w  ww  .  j  a  v  a  2s.  c o  m
private int readToBuf(int toRead) throws IOException {
    if (toRead < 0) {
        toRead = (maxPacketReadLen > 0 ? maxPacketReadLen : buf.capacity()) - buf.limit();
    }

    int nRead = in.read(buf.array(), buf.limit(), toRead);

    if (nRead < 0) {
        throw new EOFException("while trying to read " + toRead + " bytes");
    }
    bufRead = buf.limit() + nRead;
    buf.limit(bufRead);
    return nRead;
}

From source file:org.apache.flink.runtime.blob.BlobUtils.java

/**
 * Auxiliary method to read the length of an upcoming data chunk from an
 * input stream.// ww w.j av  a  2s . c  o  m
 *
 * @param inputStream
 *        the input stream to read the length from
 * @return the length of the upcoming data chunk in bytes
 * @throws IOException
 *         thrown if an I/O error occurs while reading from the input
 *         stream
 */
static int readLength(InputStream inputStream) throws IOException {
    byte[] buf = new byte[4];
    int bytesRead = 0;
    while (bytesRead < 4) {
        final int read = inputStream.read(buf, bytesRead, 4 - bytesRead);
        if (read < 0) {
            throw new EOFException("Read an incomplete length");
        }
        bytesRead += read;
    }

    bytesRead = buf[0] & 0xff;
    bytesRead |= (buf[1] & 0xff) << 8;
    bytesRead |= (buf[2] & 0xff) << 16;
    bytesRead |= (buf[3] & 0xff) << 24;

    return bytesRead;
}

From source file:org.apache.jxtadoop.hdfs.server.datanode.BlockReceiver.java

/**
 * reads upto toRead byte to buf at buf.limit() and increments the limit.
 * throws an IOException if read does not succeed.
 */// ww w  .ja  v  a  2  s .  co  m
private int readToBuf(int toRead) throws IOException {
    LOG.debug("Reading buffer data  blockreceiver");
    if (toRead < 0) {
        toRead = (maxPacketReadLen > 0 ? maxPacketReadLen : buf.capacity()) - buf.limit();
    }

    int nRead = 0;
    try {
        nRead = in.read(buf.array(), buf.limit(), toRead);
    } catch (SocketTimeoutException ste) {
        // throw new IOException("Time out while reading data in block receiver");
        LOG.debug("Time out while reading data in block receiver");
    }

    if (nRead < 0) {
        throw new EOFException("while trying to read " + toRead + " bytes");
    }
    bufRead = buf.limit() + nRead;
    buf.limit(bufRead);
    return nRead;
}

From source file:org.apache.jmeter.services.FileServer.java

/**
 * Creates an association between a filename and a File inputOutputObject,
 * and stores it for later use - unless it is already stored.
 *
 * @param filename - relative (to base) or absolute file name (must not be null or empty)
 * @param charsetName - the character set encoding to use for the file (may be null)
 * @param alias - the name to be used to access the object (must not be null)
 * @param hasHeader true if the file has a header line describing the contents
 * @return the header line; may be null//from   w w w. j ava  2s .c om
 * @throws EOFException if eof reached
 * @throws IllegalArgumentException if header could not be read or filename is null or empty
 */
public synchronized String reserveFile(String filename, String charsetName, String alias, boolean hasHeader) {
    if (filename == null || filename.isEmpty()) {
        throw new IllegalArgumentException("Filename must not be null or empty");
    }
    if (alias == null) {
        throw new IllegalArgumentException("Alias must not be null");
    }
    FileEntry fileEntry = files.get(alias);
    if (fileEntry == null) {
        fileEntry = new FileEntry(resolveFileFromPath(filename), null, charsetName);
        if (filename.equals(alias)) {
            log.info("Stored: " + filename);
        } else {
            log.info("Stored: " + filename + " Alias: " + alias);
        }
        files.put(alias, fileEntry);
        if (hasHeader) {
            try {
                fileEntry.headerLine = readLine(alias, false);
                if (fileEntry.headerLine == null) {
                    fileEntry.exception = new EOFException("File is empty: " + fileEntry.file);
                }
            } catch (IOException | IllegalArgumentException e) {
                fileEntry.exception = e;
            }
        }
    }
    if (hasHeader && fileEntry.headerLine == null) {
        throw new IllegalArgumentException("Could not read file header line for file " + filename,
                fileEntry.exception);
    }
    return fileEntry.headerLine;
}

From source file:org.apache.hadoop.hbase.client.TestFastFailWithoutTestUtil.java

@Test
public void testExceptionsIdentifiedByInterceptor() throws IOException {
    Throwable[] networkexceptions = new Throwable[] { new ConnectException("Mary is unwell"),
            new SocketTimeoutException("Mike is too late"), new ClosedChannelException(),
            new SyncFailedException("Dave is not on the same page"), new TimeoutException("Mike is late again"),
            new EOFException("This is the end... "), new ConnectionClosingException("Its closing") };
    final String INDUCED = "Induced";
    Throwable[] nonNetworkExceptions = new Throwable[] { new IOException("Bob died"),
            new RemoteException("Bob's cousin died", null), new NoSuchMethodError(INDUCED),
            new NullPointerException(INDUCED), new DoNotRetryIOException(INDUCED), new Error(INDUCED) };

    Configuration conf = HBaseConfiguration.create();
    long CLEANUP_TIMEOUT = 0;
    long FAST_FAIL_THRESHOLD = 1000000;
    conf.setBoolean(HConstants.HBASE_CLIENT_FAST_FAIL_MODE_ENABLED, true);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_CLEANUP_MS_DURATION_MS, CLEANUP_TIMEOUT);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_THREASHOLD_MS, FAST_FAIL_THRESHOLD);
    for (Throwable e : networkexceptions) {
        PreemptiveFastFailInterceptor interceptor = TestFastFailWithoutTestUtil
                .createPreemptiveInterceptor(conf);
        FastFailInterceptorContext context = (FastFailInterceptorContext) interceptor.createEmptyContext();

        RetryingCallable<?> callable = getDummyRetryingCallable(getSomeServerName());
        context.prepare(callable, 0);/*ww  w. j a v  a  2s  . c o  m*/
        interceptor.intercept(context);
        interceptor.handleFailure(context, e);
        interceptor.updateFailureInfo(context);
        assertTrue("The call shouldn't have been successful if there was a ConnectException",
                context.getCouldNotCommunicateWithServer().booleanValue());
    }
    for (Throwable e : nonNetworkExceptions) {
        try {
            PreemptiveFastFailInterceptor interceptor = TestFastFailWithoutTestUtil
                    .createPreemptiveInterceptor(conf);
            FastFailInterceptorContext context = (FastFailInterceptorContext) interceptor.createEmptyContext();

            RetryingCallable<?> callable = getDummyRetryingCallable(getSomeServerName());
            context.prepare(callable, 0);
            interceptor.intercept(context);
            interceptor.handleFailure(context, e);
            interceptor.updateFailureInfo(context);
            assertFalse("The call shouldn't have been successful if there was a ConnectException",
                    context.getCouldNotCommunicateWithServer().booleanValue());
        } catch (NoSuchMethodError t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (NullPointerException t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (DoNotRetryIOException t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (Error t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        }
    }
}

From source file:org.apache.flink.runtime.blob.BlobUtils.java

/**
 * Auxiliary method to read a particular number of bytes from an input stream. This method blocks until the
 * requested number of bytes have been read from the stream. If the stream cannot offer enough data, an
 * {@link EOFException} is thrown./*from w  w  w  . ja  v a2 s.c om*/
 *
 * @param inputStream The input stream to read the data from.
 * @param buf The buffer to store the read data.
 * @param off The offset inside the buffer.
 * @param len The number of bytes to read from the stream.
 * @param type The name of the type, to throw a good error message in case of not enough data.
 * @throws IOException
 *         Thrown if I/O error occurs while reading from the stream or the stream cannot offer enough data.
 */
static void readFully(InputStream inputStream, byte[] buf, int off, int len, String type) throws IOException {

    int bytesRead = 0;
    while (bytesRead < len) {

        final int read = inputStream.read(buf, off + bytesRead, len - bytesRead);
        if (read < 0) {
            throw new EOFException("Received an incomplete " + type);
        }
        bytesRead += read;
    }
}

From source file:lc.kra.servlet.FileManagerServlet.java

private static byte[] readStream(InputStream input, int length, boolean readAll) throws IOException {
    byte[] output = {};
    int position = 0;
    if (length == -1)
        length = Integer.MAX_VALUE;
    while (position < length) {
        int bytesToRead;
        if (position >= output.length) { // Only expand when there's no room
            bytesToRead = Math.min(length - position, output.length + 1024);
            if (output.length < position + bytesToRead)
                output = Arrays.copyOf(output, position + bytesToRead);
        } else/* ww w  . j a  va 2 s . co m*/
            bytesToRead = output.length - position;
        int bytesRead = input.read(output, position, bytesToRead);
        if (bytesRead < 0) {
            if (!readAll || length == Integer.MAX_VALUE) {
                if (output.length != position)
                    output = Arrays.copyOf(output, position);
                break;
            } else
                throw new EOFException("Detect premature EOF");
        }
        position += bytesRead;
    }
    return output;
}

From source file:henplus.HenPlus.java

public String readlineFromFile() throws IOException {
    if (_fileReader == null) {
        _fileReader = new BufferedReader(new InputStreamReader(System.in));
    }/*from   w  w  w  . ja va 2 s .  c  om*/
    final String line = _fileReader.readLine();
    if (line == null) {
        throw new EOFException("EOF");
    }
    return line.length() == 0 ? null : line;
}