Java Code Examples for java.io.Reader#skip()

The following examples show how to use java.io.Reader#skip() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TemporaryClob.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Constructs and returns a <code>Reader</code>.
 * @param pos initial position of the returned <code>Reader</code> in
 *      number of characters. Expected to be non-negative. The first
 *      character is at position <code>0</code>.
 * @return A <code>Reader</code> with the underlying <code>CLOB</code>
 *      value as source.
 * @throws IOException
 * @throws SQLException if the specified position is too big
 */
public synchronized Reader getReader (long pos)
        throws IOException, SQLException {
    checkIfValid();
    if (pos < 1) {
        throw new IllegalArgumentException(
            "Position must be positive: " + pos);
    }
    // getCSD obtains a descriptor for the stream to allow the reader
    // to configure itself.
    Reader isr = new UTF8Reader(getCSD(), conChild,
            conChild.getConnectionSynchronization());

    long leftToSkip = pos -1;
    long skipped;
    while (leftToSkip > 0) {
        skipped = isr.skip(leftToSkip);
        // Since Reader.skip block until some characters are available,
        // a return value of 0 must mean EOF.
        if (skipped <= 0) {
            throw new EOFException("Reached end-of-stream prematurely");
        }
        leftToSkip -= skipped;
    }
    return isr;
}
 
Example 2
Source File: StoreStreamClob.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a reader for the Clob, initialized at the specified character
 * position.
 *
 * @param pos character position. The first character is at position 1.
 * @return A reader initialized at the specified position.
 * @throws EOFException if the positions is larger than the Clob
 * @throws IOException if accessing the I/O resources fail
 * @throws SQLException if accessing the store resources fail
 */
public Reader getReader(long pos)
        throws IOException, SQLException  {
    checkIfValid();
    try {
        this.positionedStoreStream.reposition(0L);
    } catch (StandardException se) {
        throw Util.generateCsSQLException(se);
    }
    Reader reader = new UTF8Reader(this.positionedStoreStream,
                            TypeId.CLOB_MAXWIDTH, this.conChild,
                            this.synchronizationObject);
    long leftToSkip = pos -1;
    long skipped;
    while (leftToSkip > 0) {
        skipped = reader.skip(leftToSkip);
        // Since Reader.skip block until some characters are available,
        // a return value of 0 must mean EOF.
        if (skipped <= 0) {
            throw new EOFException("Reached end-of-stream prematurely");
        }
        leftToSkip -= skipped;
    }
    return reader;
}
 
Example 3
Source File: UTF8ReaderTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Makes sure the data returned from the internal Clob matches the data
 * returned by a fresh looping alphabet stream.
 *
 * @param pos 1-based Clob position
 * @param clob internal store stream Clob representation
 */
private static void checkInternalStream(long pos, StoreStreamClob clob)
        throws IOException, SQLException {
    Reader canonStream = new LoopingAlphabetReader(pos + 100);
    long toSkip = pos -1; // Convert to 0-based index.
    while (toSkip > 0) {
        long skipped = canonStream.skip(toSkip);
        if (skipped > 0) {
            toSkip -= skipped;
        }
    }
    Reader clobStream = clob.getInternalReader(pos);
    assertEquals("Data mismatch", canonStream.read(), clobStream.read());
    clobStream.close();
}
 
Example 4
Source File: CharSource.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private long countBySkipping(Reader reader) throws IOException {
  long count = 0;
  long read;
  while ((read = reader.skip(Long.MAX_VALUE)) != 0) {
    count += read;
  }
  return count;
}
 
Example 5
Source File: CharStreams.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Discards {@code n} characters of data from the reader. This method will block until the full
 * amount has been skipped. Does not close the reader.
 *
 * @param reader the reader to read from
 * @param n the number of characters to skip
 * @throws EOFException if this stream reaches the end before skipping all the characters
 * @throws IOException if an I/O error occurs
 */
public static void skipFully(Reader reader, long n) throws IOException {
  checkNotNull(reader);
  while (n > 0) {
    long amt = reader.skip(n);
    if (amt == 0) {
      throw new EOFException();
    }
    n -= amt;
  }
}
 
Example 6
Source File: CharStreams.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Discards {@code n} characters of data from the reader. This method will block until the full
 * amount has been skipped. Does not close the reader.
 *
 * @param reader the reader to read from
 * @param n the number of characters to skip
 * @throws EOFException if this stream reaches the end before skipping all the characters
 * @throws IOException if an I/O error occurs
 */


public static void skipFully(Reader reader, long n) throws IOException {
  checkNotNull(reader);
  while (n > 0) {
    long amt = reader.skip(n);
    if (amt == 0) {
      throw new EOFException();
    }
    n -= amt;
  }
}
 
