Java Code Examples for java.io.EOFException

The following are top voted examples for showing how to use java.io.EOFException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: flume-release-1.7.0   File: LogFile.java   Source Code and License 6 votes vote down vote up
protected static byte[] readDelimitedBuffer(RandomAccessFile fileHandle)
    throws IOException, CorruptEventException {
  int length = fileHandle.readInt();
  if (length < 0) {
    throw new CorruptEventException("Length of event is: " + String.valueOf(length) +
        ". Event must have length >= 0. Possible corruption of data or partial fsync.");
  }
  byte[] buffer = new byte[length];
  try {
    fileHandle.readFully(buffer);
  } catch (EOFException ex) {
    throw new CorruptEventException("Remaining data in file less than " +
                                    "expected size of event.", ex);
  }
  return buffer;
}
 
Example 2
Project: QDrill   File: TextInput.java   Source Code and License 6 votes vote down vote up
/**
 * Skip forward the number of line delimiters.  If you are in the middle of a line,
 * a value of 1 will skip to the start of the next record.
 * @param lines Number of lines to skip.
 * @throws IOException
 */
public final void skipLines(int lines) throws IOException {
  if (lines < 1) {
    return;
  }
  long expectedLineCount = this.lineCount + lines;

  try {
    do {
      nextChar();
    } while (lineCount < expectedLineCount);
    if (lineCount < lines) {
      throw new IllegalArgumentException("Unable to skip " + lines + " lines from line " + (expectedLineCount - lines) + ". End of input reached");
    }
  } catch (EOFException ex) {
    throw new IllegalArgumentException("Unable to skip " + lines + " lines from line " + (expectedLineCount - lines) + ". End of input reached");
  }
}
 
Example 3
Project: android-source-codes   File: DiskLruCache.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the ASCII characters up to but not including the next "\r\n", or
 * "\n".
 *
 * @throws java.io.EOFException if the stream is exhausted before the next newline
 *     character.
 */
public static String readAsciiLine(InputStream in) throws IOException {
    // TODO: support UTF-8 here instead

    StringBuilder result = new StringBuilder(80);
    while (true) {
        int c = in.read();
        if (c == -1) {
            throw new EOFException();
        } else if (c == '\n') {
            break;
        }

        result.append((char) c);
    }
    int length = result.length();
    if (length > 0 && result.charAt(length - 1) == '\r') {
        result.setLength(length - 1);
    }
    return result.toString();
}
 
Example 4
Project: openjdk-jdk10   File: BinaryParser.java   Source Code and License 6 votes vote down vote up
@Override
public GraphDocument parse() throws IOException {
    folderStack.push(rootDocument);
    hashStack.push(null);
    if (monitor != null) {
        monitor.setState("Starting parsing");
    }
    try {
        while(true) {
            parseRoot();
        }
    } catch (EOFException e) {

    }
    if (monitor != null) {
        monitor.setState("Finished parsing");
    }
    return rootDocument;
}
 
Example 5
Project: hadoop-oss   File: TestCryptoStreams.java   Source Code and License 6 votes vote down vote up
@Override
public void readFully(long position, byte[] b, int off, int len)
    throws IOException {
  if (b == null) {
    throw new NullPointerException();
  } else if (off < 0 || len < 0 || len > b.length - off) {
    throw new IndexOutOfBoundsException();
  } else if (len == 0) {
    return;
  }
  
  if (position > length) {
    throw new IOException("Cannot read after EOF.");
  }
  if (position < 0) {
    throw new IOException("Cannot read to negative offset.");
  }
  
  checkStream();
  
  if (position + len > length) {
    throw new EOFException("Reach the end of stream.");
  }
  
  System.arraycopy(data, (int)position, b, off, len);
}
 
Example 6
Project: incubator-netbeans   File: NIOStreams.java   Source Code and License 6 votes vote down vote up
@Override
public void write(byte[] b, int off, int len) throws IOException {
    ByteBuffer bb = ByteBuffer.wrap(b, off, len);
    
    while (bb.remaining() > 0) {
        channel.write(bb);
        if (bb.remaining() == 0) {
            return;
        }
        // wait for socket to become ready again
        int sel = selector.select(timeout);
        if (sel == 0) {
            throw new IOException("Timed out");
        } else if (!channel.isConnected()) {
            throw new EOFException("Closed");
        }
    }
}
 
Example 7
Project: s-store   File: ScriptReaderBinary.java   Source Code and License 6 votes vote down vote up
boolean readRow(RowInputInterface rowin, int pos) throws IOException {

        try {
            int length = dataStreamIn.readInt();
            int count  = 4;

            if (length == 0) {
                return false;
            }

            rowin.resetRow(pos, length);
            dataStreamIn.readFully(rowin.getBuffer(), count, length - count);

            return true;
        } catch (EOFException e) {
            return false;
        }
    }
 
Example 8
Project: JkImageLoader   File: DiskLruCache.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the ASCII characters up to but not including the next "\r\n", or
 * "\n".
 *
 * @throws EOFException if the stream is exhausted before the next newline
 *     character.
 */
