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.fs.nfs.stream.NFSBufferedInputStream.java

@Override
public synchronized void seek(long pos) throws IOException {
    if (pos > fileLength) {
        throw new EOFException("Cannot seek after EOF: pos=" + pos + ", fileLength=" + fileLength);
    }/*from  www. j  ava2s.  c o  m*/
    fileOffset = pos;
    prefetchBlockLimit = (long) (Math.min(fileLength, pos + this.splitSize) >> readBlockSizeBits);
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcherTest.java

@Test
public void testToByteArraySafeThrowsException3() throws Exception {
    EasyMock.reset(mockInputStream);//from  w w  w .j  a  v a2 s . c o m
    mockInputStream.close();

    // Return non-zero for 'InputStream.available()'. This should violate the other condition.
    EasyMock.expect(mockInputStream.available()).andReturn(1);
    String exceptionMessage = "Unexpected end of ZLIB input stream";
    EOFException e = new EOFException(exceptionMessage);
    EasyMock.expect(mockInputStream.read(EasyMock.isA(byte[].class))).andThrow(e).anyTimes();

    EasyMock.replay(mockEntity, mockInputStream);
    boolean exceptionCaught = false;

    try {
        fetcher.toByteArraySafe(mockEntity);
    } catch (EOFException eofe) {
        assertEquals(exceptionMessage, eofe.getMessage());
        exceptionCaught = true;
    }
    EasyMock.verify(mockEntity, mockInputStream);
    assertTrue(exceptionCaught);
}

From source file:org.apache.ratis.server.storage.LogReader.java

String readLogHeader() throws IOException {
    byte[] header = new byte[SegmentedRaftLog.HEADER_BYTES.length];
    int num = in.read(header);
    if (num < header.length) {
        throw new EOFException("EOF before reading a complete log header");
    }//  www . j a  va2  s  .  co m
    return new String(header, Charsets.UTF_8);
}

From source file:org.argouml.uml.generator.AbstractSection.java

/**
 * write TODO: Check if sections are not used within the file and put them
 * as comments at the end of the file. Hint: use a second Map to compare
 * with the used keys./*from w  ww  .j av a2s  .  c om*/
 *
 * @param filename
 *            the file name
 * @param indent
 *            the current indentation
 * @param outputLostSections
 *            true if lost sections are to be written
 */
public void write(String filename, String indent, boolean outputLostSections) {
    FileReader f = null;
    BufferedReader fr = null;
    FileWriter fw = null;
    try {
        f = new FileReader(filename);
        fr = new BufferedReader(f);
        // TODO: This is using the default platform character encoding
        // specifying an encoding will produce more predictable results
        fw = new FileWriter(filename + ".out");
        String line = "";
        line = fr.readLine();
        while (line != null) {
            String sectionId = getSectId(line);
            if (sectionId != null) {
                String content = mAry.get(sectionId);
                if (content != null) {
                    fw.write(line + LINE_SEPARATOR);
                    fw.write(content);
                    // read until the end section is found, discard
                    // generated content
                    String endSectionId = null;
                    do {
                        line = fr.readLine();
                        if (line == null) {
                            throw new EOFException("Reached end of file while looking "
                                    + "for the end of section with ID = \"" + sectionId + "\"!");
                        }
                        endSectionId = getSectId(line);
                    } while (endSectionId == null);
                    if (!endSectionId.equals(sectionId)) {
                        LOG.log(Level.SEVERE, "Mismatch between sectionId (\"" + sectionId
                                + "\") and endSectionId (\"" + endSectionId + "\")!");
                    }
                }
                mAry.remove(sectionId);
            }
            fw.write(line);
            line = fr.readLine();
            if (line != null) {
                fw.write(LINE_SEPARATOR);
            }
        }
        if ((!mAry.isEmpty()) && (outputLostSections)) {
            fw.write("/* lost code following: " + LINE_SEPARATOR);
            Set mapEntries = mAry.entrySet();
            Iterator itr = mapEntries.iterator();
            while (itr.hasNext()) {
                Map.Entry entry = (Map.Entry) itr.next();
                fw.write(indent + "// section " + entry.getKey() + " begin" + LINE_SEPARATOR);
                fw.write((String) entry.getValue());
                fw.write(indent + "// section " + entry.getKey() + " end" + LINE_SEPARATOR);
            }
            fw.write("*/");
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Error: " + e.toString());
    } finally {
        IOUtils.closeQuietly(fr);
        IOUtils.closeQuietly(fw);
    }
}

From source file:io.fabric8.maven.docker.access.log.LogRequestor.java

/**
 * This is a copy of ByteStreams.readFully(), with the slight change that it throws
 * NoBytesReadException if zero bytes are read. Otherwise it is identical.
 *
 * @param in//www  .j av a2s.  c o  m
 * @param bytes
 * @throws IOException
 */
private void readFully(InputStream in, byte[] bytes) throws IOException {
    int read = ByteStreams.read(in, bytes, 0, bytes.length);
    if (read == 0) {
        throw new NoBytesReadException();
    } else if (read != bytes.length) {
        throw new EOFException(
                "reached end of stream after reading " + read + " bytes; " + bytes.length + " bytes expected");
    }
}

From source file:org.apache.hadoop.fs.s3a.S3AUtils.java

/**
 * Translate an exception raised in an operation into an IOException.
 * The specific type of IOException depends on the class of
 * {@link AmazonClientException} passed in, and any status codes included
 * in the operation. That is: HTTP error codes are examined and can be
 * used to build a more specific response.
 * @param operation operation//ww  w . j a  v  a 2s.c  o  m
 * @param path path operated on (may be null)
 * @param exception amazon exception raised
 * @return an IOE which wraps the caught exception.
 */
@SuppressWarnings("ThrowableInstanceNeverThrown")
public static IOException translateException(String operation, String path, AmazonClientException exception) {
    String message = String.format("%s%s: %s", operation, path != null ? (" on " + path) : "", exception);
    if (!(exception instanceof AmazonServiceException)) {
        return new AWSClientIOException(message, exception);
    } else {

        IOException ioe;
        AmazonServiceException ase = (AmazonServiceException) exception;
        // this exception is non-null if the service exception is an s3 one
        AmazonS3Exception s3Exception = ase instanceof AmazonS3Exception ? (AmazonS3Exception) ase : null;
        int status = ase.getStatusCode();
        switch (status) {

        case 301:
            if (s3Exception != null) {
                if (s3Exception.getAdditionalDetails() != null
                        && s3Exception.getAdditionalDetails().containsKey(ENDPOINT_KEY)) {
                    message = String.format("Received permanent redirect response to "
                            + "endpoint %s.  This likely indicates that the S3 endpoint "
                            + "configured in %s does not match the AWS region containing " + "the bucket.",
                            s3Exception.getAdditionalDetails().get(ENDPOINT_KEY), ENDPOINT);
                }
                ioe = new AWSS3IOException(message, s3Exception);
            } else {
                ioe = new AWSServiceIOException(message, ase);
            }
            break;
        // permissions
        case 401:
        case 403:
            ioe = new AccessDeniedException(path, null, message);
            ioe.initCause(ase);
            break;

        // the object isn't there
        case 404:
        case 410:
            ioe = new FileNotFoundException(message);
            ioe.initCause(ase);
            break;

        // out of range. This may happen if an object is overwritten with
        // a shorter one while it is being read.
        case 416:
            ioe = new EOFException(message);
            break;

        default:
            // no specific exit code. Choose an IOE subclass based on the class
            // of the caught exception
            ioe = s3Exception != null ? new AWSS3IOException(message, s3Exception)
                    : new AWSServiceIOException(message, ase);
            break;
        }
        return ioe;
    }
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcherTest.java

@Test
public void testToByteArraySafeHandleException() throws Exception {
    String exceptionMessage = "Unexpected end of ZLIB input stream";
    EOFException e = new EOFException(exceptionMessage);
    EasyMock.expect(mockInputStream.read(EasyMock.isA(byte[].class))).andThrow(e).anyTimes();

    EasyMock.replay(mockEntity, mockInputStream);

    try {/* w ww  .  j  a va  2  s .  c  om*/
        fetcher.toByteArraySafe(mockEntity);
    } catch (EOFException eofe) {
        fail("Exception Should have been caught");
    }
    EasyMock.verify(mockEntity, mockInputStream);
}

From source file:com.continuent.tungsten.common.mysql.MySQLPacket.java

public static MySQLPacket mysqlReadPacket(InputStream in, boolean dropLargePackets)
        throws IOException, EOFException {
    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;
    }/* w  ww  .  j av  a2s  . c om*/
    // This is bad, client went away
    if (packetLen2 == -1 || packetLen3 == -1 || packetNumber == -1) {
        throw new EOFException("Reached end of input stream.");
    }
    if (dropLargePackets && (packetLen == MAX_LENGTH || packetLen == 0)) {
        logger.error("Received packet of size " + packetLen
                + ", but packets bigger than 16 MB are not supported yet!");
        return null;
    }

    // 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;

    // 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) {
        int count = in.read(packetData, HEADER_LENGTH + n, packetLen - n);

        if (count < 0) {
            throw new EOFException("Reached end of input stream.");
        }

        n += count;
    }
    MySQLPacket p = new MySQLPacket(packetLen, packetData, (byte) packetNumber);
    p.setInputStream(in);
    return p;
}

From source file:com.sshtools.j2ssh.transport.TransportProtocolInputStream.java

/**
 *
 *
 * @param buf//from  w w  w. ja v a 2s. c o m
 * @param off
 * @param len
 *
 * @return
 *
 * @throws IOException
 */
protected int readBufferedData(byte[] buf, int off, int len) throws IOException {
    int read;

    if ((endpos - startpos) < len) {
        // Double check the buffer has enough room for the data
        if ((buffered.length - endpos) < len) {
            /*if (log.isDebugEnabled()) {
              log.debug("Trimming used data from buffer");
                     }*/

            // no it does not odds are that the startpos is too high
            System.arraycopy(buffered, startpos, buffered, 0, endpos - startpos);

            endpos -= startpos;

            startpos = 0;

            if ((buffered.length - endpos) < len) {
                //log.debug("Resizing message buffer");
                // Last resort resize the buffer to the required length
                // this should stop any chance of error
                byte[] tmp = new byte[buffered.length + len];

                System.arraycopy(buffered, 0, tmp, 0, endpos);

                buffered = tmp;
            }
        }

        // If there is not enough data then block and read until there is (if still connected)
        while (((endpos - startpos) < len)
                && (transport.getState().getValue() != TransportProtocolState.DISCONNECTED)) {
            try {
                read = in.read(buffered, endpos, (buffered.length - endpos));
            } catch (InterruptedIOException ex) {
                // We have an interrupted io; inform the event handler
                read = ex.bytesTransferred;

                Iterator it = transport.getEventHandlers().iterator();

                TransportProtocolEventHandler eventHandler;

                while (it.hasNext()) {
                    eventHandler = (TransportProtocolEventHandler) it.next();

                    eventHandler.onSocketTimeout(transport);
                }
            }

            if (read < 0) {
                if (transport.getState().getValue() == TransportProtocolState.DISCONNECTED) {
                    throw new EOFException("The remote host has closed the connection.");
                } else {
                    log.error("Buffer empty... EOFException suppressed");
                    read = 0;
                }
            }

            endpos += read;
        }
    }

    try {
        System.arraycopy(buffered, startpos, buf, off, len);

    } catch (Throwable t) {
        System.out.println();
    }
    startpos += len;

    /*if (log.isDebugEnabled()) {
       log.debug("Buffer StartPos=" + String.valueOf(startpos)
        + " EndPos=" + String.valueOf(endpos));
     }*/

    // Try to reset the buffer
    if (startpos >= endpos) {
        //if (log.isDebugEnabled()) {
        // log.debug("Buffer has been reset");
        // }*/
        endpos = 0;

        startpos = 0;
    }

    return len;
}

From source file:org.globus.gsi.X509Credential.java

/**
 * Reads Base64 encoded data from the stream and returns its decoded value. The reading continues until
 * the "END" string is found in the data. Otherwise, returns null.
 *//*from w ww  . j a  va2 s  . c o  m*/
private static byte[] getDecodedPEMObject(BufferedReader reader) throws IOException {
    String line;
    StringBuffer buf = new StringBuffer();
    while ((line = reader.readLine()) != null) {
        if (line.indexOf("--END") != -1) { // found end
            return Base64.decode(buf.toString().getBytes());
        } else {
            buf.append(line);
        }
    }
    throw new EOFException("Missing PEM end footer");
}