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:com.continuent.tungsten.common.mysql.MySQLPacket.java

/**
 * Reads a MySQL packet from the input stream.
 * //from   w w  w  . j a va  2  s.  co  m
 * @param in the data input stream from where we read the MySQL packet
 * @param timeoutMillis Number of milliseconds we will pause while waiting
 *            for data from the the network during a packet.
 * @return a MySQLPacket object or null if the MySQL packet cannot be read
 */
public static MySQLPacket readPacket(InputStream in, long timeoutMillis) {
    try {
        int mask = 0xff;
        int packetLen1 = in.read();
        int packetLen2 = in.read();
        int packetLen3 = in.read();
        int packetLen = (packetLen1 & mask) | (packetLen2 & mask) << 8 | (packetLen3 & mask) << 16;
        int packetNumber = in.read();
        // This is ok, no more packet on the line
        if (packetLen1 == -1) {
            logger.debug("Reached end of input stream while reading packet");
            return null;
        }
        // This is bad, client went away
        if (packetLen2 == -1 || packetLen3 == -1 || packetNumber == -1) {
            throw new EOFException("Reached end of input stream.");
        }

        // read the body of the packet
        byte[] packetData = new byte[packetLen + HEADER_LENGTH];
        // copy header
        packetData[0] = (byte) packetLen1;
        packetData[1] = (byte) packetLen2;
        packetData[2] = (byte) packetLen3;
        packetData[3] = (byte) packetNumber;

        // See if we can trust the availability from this stream.
        boolean deterministicAvailability = true;
        if (in instanceof WrappedInputStream) {
            deterministicAvailability = ((WrappedInputStream) in).isDeterministic();
        }

        // read() returns the number of actual bytes read, which might be
        // less that the desired length this loop ensures that the whole
        // packet is read
        int n = 0;
        while (n < packetLen) {
            // Issue 281. Wait until at least one byte is available to avoid
            // a possible out of data condition when reading from the
            // network.
            if (deterministicAvailability && in.available() == 0) {
                long readStartTime = System.currentTimeMillis();
                long delay = -1;

                // Sleep for up to timeout.
                while (in.available() == 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        return null;
                    }
                    delay = System.currentTimeMillis() - readStartTime;
                    if (delay > timeoutMillis) {
                        break;
                    }
                }

                // Note the delay if longer than 10% of the timeout. This
                // is helpful for diagnosing failures.
                if (delay > (timeoutMillis / 10)) {
                    logger.info("Paused to allow packet data to appear on the network: delay="
                            + (delay / 1000.0) + " timeout=" + (timeoutMillis / 1000.0) + " packetNumber="
                            + packetNumber + " packetlen=" + packetLen + " bytesRead=" + n);
                }
            }

            // Now read data.
            int count = in.read(packetData, HEADER_LENGTH + n, packetLen - n);

            if (count < 0) {
                throw new EOFException("Reached end of input stream: packetNumber=" + packetNumber
                        + " packetlen=" + packetLen + " bytesRead=" + n);
            }

            n += count;
        }
        MySQLPacket p = new MySQLPacket(packetLen, packetData, (byte) packetNumber);
        p.setInputStream(in);
        return p;
    } catch (SocketTimeoutException e) {
        logger.warn("Socket timeout expired, closing connection");
    } catch (IOException e) {
        logger.error("I/O error while reading from client socket", e);
    }

    return null;
}

From source file:wordnice.api.Nice.java

public static EOFException eof(int readed, int wanted) {
    return new EOFException("Readed " + readed + " bytes from " + wanted + " total!");
}

From source file:org.apache.hadoop.hive.serde2.teradata.TeradataBinaryDataInputStream.java

/**
 * Read VARBYTE(N).//www.j  ava2 s . com
 * The representation of VARBYTE in Teradata binary format is:
 * the first two bytes represent the length N of this varchar field
 * the next N bytes represent the content of this varchar field.
 * To pad the null varbyte, the length will be 0 and the content will be none.
 *
 * @return the byte [ ]
 * @throws IOException the io exception
 */
public byte[] readVarbyte() throws IOException {
    int varbyteLength = readUnsignedShort();
    byte[] varbyteContent = new byte[varbyteLength];
    int numOfBytesRead = in.read(varbyteContent);
    if (varbyteContent.length != 0 && numOfBytesRead != varbyteLength) {
        throw new EOFException(format("Fail to read the varbyte. Expect %d bytes, get %d bytes", varbyteLength,
                numOfBytesRead));
    }
    return varbyteContent;
}