Example 7
Source File: CharSource.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private long countBySkipping(Reader reader) throws IOException {
  long count = 0;
  long read;
  while ((read = reader.skip(Long.MAX_VALUE)) != 0) {
    count += read;
  }
  return count;
}
 
Example 8
Source File: CharStreams.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Discards {@code n} characters of data from the reader. This method will block until the full
 * amount has been skipped. Does not close the reader.
 *
 * @param reader the reader to read from
 * @param n the number of characters to skip
 * @throws EOFException if this stream reaches the end before skipping all the characters
 * @throws IOException if an I/O error occurs
 */


public static void skipFully(Reader reader, long n) throws IOException {
  checkNotNull(reader);
  while (n > 0) {
    long amt = reader.skip(n);
    if (amt == 0) {
      throw new EOFException();
    }
    n -= amt;
  }
}
 
Example 9
Source File: OldAndroidLineNumberReaderTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static String skipRead(Reader a) throws IOException {
    int r;
    StringBuilder builder = new StringBuilder();
    do {
        a.skip(1);
        r = a.read();
        if (r != -1)
            builder.append((char) r);
    } while (r != -1);
    return builder.toString();
}
 
Example 10
Source File: CharStreams.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Discards {@code n} characters of data from the reader. This method will block until the full
 * amount has been skipped. Does not close the reader.
 *
 * @param reader the reader to read from
 * @param n the number of characters to skip
 * @throws EOFException if this stream reaches the end before skipping all the characters
 * @throws IOException if an I/O error occurs
 */


public static void skipFully(Reader reader, long n) throws IOException {
  checkNotNull(reader);
  while (n > 0) {
    long amt = reader.skip(n);
    if (amt == 0) {
      throw new EOFException();
    }
    n -= amt;
  }
}
 
Example 11
Source File: OldAndroidCharArrayReaderTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static String skipRead(Reader a) throws IOException {
    int r;
    StringBuilder builder = new StringBuilder();
    do {
        a.skip(1);
        r = a.read();
        if (r != -1)
            builder.append((char) r);
    } while (r != -1);
    return builder.toString();
}
 
Example 12
Source File: OldAndroidBufferedReaderTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static String skipRead(Reader a) throws IOException {
    int r;
    StringBuilder builder = new StringBuilder();
    do {
        a.skip(1);
        r = a.read();
        if (r != -1)
            builder.append((char) r);
    } while (r != -1);
    return builder.toString();
}
 
Example 13
Source File: TestCheckReturnValue.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@AssertNoWarning("ReturnValueOfSkip")
public void skipTenOk(Reader r) throws IOException {
    long skip = 10;
    while(skip > 0) {
        skip -= r.skip(skip);
    }
}
 
Example 14
Source File: DataHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extracts a portion of the contents of the given reader/stream as a string.
 *
 * @param characterStream The reader for the content
 * @param start The start position/offset (0-based, per general stream/reader contracts).
 * @param length The amount to extract
 *
 * @return The content as string
 */
private static String extractString(Reader characterStream, long start, int length) {
	if ( length == 0 ) {
		return "";
	}
	StringBuilder stringBuilder = new StringBuilder( length );
	try {
		long skipped = characterStream.skip( start );
		if ( skipped != start ) {
			throw new HibernateException( "Unable to skip needed bytes" );
		}
		final int bufferSize = getSuggestedBufferSize( length );
		char[] buffer = new char[bufferSize];
		int charsRead = 0;
		while ( true ) {
			int amountRead = characterStream.read( buffer, 0, bufferSize );
			if ( amountRead == -1 ) {
				break;
			}
			stringBuilder.append( buffer, 0, amountRead );
			if ( amountRead < bufferSize ) {
				// we have read up to the end of stream
				break;
			}
			charsRead += amountRead;
			if ( charsRead >= length ) {
				break;
			}
		}
	}
	catch ( IOException ioe ) {
		throw new HibernateException( "IOException occurred reading a binary value", ioe );
	}
	return stringBuilder.toString();
}
 
Example 15
Source File: BlobClob4BlobTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies the value returned by the method Clob.getSubstring()
 */