public static String readAsciiLine(InputStream in) throws IOException {
    // TODO: support UTF-8 here instead

    StringBuilder result = new StringBuilder(80);
    while (true) {
        int c = in.read();
        if (c == -1) {
            throw new EOFException();
        } else if (c == '\n') {
            break;
        }

        result.append((char) c);
    }
    int length = result.length();
    if (length > 0 && result.charAt(length - 1) == '\r') {
        result.setLength(length - 1);
    }
    return result.toString();
}
 
Example 9
Project: Renrentou   File: DiskLruCache.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the ASCII characters up to but not including the next "\r\n", or
 * "\n".
 *
 * @throws EOFException if the stream is exhausted before the next newline
 *                      character.
 */
public static String readAsciiLine(InputStream in) throws IOException {
    // TODO: support UTF-8 here instead

    StringBuilder result = new StringBuilder(80);
    while (true) {
        int c = in.read();
        if (c == -1) {
            throw new EOFException();
        } else if (c == '\n') {
            break;
        }

        result.append((char) c);
    }
    int length = result.length();
    if (length > 0 && result.charAt(length - 1) == '\r') {
        result.setLength(length - 1);
    }
    return result.toString();
}
 
Example 10
Project: dremio-oss   File: TextInput.java   Source Code and License 6 votes vote down vote up
/**
 * Skip forward the number of line delimiters.  If you are in the middle of a line,
 * a value of 1 will skip to the start of the next record.
 * @param lines Number of lines to skip.
 * @throws IOException
 */
public final void skipLines(int lines) throws IOException {
  if (lines < 1) {
    return;
  }
  long expectedLineCount = this.lineCount + lines;

  try {
    do {
      nextChar();
    } while (lineCount < expectedLineCount /*&& bufferPtr < READ_CHARS_LIMIT*/);
    if (lineCount < lines) {
      throw new IllegalArgumentException("Unable to skip " + lines + " lines from line " + (expectedLineCount - lines) + ". End of input reached");
    }
  } catch (EOFException ex) {
    throw new IllegalArgumentException("Unable to skip " + lines + " lines from line " + (expectedLineCount - lines) + ". End of input reached");
  }
}
 
Example 11
Project: jaer   File: MotionViewer.java   Source Code and License 6 votes vote down vote up
public MotionData getNextData() {
            MotionData data = null;
            try {
                data = motionInputStream.readData(motionData);
                return data;
            } catch (EOFException e) {
                try {
                    Thread.currentThread();
					Thread.sleep(200);
                } catch (InterruptedException ignore) {
                }
                rewind();
            } catch (IOException io) {
//                io.printStackTrace();
                rewind();
                return chip.getEmptyMotionData();
            } catch (NullPointerException np) {
                np.printStackTrace();
                rewind();
            }
            return data;
        }
 
Example 12
Project: openjdk-jdk10   File: JarFile.java   Source Code and License 6 votes vote down vote up
private byte[] getBytes(ZipEntry ze) throws IOException {
    try (InputStream is = super.getInputStream(ze)) {
        int len = (int)ze.getSize();
        int bytesRead;
        byte[] b;
        // trust specified entry sizes when reasonably small
        if (len != -1 && len <= 65535) {
            b = new byte[len];
            bytesRead = is.readNBytes(b, 0, len);
        } else {
            b = is.readAllBytes();
            bytesRead = b.length;
        }
        if (len != -1 && len != bytesRead) {
            throw new EOFException("Expected:" + len + ", read:" + bytesRead);
        }
        return b;
    }
}
 
Example 13
Project: javaide   File: DecodedInstruction.java   Source Code and License 6 votes vote down vote up
/**
 * Decodes an array of instructions. The result has non-null
 * elements at each offset that represents the start of an
 * instruction.
 */
public static DecodedInstruction[] decodeAll(short[] encodedInstructions) {
    int size = encodedInstructions.length;
    DecodedInstruction[] decoded = new DecodedInstruction[size];
    ShortArrayCodeInput in = new ShortArrayCodeInput(encodedInstructions);

    try {
        while (in.hasMore()) {
            decoded[in.cursor()] = DecodedInstruction.decode(in);
        }
    } catch (EOFException ex) {
        throw new DexException(ex);
    }

    return decoded;
}
 
Example 14
Project: jsf-sdk   File: LinkedBufferInput.java   Source Code and License 6 votes vote down vote up
public int read(byte[] b, int off, int len) throws EOFException {
    if (link.isEmpty()) {
        return 0;
    }
    int olen = len;
    while (true) {
        ByteBuffer bb = link.getFirst();
        if (len < bb.remaining()) {
            bb.get(b, off, len);
            incrReadByteCount(len);
            return olen;
        }
        int rem = bb.remaining();
        bb.get(b, off, rem);
        incrReadByteCount(rem);
        len -= rem;
        off += rem;
        if (!removeFirstLink(bb)) {
            break;
        }
    }
    return olen - len;
}
 
Example 15
Project: simple-share-android   File: Streams.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the ASCII characters up to but not including the next "\r\n", or
 * "\n".
 *
 * @throws java.io.EOFException if the stream is exhausted before the next newline
 *     character.
 */
