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.everrest.websockets.client.WSClient.java

private byte[] readFrame() throws IOException {
    // This byte contains info about message mask and about length of payload.
    final int secondByte = in.read();
    if (secondByte < 0) {
        throw new EOFException("Failed read next websocket frame, end of the stream was reached. ");
    }//w ww  .ja v a  2  s  .co  m

    final boolean masked = (secondByte & 0x80) > 0;

    long length = (secondByte & 0x7F);
    if (length == 126) {
        byte[] block = new byte[2];
        readBlock(block);
        length = getPayloadLength(block);
    } else if (length == 127) {
        byte[] block = new byte[8];
        readBlock(block);
        length = getPayloadLength(block);
    }

    byte[] mask = null;
    if (masked) {
        mask = new byte[MASK_SIZE];
        readBlock(mask);
    }

    if (length > maxMessagePayloadSize) {
        throw new IOException(String.format("Message payload is to large, may not be greater than %d",
                maxMessagePayloadSize));
    }
    // Payload may not greater then max integer: (2^31)-1
    final byte[] payload = new byte[(int) length];
    readBlock(payload);

    if (mask != null) {
        // Unmask payload bytes if they masked.
        for (int i = 0; i < payload.length; i++) {
            payload[i] = (byte) (payload[i] ^ mask[i % 4]);
        }
    }

    return payload;
}

From source file:com.sshtools.daemon.scp.ScpServer.java

private void readFromRemote(String path) throws IOException {
    String cmd;/*  www.j  a  v a2 s  .  c  o m*/
    String[] cmdParts = new String[3];

    writeOk();

    while (true) {
        log.debug("Waiting for command");

        try {
            cmd = readString();
        } catch (EOFException e) {
            return;
        }

        log.debug("Got command '" + cmd + "'");

        char cmdChar = cmd.charAt(0);

        switch (cmdChar) {
        case 'E':
            writeOk();

            return;

        case 'T':
            log.error("SCP time not currently supported");
            writeError("WARNING: This server does not currently support the SCP time command");

            break;

        case 'C':
        case 'D':
            parseCommand(cmd, cmdParts);

            FileAttributes attr = null;

            try {
                log.debug("Getting attributes for current destination (" + path + ")");
                attr = nfs.getFileAttributes(path);
            } catch (FileNotFoundException fnfe) {
                log.debug("Current destination not found");
            }

            String targetPath = path;
            String name = cmdParts[2];

            if ((attr != null) && attr.isDirectory()) {
                log.debug("Target is a directory");
                targetPath += ('/' + name);
            }

            FileAttributes targetAttr = null;

            try {
                log.debug("Getting attributes for target destination (" + targetPath + ")");
                targetAttr = nfs.getFileAttributes(targetPath);
            } catch (FileNotFoundException fnfe) {
                log.debug("Target destination not found");
            }

            if (cmdChar == 'D') {
                log.debug("Got directory request");

                if (targetAttr != null) {
                    if (!targetAttr.isDirectory()) {
                        String msg = "Invalid target " + name + ", must be a directory";
                        writeError(msg);
                        throw new IOException(msg);
                    }
                } else {
                    try {
                        log.debug("Creating directory " + targetPath);

                        if (!nfs.makeDirectory(targetPath)) {
                            String msg = "Could not create directory: " + name;
                            writeError(msg);
                            throw new IOException(msg);
                        } else {
                            log.debug("Setting permissions on directory");
                            attr.setPermissionsFromMaskString(cmdParts[0]);
                        }
                    } catch (FileNotFoundException e1) {
                        writeError("File not found");
                        throw new IOException("File not found");
                    } catch (PermissionDeniedException e1) {
                        writeError("Permission denied");
                        throw new IOException("Permission denied");
                    }
                }

                readFromRemote(targetPath);

                continue;
            }

            log.debug("Opening file for writing");

            byte[] handle = null;

            try {
                // Open the file
                handle = nfs.openFile(targetPath,
                        new UnsignedInteger32(NativeFileSystemProvider.OPEN_CREATE
                                | NativeFileSystemProvider.OPEN_WRITE | NativeFileSystemProvider.OPEN_TRUNCATE),
                        attr);
                log.debug("NFS file opened");
                writeOk();
                log.debug("Reading from client");

                int count = 0;
                int read;
                long length = Long.parseLong(cmdParts[1]);

                while (count < length) {
                    read = pipeOut.read(buffer, 0,
                            (int) (((length - count) < buffer.length) ? (length - count) : buffer.length));

                    if (read == -1) {
                        throw new EOFException("ScpServer received an unexpected EOF during file transfer");
                    }

                    log.debug("Got block of " + read);
                    nfs.writeFile(handle, new UnsignedInteger64(String.valueOf(count)), buffer, 0, read);
                    count += read;
                }

                log.debug("File transfer complete");
            } catch (InvalidHandleException ihe) {
                writeError("Invalid handle.");
                throw new IOException("Invalid handle.");
            } catch (FileNotFoundException e) {
                writeError("File not found");
                throw new IOException("File not found");
            } catch (PermissionDeniedException e) {
                writeError("Permission denied");
                throw new IOException("Permission denied");
            } finally {
                if (handle != null) {
                    try {
                        log.debug("Closing handle");
                        nfs.closeFile(handle);
                    } catch (Exception e) {
                    }
                }
            }

            waitForResponse();

            if (preserveAttributes) {
                attr.setPermissionsFromMaskString(cmdParts[0]);
                log.debug("Setting permissions on directory to " + attr.getPermissionsString());

                try {
                    nfs.setFileAttributes(targetPath, attr);
                } catch (Exception e) {
                    writeError("Failed to set file permissions.");

                    break;
                }
            }

            writeOk();

            break;

        default:
            writeError("Unexpected cmd: " + cmd);
            throw new IOException("SCP unexpected cmd: " + cmd);
        }
    }
}

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