private void verifyInterval(Clob clob, long pos, int length,
        int testNum, int clobLength) throws Exception {
    try {
        String subStr = clob.getSubString(pos, length);
        assertEquals("FAIL - getSubString returned wrong length",
                Math.min((clob.length() - pos) + 1, length),
                subStr.length());
        assertEquals("FAIL - clob has mismatched lengths",
                clobLength, clob.length());
        assertFalse("FAIL - NO ERROR ON getSubString POS TOO LARGE",
                (pos > clobLength + 1));

        // Get expected value usign Clob.getAsciiStream()
        char[] value = new char[length];
        String valueString;
        Reader reader = clob.getCharacterStream();
        long left = pos - 1;
        long skipped = 0;
        if (clobLength > 0) {
            println("clobLength: " + clobLength);
            while (left > 0 && skipped >= 0) {
                skipped = reader.skip(Math.min(1024, left));
                left -= skipped > 0 ? skipped : 0;
            }
        }
        int numBytes = reader.read(value);

        // chech the the two values match
        if (numBytes >= 0) {
            char[] readBytes = new char[numBytes];
            System.arraycopy(value, 0, readBytes, 0, numBytes);
            valueString = new String(readBytes);
            assertEquals("FAIL - wrong substring value",
                    valueString, subStr);
        } else {
            assertTrue("FAIL - wrong length", subStr.length() == 0);
        }
    } catch (SQLException e) {
        if (pos <= 0) {
            checkException(BLOB_BAD_POSITION, e);
        } else {
            if (pos > clobLength + 1) {
                checkException(BLOB_POSITION_TOO_LARGE, e);
            } else {
                throw e;
            }
        }
    } catch (StringIndexOutOfBoundsException obe) {
        // Known bug.  JCC 5914.
        if (!((pos > clobLength) && usingDB2Client())) {
            throw obe;
        }
    }
}
 
Example 16
Source File: ClobUpdatableReaderTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Tests updates on reader.
 */
public void testUpdateableReader () throws Exception {
    getConnection().setAutoCommit (false);
    PreparedStatement ps = prepareStatement ("insert into updateClob " +
            "(id , data) values (? ,?)");
    ps.setInt (1, 1);
    StringBuilder sb = new StringBuilder ();
    String base = "SampleSampleSample";
    for (int i = 0; i < 100; i++) {
        sb.append (base);
    }
    ps.setCharacterStream (2, new StringReader (sb.toString()),
                                        sb.length());
    ps.execute();
    ps.close();
    Statement stmt = createStatement ();
    ResultSet rs = stmt.executeQuery("select data from " +
            "updateClob where id = 1");
    rs.next();
    Clob clob = rs.getClob (1);
    rs.close();
    stmt.close();
    assertEquals (sb.length(), clob.length());
    Reader r = clob.getCharacterStream();
    char [] clobData = new char [sb.length()];
    r.read (clobData);
    assertEquals ("mismatch from inserted string",
                        String.valueOf (clobData), sb.toString());
    r.close();
    //update before gettting the reader
    clob.setString (50, dummy);
    r = clob.getCharacterStream();
    r.skip (49);
    char [] newChars = new char [dummy.length()];
    r.read (newChars);
    assertEquals ("update not reflected", dummy,
                                String.valueOf (newChars));
    //update again and see if stream is refreshed
    clob.setString (75, dummy);
    r.skip (75 - 50 - dummy.length());
    char [] testChars = new char [dummy.length()];
    r.read (testChars);
    assertEquals ("update not reflected", dummy,
                                String.valueOf (newChars));
    r.close();
    //try inserting some unicode string
    String unicodeStr = getUnicodeString();
    clob.setString (50, unicodeStr);
    char [] utf16Chars = new char [unicodeStr.length()];
    r = clob.getCharacterStream();
    r.skip(49);
    r.read(utf16Chars);
    assertEquals ("update not reflected",  unicodeStr,
                                String.valueOf (utf16Chars));
    r.close();
    Writer w = clob.setCharacterStream (1);
    //write enough data to switch the data to file
    r = clob.getCharacterStream ();
    for (int i = 0; i < 10000; i++) {
        w.write (dummy);
    }
    w.close();
    clob.setString (500, unicodeStr);
    r.skip (499);
    char [] unicodeChars = new char [unicodeStr.length()];
    r.read (unicodeChars);
    assertEquals ("update not reflected",  unicodeStr,
                                String.valueOf (unicodeChars));
}
 
Example 17
Source File: IOGroovyMethods.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static String readLineFromReaderWithMark(final Reader input)
        throws IOException {
    char[] cbuf = new char[charBufferSize];
    try {
        input.mark(charBufferSize);
    } catch (IOException e) {
        // this should never happen
        LOG.warning("Caught exception setting mark on supporting reader: " + e);
        // fallback
        return readLineFromReaderWithoutMark(input);
    }

    // could be changed into do..while, but then
    // we might create an additional StringBuilder
    // instance at the end of the stream
    int count = input.read(cbuf);
    if (count == EOF) // we are at the end of the input data
        return null;

    StringBuilder line = new StringBuilder(expectedLineLength);
    // now work on the buffer(s)
    int ls = lineSeparatorIndex(cbuf, count);
    while (ls == -1) {
        line.append(cbuf, 0, count);
        count = input.read(cbuf);
        if (count == EOF) {
            // we are at the end of the input data
            return line.toString();
        }
        ls = lineSeparatorIndex(cbuf, count);
    }
    line.append(cbuf, 0, ls);

    // correct ls if we have \r\n
    int skipLS = 1;
    if (ls + 1 < count) {
        // we are not at the end of the buffer
        if (cbuf[ls] == '\r' && cbuf[ls + 1] == '\n') {
            skipLS++;
        }
    } else {
        if (cbuf[ls] == '\r' && input.read() == '\n') {
            skipLS++;
        }
    }

    //reset() and skip over last linesep
    input.reset();
    input.skip(line.length() + skipLS);
    return line.toString();
}
 