public static String readAsciiLine(InputStream in) throws IOException {
    // TODO: support UTF-8 here instead

    StringBuilder result = new StringBuilder(80);
    while (true) {
        int c = in.read();
        if (c == -1) {
            throw new EOFException();
        } else if (c == '\n') {
            break;
        }

        result.append((char) c);
    }
    int length = result.length();
    if (length > 0 && result.charAt(length - 1) == '\r') {
        result.setLength(length - 1);
    }
    return result.toString();
}
 
Example 16
Project: dremio-oss   File: ConvertFromJsonConverter.java   Source Code and License 6 votes vote down vote up
private static CompleteType getLiteralSchema(QueryContext context, byte[] bytes) {
  try(
      BufferAllocator allocator = context.getAllocator().newChildAllocator("convert-from-json-sampling", 0, 1024*1024);
      BufferManager bufferManager = new BufferManagerImpl(allocator);
      ArrowBuf data = allocator.buffer(bytes.length);
      VectorContainer container = new VectorContainer(allocator);
      VectorAccessibleComplexWriter vc = new VectorAccessibleComplexWriter(container)

      ){
    data.writeBytes(bytes);
    JsonReader jsonReader = new JsonReader(bufferManager.getManagedBuffer(), false, false, false);
    jsonReader.setSource(bytes);

      ComplexWriter writer = new ComplexWriterImpl("dummy", vc);
      writer.setPosition(0);
      ReadState state = jsonReader.write(writer);
      if(state == ReadState.END_OF_STREAM){
        throw new EOFException("Unexpected arrival at end of JSON literal stream");
      }

    container.buildSchema();
    return CompleteType.fromField(container.getSchema().getFields().get(0));
  }catch(Exception ex){
    throw UserException.validationError(ex).message("Failure while trying to parse JSON literal.").build(logger);
  }
}
 
Example 17
Project: hadoop-oss   File: Client.java   Source Code and License 6 votes vote down vote up
/** Check the rpc response header. */
void checkResponse(RpcResponseHeaderProto header) throws IOException {
  if (header == null) {
    throw new EOFException("Response is null.");
  }
  if (header.hasClientId()) {
    // check client IDs
    final byte[] id = header.getClientId().toByteArray();
    if (!Arrays.equals(id, RpcConstants.DUMMY_CLIENT_ID)) {
      if (!Arrays.equals(id, clientId)) {
        throw new IOException("Client IDs not matched: local ID="
            + StringUtils.byteToHexString(clientId) + ", ID in response="
            + StringUtils.byteToHexString(header.getClientId().toByteArray()));
      }
    }
  }
}
 
Example 18
Project: s-store   File: HsqlByteArrayInputStream.java   Source Code and License 6 votes vote down vote up
public final void readFully(byte[] b, int off,
                            int len) throws IOException {

    if (len < 0) {
        throw new IndexOutOfBoundsException();
    }

    int n = 0;

    while (n < len) {
        int count = read(b, off + n, len - n);

        if (count < 0) {
            throw new EOFException();
        }

        n += count;
    }
}
 
Example 19
Project: Hubs   File: IoLib.java   Source Code and License 6 votes vote down vote up
public static LuaValue freaduntil(File f,boolean lineonly) throws IOException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	int c;
	try {
		if ( lineonly ) {
			loop: while ( (c = f.read()) > 0 ) { 
				switch ( c ) {
				case '\r': break;
				case '\n': break loop;
				default: baos.write(c); break;
				}
			}
		} else {
			while ( (c = f.read()) > 0 ) 
				baos.write(c);
		}
	} catch ( EOFException e ) {
		c = -1;
	}
	return ( c < 0 && baos.size() == 0 )? 
		(LuaValue) NIL:
		(LuaValue) LuaString.valueUsing(baos.toByteArray());
}
 
Example 20
Project: OpenJSharp   File: ZipFile.java   Source Code and License 6 votes vote down vote up
int readLeUnsignedShort() throws IOException
{
  int result;
  if(pos + 1 < buffer.length)
    {
      result = ((buffer[pos + 0] & 0xff) | (buffer[pos + 1] & 0xff) << 8);
      pos += 2;
    }
  else
    {
      int b0 = read();
      int b1 = read();
      if (b1 == -1)
        throw new EOFException();
      result = (b0 & 0xff) | (b1 & 0xff) << 8;
    }
  return result;
}
 
Example 21
Project: parabuild-ci   File: HsqlByteArrayInputStream.java   Source Code and License 6 votes vote down vote up
public final void readFully(byte[] b, int off,
                            int len) throws IOException {

    if (len < 0) {
        throw new IndexOutOfBoundsException();
    }

    int n = 0;

    while (n < len) {
        int count = read(b, off + n, len - n);

        if (count < 0) {
            throw new EOFException();
        }

        n += count;
    }
}
 
Example 22
Project: geomapapp   File: ParseLink.java   Source Code and License 6 votes vote down vote up
static String parseComment(BufferedReader in) throws IOException {
	StringBuffer sb = new StringBuffer();
	boolean white = false;
	int count = 0;
	while( true ) {
		int i = in.read();
		if( i==-1 )throw new EOFException();
		char c = (char)i;
		if( Character.isWhitespace(c) ) {
			if( white )continue;
			white = true;
			sb.append(' ');
			continue;
		}
		if( c=='<' )count++;
		if( c=='>' ) {
			if( count==0) {
			//	System.out.println("comment:\t"+sb.toString());
				return sb.toString();
			}
			count--;
		}
		sb.append(c);
		white = false;
	}
}
 