/**
 * Copy the content with the specified range of bytes from InputStream to OutputStream.
 *
 * @param in The input//from  w w  w. j  a  va  2s .co m
 * @param out The output
 * @param inPosition Current position of the input
 * @param start Start position to be copied
 * @param end End position to be copied
 * @return Exception which occurred during processing or if less than <code>end - start + 1</code> bytes were read/written.
 */
private static IOException copyRange(final InputStream in, final ServletOutputStream out, final long inPosition,
        final long start, final long end, final int outputBufferSize) {

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Serving bytes:" + start + "-" + end);
    }

    final long bytesToRead = end - start + 1;
    final long skip = start - inPosition;
    try {
        final long copied = copyLarge(in, out, skip, bytesToRead, new byte[outputBufferSize]);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Served bytes:" + copied);
        }
        if (copied != bytesToRead) {
            return new EOFException("Bytes to send: " + bytesToRead + " actual: " + copied);
        }
    } catch (final IOException e) {
        return e;
    }
    return null;
}

From source file:com.emc.ecs.smart.SmartUploader.java

private void doUploadSegment(int segmentNumber) throws IOException {
    // Calculate the segment
    long segmentStart = (long) segmentNumber * (long) segmentSize;
    int segmentLength = segmentSize;
    if (segmentStart + segmentLength > fileSize) {
        segmentLength = (int) (fileSize - segmentStart);
    }//from ww w .j a va  2  s  .  c  o m
    LogMF.debug(l4j, "Segment {0} is {1} bytes at position {2}", segmentNumber, segmentLength, segmentStart);

    ByteBuffer buf;
    if (segmentLength == segmentSize) {
        buf = getBuffer();
    } else {
        buf = ByteBuffer.allocateDirect(segmentLength);
    }
    int c;
    synchronized (fileChannel) {
        c = fileChannel.read(buf, segmentStart);
    }

    if (c == -1) {
        throw new EOFException("Unexpected EOF at offset " + segmentStart);
    }

    if (c != buf.capacity()) {
        // Didn't read expected number?
        throw new IOException(
                String.format("Read %d bytes, expected %d at offset %d", c, segmentLength, segmentStart));
    }

    // Make an MD5 so we can use Content-MD5.
    String md5 = calculateMD5(buf);

    // We have our data.  Now upload it.
    WebResource.Builder builder;
    try {
        builder = client.resource(uploadUrl.toURI()).getRequestBuilder();
    } catch (URISyntaxException e) {
        // Shouldn't happen; by now we've already parsed the URI
        throw new RuntimeException("Could not construct request", e);
    }
    builder.header(HttpHeaders.CONTENT_LENGTH, segmentLength)//.header("Content-MD5", md5)
            .header(HttpHeaders.CONTENT_TYPE, contentType);
    if (segmentNumber != 0) {
        builder.header("Range", buildRange(segmentStart, segmentLength));
    }
    builder.put(new ByteBufferInputStream(buf));

    incrementUpload(segmentLength);
    printPercent();

    if (segmentLength == segmentSize) {
        returnBuffer(buf);
    }
}