Example 18
Source File: ClobUpdatableReaderTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Tests updates on reader.
 */
public void testUpdateableReader () throws Exception {
    getConnection().setAutoCommit (false);
    PreparedStatement ps = prepareStatement ("insert into updateClob " +
            "(id , data) values (? ,?)");
    ps.setInt (1, 1);
    StringBuffer sb = new StringBuffer ();
    String base = "SampleSampleSample";
    for (int i = 0; i < 100; i++) {
        sb.append (base);
    }
    ps.setCharacterStream (2, new StringReader (sb.toString()),
                                        sb.length());
    ps.execute();
    ps.close();
    Statement stmt = createStatement ();
    ResultSet rs = stmt.executeQuery("select data from " +
            "updateClob where id = 1");
    rs.next();
    Clob clob = rs.getClob (1);
    rs.close();
    stmt.close();
    assertEquals (sb.length(), clob.length());
    Reader r = clob.getCharacterStream();
    char [] clobData = new char [sb.length()];
    r.read (clobData);
    assertEquals ("mismatch from inserted string",
                        String.valueOf (clobData), sb.toString());
    r.close();
    //update before gettting the reader
    clob.setString (50, dummy);
    r = clob.getCharacterStream();
    r.skip (49);
    char [] newChars = new char [dummy.length()];
    r.read (newChars);
    assertEquals ("update not reflected", dummy,
                                String.valueOf (newChars));
    //update again and see if stream is refreshed
    clob.setString (75, dummy);
    r.skip (75 - 50 - dummy.length());
    char [] testChars = new char [dummy.length()];
    r.read (testChars);
    assertEquals ("update not reflected", dummy,
                                String.valueOf (newChars));
    r.close();
    //try inserting some unicode string
    String unicodeStr = getUnicodeString();
    clob.setString (50, unicodeStr);
    char [] utf16Chars = new char [unicodeStr.length()];
    r = clob.getCharacterStream();
    r.skip(49);
    r.read(utf16Chars);
    assertEquals ("update not reflected",  unicodeStr,
                                String.valueOf (utf16Chars));
    r.close();
    Writer w = clob.setCharacterStream (1);
    //write enough data to switch the data to file
    r = clob.getCharacterStream ();
    for (int i = 0; i < 10000; i++) {
        w.write (dummy);
    }
    w.close();
    clob.setString (500, unicodeStr);
    r.skip (499);
    char [] unicodeChars = new char [unicodeStr.length()];
    r.read (unicodeChars);
    assertEquals ("update not reflected",  unicodeStr,
                                String.valueOf (unicodeChars));
}
 
Example 19
Source File: XmlBeansMarshaller.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public long skip(long n) throws IOException {
	Reader rdr = getReader();
	return (rdr != null ? rdr.skip(n) : 0);
}
 
Example 20
Source File: ClobUpdatableReaderTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Test updating a large clob
 */
public void testUpdateableStoreReader () throws Exception {
    getConnection().setAutoCommit (false);
    PreparedStatement ps = prepareStatement ("insert into updateClob " +
            "(id , data) values (? ,?)");
    ps.setInt (1, 2);
    StringBuffer sb = new StringBuffer ();
    String base = "SampleSampleSample";
    for (int i = 0; i < 100000; i++) {
        sb.append (base);
    }
    //insert a large enough data to ensure stream is created in dvd
    ps.setCharacterStream (2, new StringReader (sb.toString()),
                                        sb.length());
    ps.execute();
    ps.close();
    Statement stmt = createStatement ();
    ResultSet rs = stmt.executeQuery("select data from " +
            "updateClob where id = 2");
    rs.next();
    Clob clob = rs.getClob (1);
    rs.close();
    stmt.close();
    assertEquals (sb.length(), clob.length());
    Reader r = clob.getCharacterStream();
    String newString = "this is a new string";
    //access reader before modifying the clob
    long l = r.skip (100);
    clob.setString (1001, newString);
    //l chars are already skipped
    long toSkip = 1000 - l;
    while (toSkip > 0) {
        long skipped = r.skip (toSkip);
        toSkip -= skipped;
    }
    char [] newdata = new char [newString.length()];
    int len = r.read(newdata);
    assertEquals ("updated not reflected", newString,
                            new String (newdata, 0, len));
    r.close();
}