Example 23
Project: tomcat7   File: UpgradeNioProcessor.java   Source Code and License 5 votes vote down vote up
private int fillReadBuffer(boolean block) throws IOException {
    int nRead;
    if (block) {
        Selector selector = null;
        try {
            selector = pool.get();
        } catch ( IOException x ) {
            // Ignore
        }
        try {
            NioEndpoint.KeyAttachment att =
                    (NioEndpoint.KeyAttachment) nioChannel.getAttachment();
            if (att == null) {
                throw new IOException("Key must be cancelled.");
            }
            nRead = pool.read(nioChannel.getBufHandler().getReadBuffer(),
                    nioChannel, selector, att.getTimeout());
        } catch (EOFException eof) {
            nRead = -1;
        } finally {
            if (selector != null) {
                pool.put(selector);
            }
        }
    } else {
        nRead = nioChannel.read(nioChannel.getBufHandler().getReadBuffer());
    }
    return nRead;
}
 
Example 24
Project: openjdk-jdk10   File: RIFFReader.java   Source Code and License 5 votes vote down vote up
public long readLong() throws IOException {
    long ch1 = read();
    long ch2 = read();
    long ch3 = read();
    long ch4 = read();
    long ch5 = read();
    long ch6 = read();
    long ch7 = read();
    long ch8 = read();
    if (ch1 < 0)
        throw new EOFException();
    if (ch2 < 0)
        throw new EOFException();
    if (ch3 < 0)
        throw new EOFException();
    if (ch4 < 0)
        throw new EOFException();
    if (ch5 < 0)
        throw new EOFException();
    if (ch6 < 0)
        throw new EOFException();
    if (ch7 < 0)
        throw new EOFException();
    if (ch8 < 0)
        throw new EOFException();
    return ch1 | (ch2 << 8) | (ch3 << 16) | (ch4 << 24)
            | (ch5 << 32) | (ch6 << 40) | (ch7 << 48) | (ch8 << 56);
}
 
Example 25
Project: PlusGram   File: ID3v2DataInput.java   Source Code and License 5 votes vote down vote up
public byte readByte() throws IOException {
	int b = input.read();
	if (b < 0) {
		throw new EOFException();
	}
	return (byte) b;
}
 
Example 26
Project: openjdk-jdk10   File: RIFFReader.java   Source Code and License 5 votes vote down vote up
public int readInt() throws IOException {
    int ch1 = read();
    int ch2 = read();
    int ch3 = read();
    int ch4 = read();
    if (ch1 < 0)
        throw new EOFException();
    if (ch2 < 0)
        throw new EOFException();
    if (ch3 < 0)
        throw new EOFException();
    if (ch4 < 0)
        throw new EOFException();
    return ch1 + (ch2 << 8) | (ch3 << 16) | (ch4 << 24);
}
 
Example 27
Project: ExoPlayer-Offline   File: FakeTrackOutput.java   Source Code and License 5 votes vote down vote up
@Override
public int sampleData(ExtractorInput input, int length, boolean allowEndOfInput)
    throws IOException, InterruptedException {
  byte[] newData = new byte[length];
  int bytesAppended = input.read(newData, 0, length);
  if (bytesAppended == C.RESULT_END_OF_INPUT) {
    if (allowEndOfInput) {
      return C.RESULT_END_OF_INPUT;
    }
    throw new EOFException();
  }
  newData = Arrays.copyOf(newData, bytesAppended);
  sampleData = TestUtil.joinByteArrays(sampleData, newData);
  return bytesAppended;
}
 
Example 28
Project: dev-courses   File: HsqlByteArrayInputStream.java   Source Code and License 5 votes vote down vote up
public final int readUnsignedShort() throws IOException {

        int ch1 = read();
        int ch2 = read();

        if ((ch1 | ch2) < 0) {
            throw new EOFException();
        }

        return (ch1 << 8) + (ch2);
    }
 
Example 29
Project: hadoop   File: TestNodeStatusUpdater.java   Source Code and License 5 votes vote down vote up
@Override
public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request)
    throws YarnException, IOException {
  heartBeatID++;
  if(heartBeatID == 1) {
    // EOFException should be retried as well.
    throw new EOFException("NodeHeartbeat exception");
  }
  else {
  throw new java.net.ConnectException(
      "NodeHeartbeat exception");
  }
}
 
Example 30
Project: ApkMultiChannelPlugin   File: IntReader.java   Source Code and License 5 votes vote down vote up
public final void skip(int bytes) throws IOException {
        if (bytes<=0) {
                return;
        }
        long skipped=m_stream.skip(bytes);
        m_position+=skipped;
        if (skipped!=bytes) {
                throw new EOFException();
        }
}
 