From source file:com.sshtools.daemon.scp.ScpServer.java

private String readString() throws IOException {
    int ch;/*from  w w w .  ja v a  2  s  . c  om*/
    int i = 0;

    while (((ch = pipeOut.read()) != ((int) '\n')) && (ch >= 0)) {
        buffer[i++] = (byte) ch;
    }

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

    if (buffer[0] == (byte) '\n') {
        throw new IOException("Unexpected <NL>");
    }

    if ((buffer[0] == (byte) '\02') || (buffer[0] == (byte) '\01')) {
        String msg = new String(buffer, 1, i - 1);

        if (buffer[0] == (byte) '\02') {
            throw new IOException(msg);
        }

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

    return new String(buffer, 0, i);
}

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

/**
 *
 *
 * @param handle/*  w  ww .  j  a  va2 s  .  c  om*/
 * @param offset
 * @param len
 *
 * @return
 *
 * @throws InvalidHandleException
 * @throws EOFException
 * @throws IOException
 */
public byte[] readFile(byte[] handle, UnsignedInteger64 offset, UnsignedInteger32 len)
        throws InvalidHandleException, EOFException, IOException {
    String shandle = new String(handle);

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

        if (obj instanceof OpenFile) {
            OpenFile file = (OpenFile) obj;

            if ((file.getFlags().intValue()
                    & NativeFileSystemProvider.OPEN_READ) == NativeFileSystemProvider.OPEN_READ) {
                byte[] buf = new byte[len.intValue()];

                if (file.getRandomAccessFile().getFilePointer() != offset.longValue()) {
                    file.getRandomAccessFile().seek(offset.longValue());
                }

                int read = file.getRandomAccessFile().read(buf);

                if (read >= 0) {
                    if (read == buf.length) {
                        return buf;
                    } else {
                        byte[] tmp = new byte[read];
                        System.arraycopy(buf, 0, tmp, 0, read);

                        return tmp;
                    }
                } else {
                    throw new EOFException("The file is EOF");
                }
            } else {
                throw new InvalidHandleException("The file handle was not opened for reading");
            }
        } else {
            throw new InvalidHandleException("Handle is not an open file");
        }
    } else {
        throw new InvalidHandleException("The handle is invalid");
    }
}

From source file:org.apache.tajo.pullserver.PullServerUtil.java

/**
 * Retrieve file chunks which correspond to the requested URI.
 * Only the file chunks which has non-zero length are retrieved.
 *
 * @param conf/*from   w w  w. j  a  v a  2 s  . com*/
 * @param lDirAlloc
 * @param localFS
 * @param params
 * @param indexReaderCache
 * @param lowCacheHitCheckThreshold
 * @return
 * @throws IOException
 * @throws ExecutionException
 */