From source file:org.apache.ignite.internal.processors.hadoop.igfs.HadoopIgfsInputStream.java

/** {@inheritDoc} */
@Override/*ww  w . j  a  v a  2  s . com*/
public synchronized void readFully(long position, byte[] buf, int off, int len) throws IOException {
    long remaining = limit - position;

    checkClosed();

    if (len > remaining)
        throw new EOFException("End of stream reached before data was fully read.");

    readStart();

    try {
        int read = this.buf.flatten(buf, position, off, len);

        total += read;

        if (read != len) {
            int readAmt = len - read;

            delegate.hadoop().readData(delegate, position + read, readAmt, buf, off + read, readAmt).get();

            total += readAmt;
        }

        if (clientLog.isLogEnabled())
            clientLog.logRandomRead(logStreamId, position, len);
    } catch (IgniteCheckedException e) {
        throw HadoopIgfsUtils.cast(e);
    } finally {
        readEnd();
    }
}

From source file:org.gridgain.grid.kernal.ggfs.hadoop.GridGgfsHadoopInputStream.java

/** {@inheritDoc} */
@Override/*from w w w  .j av a  2  s .c  o  m*/
public synchronized void readFully(long position, byte[] buf, int off, int len) throws IOException {
    long remaining = limit - position;

    checkClosed();

    if (len > remaining)
        throw new EOFException("End of stream reached before data was fully read.");

    readStart();

    try {
        int read = this.buf.flatten(buf, position, off, len);

        total += read;

        if (read != len) {
            int readAmt = len - read;

            delegate.hadoop().readData(delegate, position + read, readAmt, buf, off + read, readAmt).get();

            total += readAmt;
        }

        if (clientLog.isLogEnabled())
            clientLog.logRandomRead(logStreamId, position, len);
    } catch (GridException e) {
        throw GridGgfsHadoopUtils.cast(e);
    } finally {
        readEnd();
    }
}

From source file:dk.statsbiblioteket.util.LineReader.java

/**
 * Sets the absolute position within the file.
 *
 * @param position the position in the given file. this must be equal to or
 *                 less than the file size.
 * @throws IOException if the position is not within the range of the file.
 *///from  www  . j  av  a 2s.  c  o  m
public void seek(long position) throws IOException {
    //log.trace("seek(" + position + ") called");
    if (position > length()) {
        //noinspection DuplicateStringLiteralInspection
        throw new EOFException(
                "Cannot set position " + position + " as the file size is only " + length() + " bytes");
    }
    if (position < 0) {
        throw new IllegalArgumentException("The position cannot be negative");
    }
    if (bufferStart != -1) {
        if (position < bufferStart || position >= bufferStart + bufferSize) {
            invalidateBuffer();
        } else {
            // The new position is inside the existing buffer
            try {
                buffer.position((int) (position - bufferStart));
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException(
                        "Trying to set the buffer position to " + position + " - " + bufferStart + " = "
                                + (position - bufferStart) + " with a buffer of size " + getBufferSize(),
                        e);
            }
        }
    }
    this.position = position;
}

From source file:com.maverick.http.HttpResponse.java

protected String readLine(InputStream in) throws IOException {
    StringBuffer lineBuf = new StringBuffer();
    int c;/*w ww.  ja va2s .  c om*/

    while (true) {
        c = in.read();

        if (c == -1) {
            if (lineBuf.length() == 0)
                throw new EOFException(Messages.getString("HttpResponse.unexpectedEOF")); //$NON-NLS-1$

            break;
        }

        if (c != '\n') {
            lineBuf.append((char) c);
        } else {
            break;
        }
    }

    return lineBuf.toString().trim();
}

From source file:org.apache.hadoop.hbase.index.IndexSpecification.java

/**
 * @param Data Input Stream//from   ww w .  j ava 2  s  . c o m
 * @throws IOException
 */