Example 31
Project: lams   File: ByteBufferIndexInput.java   Source Code and License 5 votes vote down vote up
@Override
public int readInt(long pos) throws IOException {
  try {
    return curBuf.getInt((int) pos);
  } catch (IllegalArgumentException e) {
    if (pos < 0) {
      throw new IllegalArgumentException("Seeking to negative position: " + this, e);
    } else {
      throw new EOFException("seek past EOF: " + this);
    }
  } catch (NullPointerException npe) {
    throw new AlreadyClosedException("Already closed: " + this);
  }
}
 
Example 32
Project: Reer   File: DaemonStopEvent.java   Source Code and License 5 votes vote down vote up
@Override
public DaemonStopEvent read(Decoder decoder) throws EOFException, Exception {
    long timestamp = decoder.readLong();
    long pid = decoder.readLong();
    DaemonExpirationStatus status = decoder.readBoolean() ? DaemonExpirationStatus.values()[decoder.readByte()] : null;
    String reason = decoder.readNullableString();
    return new DaemonStopEvent(new Date(timestamp), pid, status, reason);
}
 
Example 33
Project: s-store   File: ReaderDataInput.java   Source Code and License 5 votes vote down vote up
public final int readUnsignedShort() throws IOException {

        int b1 = read();
        int b2 = read();

        if ((b1 | b2) < 0) {
            throw new EOFException();
        }

        return ((b1 << 8) + (b2));
    }
 
Example 34
Project: parabuild-ci   File: ScaledRAFile.java   Source Code and License 5 votes vote down vote up
public void read(byte[] b, int offset, int length) throws IOException {

        try {
            if (bufferDirty || seekPosition < bufferOffset
                    || seekPosition >= bufferOffset + buffer.length) {
                readIntoBuffer();
            } else {
                cacheHit++;
            }

            ba.reset();

            if (seekPosition - bufferOffset
                    != ba.skip(seekPosition - bufferOffset)) {
                throw new EOFException();
            }

            int bytesRead = ba.read(b, offset, length);

            seekPosition += bytesRead;

            if (bytesRead < length) {
                if (seekPosition != realPosition) {
                    file.seek(seekPosition);
                }

                file.readFully(b, offset + bytesRead, length - bytesRead);

                seekPosition += (length - bytesRead);
                realPosition = seekPosition;
            }
        } catch (IOException e) {
            resetPointer();
            appLog.logContext(e, null);

            throw e;
        }
    }
 
Example 35
Project: openjdk-jdk10   File: ModuleInfo.java   Source Code and License 5 votes vote down vote up
@Override
public byte readByte() throws IOException {
    try {
        return bb.get();
    } catch (BufferUnderflowException e) {
        throw new EOFException(e.getMessage());
    }
}
 
Example 36
Project: NGB-master   File: BlockCompressedDataInputStream.java   Source Code and License 5 votes vote down vote up
/**
 * Reads an int value from stream
 * @return an int value
 * @throws IOException if no value was read
 */
public final int readInt() throws IOException {
    int ch1 = read();
    int ch2 = read();
    int ch3 = read();
    int ch4 = read();
    if ((ch1 | ch2 | ch3 | ch4) < 0) {
        throw new EOFException();
    }
    return (ch1 << SHIFT24) + (ch2 << TWO_BYTE_SIZE) + (ch3 << BYTE_SIZE) + ch4;
}
 
Example 37
Project: RedisDirectory   File: RedisInputStream.java   Source Code and License 5 votes vote down vote up
@Override
public void seek(long pos) throws IOException {
    int newBufferIndex = (int) (pos / Constants.BUFFER_SIZE);
    if (newBufferIndex != currentBufferIndex) {
        currentBufferIndex = newBufferIndex;
        setCurrentBuffer();
    }
    bufferPosition = (int) (pos % Constants.BUFFER_SIZE);
    if (getFilePointer() > length()) {
        throw new EOFException("seek beyond EOF: pos=" + getFilePointer() + " vs length=" + length() + ": " + this);
    }
}
 
Example 38
Project: Codeforces   File: DiskBasedCache.java   Source Code and License 5 votes vote down vote up
/**
 * Simple wrapper around {@link InputStream#read()} that throws EOFException
 * instead of returning -1.
 */
private static int read(InputStream is) throws IOException {
    int b = is.read();
    if (b == -1) {
        throw new EOFException();
    }
    return b;
}
 
Example 39
Project: monarch   File: DiskInitFileParser.java   Source Code and License 5 votes vote down vote up
private void readEndOfRecord(DataInput di) throws IOException {
  int b = di.readByte();
  if (b != DiskInitFile.END_OF_RECORD_ID) {
    if (b == 0) {
      // this is expected if this is the last record and we died while writing it.
      throw new EOFException("found partial last record");
    } else {
      // Our implementation currently relies on all unwritten bytes having
      // a value of 0. So throw this exception if we find one we didn't expect.
      throw new IllegalStateException("expected end of record (byte=="
          + DiskInitFile.END_OF_RECORD_ID + ") or zero but found " + b);
    }
  }
}
 
Example 40
Project: elasticsearch_my   File: ByteArrayIndexInput.java   Source Code and License 5 votes vote down vote up
@Override
public byte readByte() throws IOException {
    if (pos >= offset + length) {
        throw new EOFException("seek past EOF");
    }
    return bytes[offset + pos++];
}
 