public static List<FileChunk> getFileChunks(final TajoConf conf, final LocalDirAllocator lDirAlloc,
        final FileSystem localFS, final PullServerParams params,
        final LoadingCache<IndexCacheKey, BSTIndexReader> indexReaderCache, final int lowCacheHitCheckThreshold)
        throws IOException, ExecutionException {
    final List<FileChunk> chunks = new ArrayList<>();

    final String queryId = params.queryId();
    final String shuffleType = params.shuffleType();
    final String sid = params.ebId();

    final long offset = params.offset();
    final long length = params.length();

    final Path queryBaseDir = PullServerUtil.getBaseOutputDir(queryId, sid);

    if (LOG.isDebugEnabled()) {
        LOG.debug("PullServer request param: shuffleType=" + shuffleType + ", sid=" + sid);

        // the working dir of tajo worker for each query
        LOG.debug("PullServer baseDir: " + conf.get(ConfVars.WORKER_TEMPORAL_DIR.varname) + "/" + queryBaseDir);
    }

    // if a stage requires a range shuffle
    if (PullServerUtil.isRangeShuffle(shuffleType)) {
        final List<String> taskIdList = params.taskAttemptIds();
        final List<String> taskIds = PullServerUtil.splitMaps(taskIdList);

        final String startKey = params.startKey();
        final String endKey = params.endKey();
        final boolean last = params.last();

        long before = System.currentTimeMillis();
        for (String eachTaskId : taskIds) {
            Path outputPath = StorageUtil.concatPath(queryBaseDir, eachTaskId, "output");
            if (!lDirAlloc.ifExists(outputPath.toString(), conf)) {
                LOG.warn(outputPath + " does not exist.");
                continue;
            }
            Path path = localFS.makeQualified(lDirAlloc.getLocalPathToRead(outputPath.toString(), conf));

            FileChunk chunk = PullServerUtil.searchFileChunk(queryId, sid, path, startKey, endKey, last,
                    indexReaderCache, lowCacheHitCheckThreshold);
            if (chunk != null) {
                chunks.add(chunk);
            }
        }
        long after = System.currentTimeMillis();
        LOG.info("Index lookup time: " + (after - before) + " ms");

        // if a stage requires a hash shuffle or a scattered hash shuffle
    } else if (PullServerUtil.isHashShuffle(shuffleType)) {

        final String partId = params.partId();
        int partParentId = HashShuffleAppenderManager.getPartParentId(Integer.parseInt(partId), conf);
        Path partPath = StorageUtil.concatPath(queryBaseDir, "hash-shuffle", String.valueOf(partParentId),
                partId);
        if (!lDirAlloc.ifExists(partPath.toString(), conf)) {
            throw new FileNotFoundException(partPath.toString());
        }

        Path path = localFS.makeQualified(lDirAlloc.getLocalPathToRead(partPath.toString(), conf));

        File file = new File(path.toUri());
        long startPos = (offset >= 0 && length >= 0) ? offset : 0;
        long readLen = (offset >= 0 && length >= 0) ? length : file.length();

        if (startPos >= file.length()) {
            String errorMessage = "Start pos[" + startPos + "] great than file length [" + file.length() + "]";
            throw new EOFException(errorMessage);
        }
        FileChunk chunk = new FileChunk(file, startPos, readLen);
        chunks.add(chunk);
    } else {
        throw new IllegalArgumentException(shuffleType);
    }
    return chunks.stream().filter(c -> c.length() > 0).collect(Collectors.toList());
}

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

private void readBlock(byte[] buff) throws IOException {
    int offset = 0;
    int length = buff.length;
    int r;//from w  w  w. j  a  v  a2 s.c om
    while (offset < buff.length) {
        r = in.read(buff, offset, length - offset);
        if (r < 0) {
            throw new EOFException("Failed read next websocket frame, end of the stream was reached. ");
        }
        offset += r;
    }
}

From source file:org.apache.hadoop.hive.ql.exec.vector.VectorDeserializeRow.java

private void throwMoreDetailedException(IOException e, int index) throws EOFException {
    StringBuilder sb = new StringBuilder();
    sb.append("Detail: \"" + e.toString() + "\" occured for field " + index + " of " + primitiveTypeInfos.length
            + " fields (");
    for (int i = 0; i < primitiveTypeInfos.length; i++) {
        if (i > 0) {
            sb.append(", ");
        }/*from   www. j a v  a2  s  .c om*/
        sb.append(primitiveTypeInfos[i].getPrimitiveCategory().name());
    }
    sb.append(")");
    throw new EOFException(sb.toString());
}

From source file:org.apache.fontbox.ttf.TTFSubsetter.java

private long copyBytes(InputStream is, OutputStream os, long newOffset, long lastOffset, int count)
        throws IOException {
    // skip over from last original offset
    long nskip = newOffset - lastOffset;
    if (nskip != is.skip(nskip)) {
        throw new EOFException("Unexpected EOF exception parsing glyphId of hmtx table.");
    }/* w  ww  .j ava  2 s.c  o m*/
    byte[] buf = new byte[count];
    if (count != is.read(buf, 0, count)) {
        throw new EOFException("Unexpected EOF exception parsing glyphId of hmtx table.");
    }
    os.write(buf, 0, count);
    return newOffset + count;
}