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.sshtools.daemon.scp.ScpServer.java

private void waitForResponse() throws IOException {
    log.debug("Waiting for response");

    int r = pipeOut.read();

    if (r == 0) {
        log.debug("Got Ok");

        // All is well, no error
        return;//from  ww w  .ja va  2  s  .co  m
    }

    if (r == -1) {
        throw new EOFException("SCP returned unexpected EOF");
    }

    String msg = readString();
    log.debug("Got error '" + msg + "'");

    if (r == (byte) '\02') {
        log.debug("This is a serious error");
        throw new IOException(msg);
    }

    throw new IOException("SCP returned an unexpected error: " + msg);
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Consumes the content and writes it to the ServletOutputStream.
 *//*  www .  j a  v a 2s .  c o  m*/
private static void copy(final MCRContent content, final ServletOutputStream out, final int inputBufferSize,
        final int outputBufferSize) throws IOException {
    final long bytesCopied;
    long length = content.length();
    if (content instanceof MCRSeekableChannelContent) {
        try (SeekableByteChannel byteChannel = ((MCRSeekableChannelContent) content).getSeekableByteChannel();
                WritableByteChannel nout = Channels.newChannel(out)) {
            endCurrentTransaction();
            bytesCopied = copyChannel(byteChannel, nout, outputBufferSize);
        }
    } else {
        try (InputStream contentIS = content.getInputStream();
                final InputStream in = isInputStreamBuffered(contentIS, content) ? contentIS
                        : new BufferedInputStream(contentIS, inputBufferSize);) {
            endCurrentTransaction();
            // Copy the inputBufferSize stream to the outputBufferSize stream
            bytesCopied = IOUtils.copyLarge(in, out, new byte[outputBufferSize]);
        }
    }
    if (length >= 0 && length != bytesCopied) {
        throw new EOFException("Bytes to send: " + length + " actual: " + bytesCopied);
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Wrote " + bytesCopied + " bytes.");
    }
}

From source file:org.everrest.websockets.client.WSClient.java

private void read() throws IOException {
    while (connected) {
        final int firstByte = in.read();
        if (firstByte < 0) {
            throw new EOFException("Failed read next websocket frame, end of the stream was reached. ");
        }/* w ww . ja v  a2s  . c o  m*/

        // Check most significant bit in this byte. It always set in '1' if this fragment is final fragment.
        // In other word each message may not be sent in more then one fragment.
        final boolean fin = (firstByte & 0x80) != 0;
        final byte opCode = (byte) (firstByte & 0x0F);

        byte[] payload;
        switch (opCode) {
        case 0: // continuation frame
            payload = readFrame();
            saveInInputBuffer(payload);
            // Only data frames might be fragmented. Control frames may not be fragmented.
            // So we can't get here with any control frames, e.g. with ping/pong messages.
            if (fin) {
                if (type == TEXT) {
                    onMessage(getStringFormInputBuffer());
                } else if (type == BIN) {
                    onMessage(getBytesFormInputBuffer());
                }
            }
            break;
        case 1: // text frame
            payload = readFrame();
            if (fin) {
                onMessage(new String(payload, UTF8_CS));
            } else {
                saveInInputBuffer(payload);
                type = TEXT;
            }
            break;
        case 2: // binary frame
            payload = readFrame();
            if (fin) {
                onMessage(payload);
            } else {
                saveInInputBuffer(payload);
                type = BIN;
            }
            break;
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            // Do nothing fo this. They are reserved for further non-control frames.
            break;
        case 8: // connection close
            payload = readFrame();
            int status;
            // Read status.
            if (payload.length > 0) {
                status = ((payload[0] & 0xFF) << 8);
                status += (payload[1] & 0xFF);
            } else {
                status = 0; // No status.
            }
            String message = null;
            if (!(status == 0 || status == 1000)) {
                // Two bytes contains status code. The rest of bytes is message.
                if (payload.length > 2) {
                    message = new String(payload, 2, payload.length - 2, UTF8_CS);
                }
                LOG.warn("Close status: {}, message: {} ", status, message);
            }
            // Specification says: body is not guaranteed to be human readable.
            // Send body to the listeners here if server provides it and let listeners decide what to do.
            onClose(status, message);
            break;
        case 9: // ping
            payload = readFrame();
            // 'pong' response for the 'ping' message.
            writeFrame((byte) 0x8A, payload);
            LOG.debug("Ping: {} ", new String(payload, UTF8_CS));
            break;
        case 0x0A: // pong
            payload = readFrame();
            onPong(payload);
            break;
        case 0x0B:
        case 0x0C:
        case 0x0D:
        case 0x0E:
        case 0x0F:
            // Do nothing fo this.
            break;
        default:
            throw new ConnectionException(1003,
                    String.format("Invalid opcode: '%s' ", Integer.toHexString(opCode)));
        }
        if (socket.isClosed()) {
            // May be server going down, we did not receive 'close' op_code but connection is lost.
            onClose(1006, null);
        }
    }
}

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

@Override
public void readFully(byte[] buf, int offset, int length) throws IOException {
    int got = read(buf, offset, length);
    if (got < length) {
        throw new EOFException("Reached end of file '" + file + "' at " + position + " with " + (length - got)
                + " bytes yet to read");
    }//www.  j av a 2s. c  o  m
    if (log.isTraceEnabled()) {
        log.trace("Read " + length + " bytes from file '" + file + "' from offset " + (position - length)
                + " to " + position);
    }
}

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

/**
 * Subclass {@code readFully()} operation which only seeks at the start
 * of the series of operations; seeking back at the end.
 *
 * This is significantly higher performance if multiple read attempts are
 * needed to fetch the data, as it does not break the HTTP connection.
 *
 * To maintain thread safety requirements, this operation is synchronized
 * for the duration of the sequence.//from w  w w .j av  a  2s. c  o m
 * {@inheritDoc}
 *
 */
@Override
public void readFully(long position, byte[] buffer, int offset, int length) throws IOException {
    checkNotClosed();
    validatePositionedReadArgs(position, buffer, offset, length);
    streamStatistics.readFullyOperationStarted(position, length);
    if (length == 0) {
        return;
    }
    int nread = 0;
    synchronized (this) {
        long oldPos = getPos();
        try {
            seek(position);
            while (nread < length) {
                int nbytes = read(buffer, offset + nread, length - nread);
                if (nbytes < 0) {
                    throw new EOFException(FSExceptionMessages.EOF_IN_READ_FULLY);
                }
                nread += nbytes;
            }
        } finally {
            seekQuietly(oldPos);
        }
    }
}

From source file:com.emc.atmos.api.jersey.EsuApiJerseyAdapter.java

private byte[] readObject(ObjectIdentifier identifier, Extent extent, byte[] buffer, Checksum checksum) {
    try {/*from w  w  w . j  av a 2 s .com*/
        if (buffer != null && extent != null && extent.getSize() > (long) buffer.length) {
            throw new IllegalArgumentException("The buffer is smaller than the requested extent");
        }

        ReadObjectResponse<InputStream> response = adaptee.readObjectStream(identifier, adaptExtent(extent));

        long contentLength = response.getContentLength();
        if (buffer != null && contentLength > -1) {
            if ((long) buffer.length < contentLength) {
                throw new EsuException("The response buffer was not long enough to hold the response: "
                        + buffer.length + "<" + contentLength);
            }
            int read, c = 0;
            InputStream in = response.getObject();
            while (c < contentLength) {
                read = in.read(buffer, c, (int) contentLength - c);
                if (read == -1) {
                    throw new EOFException(
                            "EOF reading response at position " + c + " size " + (contentLength - c));
                }
                c += read;
            }
        } else {
            if (contentLength > Integer.MAX_VALUE)
                throw new EsuException("Object is too large to hold in a byte array");
            buffer = StreamUtil.readAsBytes(response.getObject());
        }

        if (checksum != null && response.getWsChecksum() != null) {
            checksum.setExpectedValue(response.getWsChecksum().toString());
            if (contentLength > -1)
                checksum.update(buffer, 0, (int) contentLength);
            else
                checksum.update(buffer, 0, buffer.length);
        }

        return buffer;
    } catch (IOException e) {
        throw new EsuException("Error connecting to server", e);
    }
}

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

public HttpResponse execute(HttpMethod method) throws UnknownHostException, IOException, HttpException,
        UnsupportedAuthenticationException, AuthenticationCancelledException {
    // #ifdef DEBUG
    log.debug(MessageFormat.format(Messages.getString("HttpClient.executing"), //$NON-NLS-1$
            new Object[] { method.getName() }));
    // #endif/*from  w  w w .  j a v  a  2  s.  c  o m*/
    for (int i = 0; i < 2; i++) {
        try {
            return execute(method, connections.getConnection());
        } catch (EOFException eof) {
            // #ifdef DEBUG
            if (i != 1) {
                log.warn(MessageFormat.format(Messages.getString("HttpClient.eof.attemptingAgain"), //$NON-NLS-1$
                        new Object[] { new Integer(i) }));
            } else {
                log.warn(MessageFormat.format(Messages.getString("HttpClient.eof.givingUp"), //$NON-NLS-1$
                        new Object[] { new Integer(i) }));
            }
            // #endif
        }
    }
    throw new EOFException(Messages.getString("HttpClient.couldNotConnect")); //$NON-NLS-1$
}

From source file:com.sshtools.daemon.vfs.VirtualFileSystem.java

/**
 *
 *
 * @param handle//from w  w w. ja va 2 s.co  m
 *
 * @return
 *
 * @throws InvalidHandleException
 * @throws EOFException
 * @throws IOException
 */
public SftpFile[] readDirectory(byte[] handle) throws InvalidHandleException, EOFException, IOException {
    String shandle = new String(handle);

    if (openFiles.containsKey(shandle)) {
        Object obj = openFiles.get(shandle);

        if (obj instanceof OpenDirectory) {
            OpenDirectory dir = (OpenDirectory) obj;
            int pos = dir.getPosition();
            File[] children = dir.getChildren();

            if (children == null) {
                throw new IOException("Permission denined.");
            }

            int count = ((children.length - pos) < 100) ? (children.length - pos) : 100;

            if (count > 0) {
                SftpFile[] files = new SftpFile[count];

                for (int i = 0; i < files.length; i++) {
                    File f = children[pos + i];
                    String absolutePath = dir.realPath + "/" + f.getName();
                    SftpFile sftpfile = new SftpFile(f.getName(), getFileAttributes(absolutePath));
                    files[i] = sftpfile;
                }

                dir.readpos = pos + files.length;

                return files;
            } else {
                throw new EOFException("There are no more files");
            }
        } else {
            throw new InvalidHandleException("Handle is not an open directory");
        }
    } else {
        throw new InvalidHandleException("The handle is invalid");
    }
}

From source file:com.google.android.gms.internal.zzbti.java

private int zzbh(boolean z) throws IOException {
    char[] cArr = this.zzcpH;
    int i = this.pos;
    int i2 = this.limit;
    while (true) {
        int lineNumber;
        if (i == i2) {
            this.pos = i;
            if (zzqe(1)) {
                i = this.pos;
                i2 = this.limit;
            } else if (!z) {
                return -1;
            } else {
                String valueOf = String.valueOf("End of input at line ");
                lineNumber = getLineNumber();
                throw new EOFException(new StringBuilder(String.valueOf(valueOf).length() + 30).append(valueOf)
                        .append(lineNumber).append(" column ").append(getColumnNumber()).toString());
            }/*  w  w w.  java2s. c  o  m*/
        }
        lineNumber = i + 1;
        char c = cArr[i];
        if (c == '\n') {
            this.zzcpI++;
            this.zzcpJ = lineNumber;
            i = lineNumber;
        } else if (c == ' ' || c == '\r') {
            i = lineNumber;
        } else if (c == '\t') {
            i = lineNumber;
        } else if (c == '/') {
            this.pos = lineNumber;
            if (lineNumber == i2) {
                this.pos--;
                boolean zzqe = zzqe(2);
                this.pos++;
                if (!zzqe) {
                    return c;
                }
            }
            zzaci();
            switch (cArr[this.pos]) {
            case C0394R.styleable.AppCompatTheme_textAppearancePopupMenuHeader /*42*/:
                this.pos++;
                if (zzjY("*/")) {
                    i = this.pos + 2;
                    i2 = this.limit;
                    break;
                }
                throw zzjZ("Unterminated comment");
            case C0394R.styleable.AppCompatTheme_dropdownListPreferredItemHeight /*47*/:
                this.pos++;
                zzacj();
                i = this.pos;
                i2 = this.limit;
                break;
            default:
                return c;
            }
        } else if (c == '#') {
            this.pos = lineNumber;
            zzaci();
            zzacj();
            i = this.pos;
            i2 = this.limit;
        } else {
            this.pos = lineNumber;
            return c;
        }
    }
}

From source file:org.sonatype.nexus.proxy.SimplePullTest.java

/**
 * NXCM-4582: When Local storage is about to store something, but during "store" operation source stream EOFs, the
 * new LocalStorage exception should be thrown, to differentiate from other "fatal" (like disk full or what not)
 * error./* w  w  w  . j  a  v  a  2s.co m*/
 */
@Test
public void testNXCM4852() throws Exception {
    final Repository repository = getRepositoryRegistry().getRepository("inhouse");
    final ResourceStoreRequest request = new ResourceStoreRequest(
            "/activemq/activemq-core/1.2/activemq-core-1.2.jar", true);

    try {
        repository.storeItem(request,
                new FilterInputStream(new ByteArrayInputStream("123456789012345678901234567890".getBytes())) {
                    @Override
                    public int read() throws IOException {
                        int result = super.read();
                        if (result == -1) {
                            throw new EOFException("Foo");
                        } else {
                            return result;
                        }
                    }

                    @Override
                    public int read(final byte[] b, final int off, final int len) throws IOException {
                        int result = super.read(b, off, len);
                        if (result == -1) {
                            throw new EOFException("Foo");
                        }
                        return result;
                    }
                }, null);

        fail("We expected a LocalStorageEofException to be thrown");
    } catch (LocalStorageEOFException e) {
        // good, we expected this
    } finally {
        // now we have to ensure no remnant files exists
        assertThat(repository.getLocalStorage().containsItem(repository, request), is(false));
        // no tmp files should exists either
        assertThat(repository.getLocalStorage().listItems(repository, new ResourceStoreRequest("/.nexus/tmp")),
                is(empty()));
    }
}