Example 41
Project: SnapDup   File: MainDisplay.java   Source Code and License 5 votes vote down vote up
@FXML
private void btnOpenAction()
{
	FileChooser fileChooser = new FileChooser();
	File file = fileChooser.showOpenDialog(null);
	// String fileName = "\\\\LEAP-MEDIA\\data\\dup.out";
	// File file = new File(fileName);
	
	if(file == null)
		return;		
	
	try
	{		
		DupParserTask task = new DupParserTask(file);
		txtArea.textProperty().bind(task.valueProperty());

		Thread th = new Thread(task);
		th.setDaemon(true);
		th.start();
		
		btnDelete.setDisable(true);
		btnGenerateScript.setDisable(true);
		btnOverRun.setDisable(false);
		btnMapDevices.setDisable(false);
		totalSelected = 0;
	}
	catch (EOFException e)
	{
		e.printStackTrace();
	}
}
 
Example 42
Project: godlibrary   File: DiskLruCache.java   Source Code and License 5 votes vote down vote up
private void readJournal() throws IOException {
    InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE);
    try {
        String magic = readAsciiLine(in);
        String version = readAsciiLine(in);
        String appVersionString = readAsciiLine(in);
        String valueCountString = readAsciiLine(in);
        String blank = readAsciiLine(in);
        if (!MAGIC.equals(magic)
                || !VERSION_1.equals(version)
                || !Integer.toString(appVersion).equals(appVersionString)
                || !Integer.toString(valueCount).equals(valueCountString)
                || !"".equals(blank)) {
            throw new IOException("unexpected journal header: ["
                    + magic + ", " + version + ", " + valueCountString + ", " + blank + "]");
        }

        while (true) {
            try {
                readJournalLine(readAsciiLine(in));
            } catch (EOFException endOfJournal) {
                break;
            }
        }
    } finally {
        closeQuietly(in);
    }
}
 
Example 43
Project: lams   File: ByteBufferIndexInput.java   Source Code and License 5 votes vote down vote up
@Override
public void seek(long pos) throws IOException {
  try {
    curBuf.position((int) pos);
  } catch (IllegalArgumentException e) {
    if (pos < 0) {
      throw new IllegalArgumentException("Seeking to negative position: " + this, e);
    } else {
      throw new EOFException("seek past EOF: " + this);
    }
  } catch (NullPointerException npe) {
    throw new AlreadyClosedException("Already closed: " + this);
  }
}
 
Example 44
Project: apache-tomcat-7.0.73-with-comment   File: XMLEncodingDetector.java   Source Code and License 5 votes vote down vote up
/**
 * Loads a chunk of text.
 *
 * @param offset       The offset into the character buffer to
 *                     read the next batch of characters.
 * @param changeEntity True if the load should change entities
 *                     at the end of the entity, otherwise leave
 *                     the current entity in place and the entity
 *                     boundary will be signaled by the return
 *                     value.
 *
 * @return Returns true if the entity changed as a result of this
 *         load operation.
 */
final boolean load(int offset, boolean changeEntity)
    throws IOException {

    // read characters
    int length = fCurrentEntity.mayReadChunks?
        (fCurrentEntity.ch.length - offset):
        (DEFAULT_XMLDECL_BUFFER_SIZE);
    int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset,
                                           length);

    // reset count and position
    boolean entityChanged = false;
    if (count != -1) {
        if (count != 0) {
            fCurrentEntity.count = count + offset;
            fCurrentEntity.position = offset;
        }
    }

    // end of this entity
    else {
        fCurrentEntity.count = offset;
        fCurrentEntity.position = offset;
        entityChanged = true;
        if (changeEntity) {
            endEntity();
            if (fCurrentEntity == null) {
                throw new EOFException();
            }
            // handle the trailing edges
            if (fCurrentEntity.position == fCurrentEntity.count) {
                load(0, false);
            }
        }
    }

    return entityChanged;

}
 
Example 45
Project: GitHub   File: WebSocketReaderTest.java   Source Code and License 5 votes vote down vote up
@Test public void serverIncompleteControlFrameBodyThrows() throws IOException {
  data.write(ByteString.decodeHex("8a8537fa213d7f9f4d")); // Length = 5, "Hel"
  try {
    serverReader.processNextFrame();
    fail();
  } catch (EOFException ignored) {
  }
}
 
Example 46
Project: atlas   File: ShortArrayCodeInput.java   Source Code and License 5 votes vote down vote up
/** @inheritDoc */
public int readInt() throws EOFException {
    int short0 = read();
    int short1 = read();

    return short0 | (short1 << 16);
}
 
Example 47
Project: monarch   File: ByteArrayDataInput.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final int read() throws IOException {
  if (this.pos < this.nBytes) {
    return (this.bytes[this.pos++] & 0xff);
  } else {
    throw new EOFException();
  }
}
 
Example 48
Project: HtmlNative   File: Lexer.java   Source Code and License 5 votes vote down vote up
public void skipWhiteSpace() throws EOFException {
    for (; ; ) {
        char ch = peek();
        if (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\f' || ch == '\b') {
            next();
        } else {
            break;
        }
    }
}
 