public void readFields(DataInput in) throws IOException {
    this.name = Bytes.readByteArray(in);
    try {
        HTableDescriptor.isLegalTableName(this.name);
    } catch (IllegalArgumentException e) {
        String msg = "Received unexpected data while parsing the column qualifiers :"
                + Bytes.toString(this.name) + ".";
        Log.warn(msg + " Could be an non-indexed table.");
        throw new EOFException(msg);
    }
    int indexColsSize = in.readInt();
    indexColumns.clear();
    for (int i = 0; i < indexColsSize; i++) {
        ColumnQualifier cq = new ColumnQualifier();
        // Need to revisit this place. May be some other valid value though invalid
        // comes up.
        try {
            cq.readFields(in);
        } catch (IllegalArgumentException e) {
            throw new EOFException("Received unexpected data while parsing the column qualifiers.");
        }
        internalAdd(cq);
    }
    this.maxVersions = in.readInt();
    this.ttl = in.readLong();
}

From source file:com.microsoft.azure.storage.analytics.LogRecordStreamReader.java

/**
 * Read a field from the stream.//from   w  w w. j av  a 2  s .c o  m
 * 
 * @param isQuotedString
 *            whether the field is encased in quotes and escaped.
 * @return
 *         the field read.
 * @throws IOException
 */
private String readField(boolean isQuotedString) throws IOException {
    if (!this.isFirstFieldInRecord) {
        this.readDelimiter(LogRecordStreamReader.FIELD_DELIMITER);
    } else {
        this.isFirstFieldInRecord = false;
    }

    // Read a field, handling field/record delimiters in quotes and not counting them,
    // and also check that there are no record delimiters since they are only expected
    // outside of a field.
    // Note: We only need to handle strings that are quoted once from the beginning,
    // (e.g. "mystring"). We do not need to handle nested quotes or anything because
    // we control the string format. 
    StringBuilder fieldBuilder = new StringBuilder();
    boolean hasSeenQuoteForQuotedString = false;
    boolean isExpectingDelimiterForNextCharacterForQuotedString = false;
    while (true) {
        // If EOF when we haven't read the delimiter; unexpected.
        if (this.isEndOfFile()) {
            throw new EOFException(SR.LOG_STREAM_END_ERROR);
        }

        // Since we just checked isEndOfFile above, we know this is a char.
        char c = (char) this.peek();

        // If we hit a delimiter that is not quoted or we hit the delimiter for
        // a quoted string or we hit the empty value string and hit a delimiter,
        // then we have finished reading the field.
        // Note: The empty value string is the only string that we don't require
        // quotes for for a quoted string.
        if ((!isQuotedString || isExpectingDelimiterForNextCharacterForQuotedString
                || fieldBuilder.length() == 0)
                && (c == LogRecordStreamReader.FIELD_DELIMITER
                        || c == LogRecordStreamReader.RECORD_DELIMITER)) {
            // The delimiter character was peeked but not read -- they'll be consumed 
            // on either the next call to readField or to EndCurrentRecord.
            break;
        }

        if (isExpectingDelimiterForNextCharacterForQuotedString) {
            // We finished reading a quoted string but found no delimiter following it.
            throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR);
        }

        // The character was not a delimiter, so consume and add to builder.
        this.read();
        fieldBuilder.append(c);

        // We need to handle quotes specially since quoted delimiters
        // do not count since they are considered to be part of the
        // quoted string and not actually a delimiter.
        // Note: We use a specific quote character since we control the format
        // and we only allow non-encoded quote characters at the beginning/end
        // of the string.
        if (c == LogRecordStreamReader.QUOTE_CHAR) {
            if (!isQuotedString) {
                // Non-encoded quote character only allowed for quoted strings.
                throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR);
            } else if (fieldBuilder.length() == 1) {
                // Opening quote for a quoted string.
                hasSeenQuoteForQuotedString = true;
            } else if (hasSeenQuoteForQuotedString) {
                // Closing quote for a quoted string.
                isExpectingDelimiterForNextCharacterForQuotedString = true;
            } else {
                // Unexpected non-encoded quote.
                throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR);
            }
        }
    }

    String field;

    // Note: For quoted strings we remove the quotes.
    // We do not do this for the empty value string since it represents empty
    // and we don't write that out in quotes even for quoted strings.
    if (isQuotedString && fieldBuilder.length() != 0) {
        field = fieldBuilder.substring(1, fieldBuilder.length() - 1);
    } else {
        field = fieldBuilder.toString();
    }

    return field;
}