Example 49
Project: HtmlNative   File: Parser.java   Source Code and License 5 votes vote down vote up
private void scanFor(@NonNull TokenType tokenType) throws EOFException, HNSyntaxError {
    scan();

    if (mCurToken.type() != tokenType) {
        mSyntaxErrorHandler.throwException("syntax error, should be " + tokenType.toString()
                + ", but " + "current is " + mCurToken.toString());
    }
}
 
Example 50
Project: hadoop   File: TestSeek.java   Source Code and License 5 votes vote down vote up
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testSeekAndPastEndOfFileThenReseekAndRead() throws Throwable {
  instream = fs.open(smallSeekFile);
  //go just before the end. This may or may not fail; it may be delayed until the
  //read
  try {
    instream.seek(SMALL_SEEK_FILE_LEN);
    //if this doesn't trigger, then read() is expected to fail
    assertMinusOne("read after seeking past EOF", instream.read());
  } catch (EOFException expected) {
    //here an exception was raised in seek
  }
  instream.seek(1);
  assertTrue("Premature EOF", instream.read() != -1);
}
 
Example 51
Project: OpenJSharp   File: StandardMidiFileReader.java   Source Code and License 5 votes vote down vote up
boolean nextTrack() throws IOException, InvalidMidiDataException {
    int magic;
    trackLength = 0;
    do {
        // $$fb 2003-08-20: fix for 4910986: MIDI file parser breaks up on http connection
        if (stream.skipBytes(trackLength) != trackLength) {
            if (!STRICT_PARSER) {
                return false;
            }
            throw new EOFException("invalid MIDI file");
        }
        magic = readIntFromStream();
        trackLength = readIntFromStream();
    } while (magic != MTrk_MAGIC);
    if (!STRICT_PARSER) {
        if (trackLength < 0) {
            return false;
        }
    }
    // now read track in a byte array
    try {
        trackData = new byte[trackLength];
    } catch (final OutOfMemoryError oom) {
        throw new IOException("Track length too big", oom);
    }
    try {
        // $$fb 2003-08-20: fix for 4910986: MIDI file parser breaks up on http connection
        stream.readFully(trackData);
    } catch (EOFException eof) {
        if (!STRICT_PARSER) {
            return false;
        }
        throw new EOFException("invalid MIDI file");
    }
    pos = 0;
    return true;
}
 
Example 52
Project: rskj   File: TrieImpl.java   Source Code and License 5 votes vote down vote up
/**
 * deserialize returns a NewTrieImpl, from its serialized bytes
 *
 * @return full trie deserialized from byte array
 */
public static Trie deserialize(byte[] bytes) {
    ByteArrayInputStream bstream = new ByteArrayInputStream(bytes);
    DataInputStream dstream = new DataInputStream(bstream);

    try {
        dstream.readShort();

        byte[] root = new byte[SHA3Helper.DEFAULT_SIZE_BYTES];

        if (dstream.read(root) != SHA3Helper.DEFAULT_SIZE_BYTES) {
            throw new EOFException();
        }

        TrieStoreImpl store = TrieStoreImpl.deserialize(bytes, Short.BYTES + SHA3Helper.DEFAULT_SIZE_BYTES, bytes.length - Short.BYTES - SHA3Helper.DEFAULT_SIZE_BYTES, new HashMapDB());

        Trie newTrie = store.retrieve(root);

        if (newTrie == null) {
            String strHash = Hex.toHexString(root);
            logger.error(ERROR_NON_EXISTENT_TRIE_LOGGER, strHash);
            panicProcessor.panic(PANIC_TOPIC, ERROR_CREATING_TRIE + " " + strHash);
            throw new TrieSerializationException(ERROR_CREATING_TRIE + " " + strHash, null);
        }

        return newTrie;
    }
    catch (IOException ex) {
        logger.error(ERROR_CREATING_TRIE, ex);
        panicProcessor.panic(PANIC_TOPIC, ERROR_CREATING_TRIE +": " + ex.getMessage());
        throw new TrieSerializationException(ERROR_CREATING_TRIE, ex);
    }
}
 
Example 53
Project: CustomWorldGen   File: GDiffPatcher.java   Source Code and License 5 votes vote down vote up
private void copy(long offset, int length, SeekableSource source, OutputStream output)
	throws IOException
{
       source.seek(offset);
       while (length > 0) {
           int len = Math.min(buf.capacity(), length);
           buf.clear().limit(len);
           int res = source.read(buf);
           if (res == -1)
               throw new EOFException("in copy " + offset + " " + length);
           output.write(buf.array(), 0, res);
           length -= res;
       }
   }
 
Example 54
Project: ditb   File: HRegionInfo.java   Source Code and License 5 votes vote down vote up
/**
 * @deprecated Use protobuf deserialization instead.
 * @see #parseFrom(byte[])
 */
@Deprecated
public void readFields(DataInput in) throws IOException {
  // Read the single version byte.  We don't ask the super class do it
  // because freaks out if its not the current classes' version.  This method
  // can deserialize version 0 and version 1 of HRI.
  byte version = in.readByte();
  if (version == 0) {
    // This is the old HRI that carried an HTD.  Migrate it.  The below
    // was copied from the old 0.90 HRI readFields.
    this.endKey = Bytes.readByteArray(in);
    this.offLine = in.readBoolean();
    this.regionId = in.readLong();
    this.regionName = Bytes.readByteArray(in);
    this.split = in.readBoolean();
    this.startKey = Bytes.readByteArray(in);
    try {
      HTableDescriptor htd = new HTableDescriptor();
      htd.readFields(in);
      this.tableName = htd.getTableName();
    } catch(EOFException eofe) {
       throw new IOException("HTD not found in input buffer", eofe);
    }
    this.hashCode = in.readInt();
  } else if (getVersion() == version) {
    this.endKey = Bytes.readByteArray(in);
    this.offLine = in.readBoolean();
    this.regionId = in.readLong();
    this.regionName = Bytes.readByteArray(in);
    this.split = in.readBoolean();
    this.startKey = Bytes.readByteArray(in);
    this.tableName = TableName.valueOf(Bytes.readByteArray(in));
    this.hashCode = in.readInt();
  } else {
    throw new IOException("Non-migratable/unknown version=" + getVersion());
  }
}
 
Example 55
Project: MpiTaskFramework   File: TaskSystem.java   Source Code and License 5 votes vote down vote up
/**
 * Return true if there are no message in the Q.
 * @param pTaskId
 * @return
 */
public boolean message_immediate(int pTaskId) {
	try {
		return !readers[pTaskId].next();
	} catch (EOFException e) {
		System.err.println("message_immediate error : " + e.getMessage());
		e.printStackTrace();
	}
	
	return false;
}
 
Example 56
Project: openjdk-jdk10   File: ModuleInfo.java   Source Code and License 5 votes vote down vote up
@Override
public int readUnsignedShort() throws IOException {
    try {
        return ((int) bb.getShort()) & 0xffff;
    } catch (BufferUnderflowException e) {
        throw new EOFException(e.getMessage());
    }
}
 
Example 57
Project: publicProject   File: DiskBasedCache.java   Source Code and License 5 votes vote down vote up
/**
 * Simple wrapper around {@link InputStream#read()} that throws EOFException
 * instead of returning -1.
 */
private static int read(InputStream is) throws IOException {
    int b = is.read();
    if (b == -1) {
        throw new EOFException();
    }
    return b;
}
 
Example 58
Project: readable-message-android   File: DefaultNetworkParser.java   Source Code and License 5 votes vote down vote up
private static String parse(Resources res, Throwable throwable) {
    String msg;
    Throwable cause;
    if (throwable.getCause() != null) {
        cause = throwable.getCause();
        msg = cause.getMessage() != null ? cause.getMessage() : throwable.getMessage();
    } else {
        cause = throwable;
        msg = throwable.getMessage();
    }

    if (msg != null) {
        msg = msg.toUpperCase(Locale.US);
        if (msg.contains("ECONNREFUSED")) { /*Connection refused*/
            return res.getString(R.string.msg_cnn_refuse);
        } else if (msg.contains("ENETUNREACH")
                || msg.contains("EHOSTUNREACH")
                || msg.contains("ECONNRESET")
                || msg.contains("EAI_NODATA")) { /*Network is unreachable*/
            return res.getString(R.string.msg_cnn_unreachable);
        } else if (msg.contains("ETIMEDOUT")
                || msg.contains("TIMEOUT")) {
            return res.getString(R.string.msg_cnn_timeout);
        } else if (msg.contains("CANCELED")
                || msg.contains("SOCKET CLOSED")) {
            return res.getString(R.string.msg_cnn_close);
        }
    }

    if (cause instanceof UnknownHostException
            || cause instanceof NoRouteToHostException) {
        return res.getString(R.string.msg_cnn_no_route);
    } else if (cause instanceof SocketTimeoutException) {
        return res.getString(R.string.msg_cnn_timeout);
    } else if ((cause instanceof EOFException) || (cause instanceof ConnectException)) {
        return res.getString(R.string.msg_cnn_close);
    } else {
        return String.format("未知错误(%s,%s)", throwable.getLocalizedMessage(), cause.getClass().getSimpleName());
    }
}
 
Example 59
Project: GitHub   File: LEInputStream.java   Source Code and License 5 votes vote down vote up
/**
 * 32-bit little endian integer
 */
public int read32() throws IOException {
    int b1 = read();
    int b2 = read();
    int b3 = read();
    int b4 = read();
    if ((b1 | b2 | b3 | b4) < 0)
        throw new EOFException();
    return ((b1 << 0) + (b2 << 8) + (b3 << 16) + (b4 << 24));
}
 
Example 60
Project: VASSAL-src   File: ADC2Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Read a block separator byte from an import module file and throw an exception if it
 * doesn't match.
 */
static void readBlockHeader(DataInputStream in, String string) throws IOException {
  try {
    int header = in.readByte();
    if (header != BLOCK_SEPARATOR)
      throw new FileFormatException("Invalid " + string + " block header.");
  }
  // FIXME: review error message
  catch (EOFException e) {
    throw new NoMoreBlocksException(string);
  }
  if (in.available() == 0)
    throw new NoMoreBlocksException(string);
}