java.io.PushbackReader Java Examples

The following examples show how to use java.io.PushbackReader. 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 Project: phoebus   Author: ControlSystemStudio   File: PGCopyPreparedStatement.java    License: Eclipse Public License 1.0 7 votes vote down vote up
@Override
public int[] executeBatch() throws SQLException {
    long res = 0;
    try {
        CopyManager cpManager = ((PGConnection) connection).getCopyAPI();
        PushbackReader reader = new PushbackReader(new StringReader(""),
                batchBuilder.length());
        reader.unread(batchBuilder.toString().toCharArray());
        res = cpManager.copyIn("COPY " + tableName +  " FROM STDIN WITH CSV", reader);
        batchBuilder.setLength(0);
        reader.close();
    } catch (IOException e) {
        throw new SQLException(e);
    }
    return new int[] { (int) res };
}
 
Example #2
Source Project: netbeans   Author: apache   File: DTDParser.java    License: Apache License 2.0 6 votes vote down vote up
/** Parser that eats everything until two consecutive dashes (inclusive) */
private void parseComment( PushbackReader in ) throws IOException, WrongDTDException {
    int state = COMM_TEXT;
    for( ;; ) {
        int i = in.read();
        if( i == -1 ) break; // EOF
        switch( state ) {
            case COMM_TEXT:
                if( i == '-' ) state = COMM_DASH;
                break;
            case COMM_DASH:
                if( i == '-' ) return; // finished eating comment
                state = COMM_TEXT;
                break;
        }
    }
    throw new WrongDTDException( "Premature end of DTD" ); // NOI18N
}
 
Example #3
Source Project: hj-t212-parser   Author: xiaoyao9184   File: ReaderStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch() throws IOException {
    String data = "C=c;B=&&B1=b1;A=&&A1=a1;A2=a2;A3=a3&&&&";
    PushbackReader reader = new PushbackReader(new StringReader(data));
    CharBuffer buffer = CharBuffer.allocate(10);
    int len = ReaderStream.of(reader)
            .next()
                .when(c -> c =='=')
                .then()
                    .next(2)
                        .when(c -> Arrays.equals(c,new char[]{'&','&'}))
                        .then(() -> {
                            System.out.print("is '=&&'");
                        })
                        .back()
                    .back()
                .then(() -> {
                    System.out.print("is '='");
                })
                .done()
            .read(buffer);

    assertEquals(len,1);
}
 
Example #4
Source Project: hj-t212-parser   Author: xiaoyao9184   File: DataLevelMapDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, String> deserialize(char[] data) throws IOException, T212FormatException {
    PushbackReader reader = new PushbackReader(new CharArrayReader(data));
    SegmentParser parser = new SegmentParser(reader);
    parser.configured(segmentParserConfigurator);

    Map<String,String> result = null;
    try {
        result = segmentDeserializer.deserialize(parser);
    } catch (SegmentFormatException e) {
        T212FormatException.segment_exception(e);
    }

    if(USE_VERIFICATION.enabledIn(verifyFeature)){
        verifyByType(result);
    }
    return result;
}
 
Example #5
Source Project: ion-java   Author: amzn   File: IonBinary.java    License: Apache License 2.0 6 votes vote down vote up
final boolean isLongTerminator(int terminator, PushbackReader r) throws IOException {
    int c;

    // look for terminator 2 - if it's not there put back what we saw
    c = r.read();
    if (c != terminator) {
        r.unread(c);
        return false;
    }

    // look for terminator 3 - otherwise put back what we saw and the
    // preceeding terminator we found above
    c = r.read();
    if (c != terminator) {
        r.unread(c);
        r.unread(terminator);
        return false;
    }
    // we found 3 in a row - now that's a long terminator
    return true;
}
 
Example #6
Source Project: everrest   Author: codenvy   File: JsonParser.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public void parse(Reader reader) throws JsonException {
    pushbackReader = new PushbackReader(reader);
    eventHandler.reset();
    stack.clear();
    char c;
    while ((c = next()) != END_OF_STREAM) {
        if (c == '{') {
            readObject();
        } else if (c == '[') {
            readArray();
        } else {
            throw new JsonException(String.format("Syntax error. Unexpected '%s'. Must be '{'.", c));
        }
        c = assertNextIs(",]}");
        if (c != END_OF_STREAM) {
            pushBack(c);
        }
    }
    if (!stack.isEmpty()) {
        throw new JsonException("Syntax error. Missing one or more close bracket(s).");
    }
}
 
Example #7
Source Project: knopflerfish.org   Author: knopflerfish   File: XmlReader.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
boolean readToNextTag(PushbackReader r)
    throws Exception
{
  boolean foundATag = true;
  try {
    char c = readAndPushbackNextNonWhitespaceChar(r);
    throwIfNotExpectedChar(c, '<', r);
  } catch (Exception e) {
    if (EOF.equals(e.getMessage())) {
      foundATag = false;
    } else {
      throw e;
    }
  }
  return foundATag;
}
 
Example #8
Source Project: wandora   Author: wandora-team   File: CSVParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Row readLine(PushbackReader in) throws IOException {
    Row ret=new Row();
    while(true){
        int c=in.read();
        if(c<0) {
            if(ret.size()>0) return ret;
            else return null;
        }
        else in.unread(c);

        Object v=readValue(in);
        ret.add(v);
        boolean next=readValueSeparator(in);
        if(!next) break;
    }

    return ret;
}
 
Example #9
Source Project: wandora   Author: wandora-team   File: CSVParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String parseString(PushbackReader in) throws IOException {
    readWhitespace(in);

    int c=in.read();
    if(c!=stringChar) throw new RuntimeException("Error parsing CSV file");
    StringBuilder sb=new StringBuilder();

    while(true){
        c=in.read();
        if(c<0) throw new RuntimeException("Error parsing CSV file");
        else if(c == stringChar) {
            int c2=in.read();
            if(c2==stringChar){
                sb.append((char)stringChar);
            }
            else {
                if(c2>=0) in.unread(c2);
                return sb.toString();
            }
        }
        else {
            sb.append((char)c);
        }
    }
}
 
Example #10
Source Project: knopflerfish.org   Author: knopflerfish   File: XmlReader.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String readXMLName(PushbackReader r)
    throws Exception
{
  char c = readNextNonWhitespaceChar(r);
  StringBuffer xmlName = new StringBuffer();
  if (isXMLNameStartChar(c)) {
    xmlName.append(c);
  } else {
    throwMessage("Error while reading XML name: " + c
                 + " is not a valid start char.");
  }
  c = readNextChar(r);
  while (isXMLNameChar(c)) {
    xmlName.append(c);
    c = readNextChar(r);
  }
  r.unread(c);
  return xmlName.toString();
}
 
Example #11
Source Project: knopflerfish.org   Author: knopflerfish   File: XmlReader.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String readAttributeValue(PushbackReader r)
    throws Exception
{
  char c = readNextChar(r);
  throwIfNotExpectedChar(c, '\"');
  StringBuffer value = new StringBuffer();
  c = readNextChar(r);
  while (isXMLAttributeValueChar(c)) {
    if (isXMLEscapeCharacter(c)) {
      c = readEscapedCharacter(r);
    }
    value.append(c);
    c = readNextChar(r);
  }
  throwIfNotExpectedChar(c, '\"');
  return value.toString();
}
 
Example #12
Source Project: knopflerfish.org   Author: knopflerfish   File: XmlReader.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void throwIfNotExpectedChar(char c,
                                      char expected,
                                      PushbackReader pbr)
    throws Exception
{
  if (c != expected) {
    StringBuffer msg = new StringBuffer();
    msg.append("Expected " + expected + " but found " + c + "\n");
    msg.append("At:");
    for (int i = 0; i < 20; ++i) {
      int rc = pbr.read();
      if (rc == -1) {
        break;
      }
      msg.append((char) rc);
    }
    throw new Exception(msg.toString()); // TODO
  }
}
 
Example #13
Source Project: dynamic-object   Author: rschmitt   File: StreamingTest.java    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
@Test
public void iteratorTest() {
    String edn = "{:x 1} {:x 2}";
    PushbackReader reader = new PushbackReader(new StringReader(edn));

    Iterator<StreamingType> iterator = deserializeStream(reader, StreamingType.class).iterator();

    assertTrue(iterator.hasNext());
    assertTrue(iterator.hasNext());
    assertEquals(1, iterator.next().x());
    assertTrue(iterator.hasNext());
    assertTrue(iterator.hasNext());
    assertEquals(2, iterator.next().x());
    assertFalse(iterator.hasNext());
    assertFalse(iterator.hasNext());
}
 
Example #14
Source Project: extract   Author: ICIJ   File: TokenReplacingReader.java    License: MIT License 6 votes vote down vote up
public TokenReplacingReader(final TokenResolver<Reader> resolver, final Reader source, final String start, final String end) {
	if (resolver == null) {
		throw new IllegalArgumentException("Token resolver is null");
	}

	if ((start == null || start.length() < 1) || (end == null || end.length() < 1)) {
		throw new IllegalArgumentException("Token start / end marker is null or empty");
	}

	this.start = start;
	this.end = end;
	this.startChars = start.toCharArray();
	this.endChars = end.toCharArray();
	this.startCharsBuffer = new char[start.length()];
	this.endCharsBuffer = new char[end.length()];
	this.pushback = new PushbackReader(source, Math.max(start.length(), end.length()));
	this.resolver = resolver;
}
 
Example #15
Source Project: hawkular-alerts   Author: hawkular   File: TokenReplacingReader.java    License: Apache License 2.0 5 votes vote down vote up
public TokenReplacingReader(String source, Map<String, String> tokens, Deque<String> activeTokens,
        Map<String, String> resolvedTokens) {
    pushbackReader = new PushbackReader(new StringReader(source));
    this.tokens = tokens;
    this.activeTokens = activeTokens;
    this.resolvedTokens = resolvedTokens;
}
 
Example #16
Source Project: fnlp   Author: FudanNLP   File: MyTreebankReader.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public TreeReaderIterator(File file, Charset charset)
				throws IOException {
			//add by xpqiu
			BufferedReader in = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), charset));
			StringBuilder sb = new StringBuilder();
			

			String line = null;
			while ((line = in.readLine()) != null) {
//				line = line.trim();	
				if(line.length()==0)
					continue;
				if(line.startsWith("<")&&line.endsWith(">"))
					continue;
				sb.append(line);
				sb.append("\n");
			}
			in.close();
			
			this.in = new PushbackReader(new StringReader(sb.toString()));
			//end add 
			
//			this.in = new PushbackReader(new InputStreamReader(
//					new FileInputStream(file), charset));
			nextTree = nextTree();
		}
 
Example #17
Source Project: rhizobia_J   Author: momosecurity   File: HashTrie.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Recursively lookup the longest key match.
 * @param keyIn Where to read the key from
 * @param pos The position in the key that is being
 *	looked up at this level.
 * @return The Entry assocatied with the longest key
 *	match or null if none exists.
 */
Entry<T> getLongestMatch(PushbackReader keyIn, StringBuilder key) throws IOException
{
	Node<T> nextNode;
	Entry<T> ret;
	int c;
	char ch;
	int prevLen;

	// read next key char and append to key...
	if((c = keyIn.read())<0)
		// end of input, return what we have currently
		return Entry.newInstanceIfNeeded(key,value);
	ch = (char)c;
	prevLen = key.length();
	key.append(ch);

	if((nextNode = getNextNode(ch))==null)
	{	// last in trie... return ourselves
		return Entry.newInstanceIfNeeded(key,value);
	}
	if((ret = nextNode.getLongestMatch(keyIn, key))!=null)
		return ret;

	// undo reading of key char and appending to key...
	key.setLength(prevLen);
	keyIn.unread(c);

	return Entry.newInstanceIfNeeded(key,value);
}
 
Example #18
Source Project: ModTheSpire   Author: kiooeht   File: XStringBufBase.java    License: MIT License 5 votes vote down vote up
/**
 * Decode a metacharacter sequence.
 *
 * @param c   the character after the backslash
 * @param pb  a PushbackReader representing the remainder of the region
 *            being processed (necessary for Unicode sequences)
 *
 * @return the decoded metacharacter, -1 on EOF, -2 for unknown or
 *         bad sequence
 *
 * @throws IOException read error
 */
private int decodeMetacharacter (int c, PushbackReader pb)
    throws IOException
{
    switch (c)
    {
        case 't':
            c = '\t';
            break;

        case 'n':
            c = '\n';
            break;

        case 'r':
            c = '\r';
            break;

        case METACHAR_SEQUENCE_START:
            c = METACHAR_SEQUENCE_START;
            break;

        case 'u':
            c = decodeUnicodeSequence (pb);
            if (c == -2)
            {
                pb.unread ('u');
                c = METACHAR_SEQUENCE_START;
            }
            break;

        default:
            // An escaped "regular" character is just the character.
            break;
    }

    return c;
}
 
Example #19
Source Project: mmseg4j-core   Author: chenlb   File: MMSeg.java    License: Apache License 2.0 5 votes vote down vote up
public void reset(Reader input) {
	this.reader = new PushbackReader(new BufferedReader(input), 20);
	currentSentence = null;
	bufWord = new LinkedList<Word>();
	bufSentence.setLength(0);
	readedIdx = -1;
}
 
Example #20
Source Project: netbeans   Author: apache   File: DTDParser.java    License: Apache License 2.0 5 votes vote down vote up
/** Parser that reads the markup type after <!. Recognizes ENTITY, ELEMENT
 * and ATTLIST markup and forwards their processing to proper parser.
 * It gets the control just after starting "<!" and releases after eating
 * final '>' */
private void parseMarkup( PushbackReader in ) throws IOException, WrongDTDException {
    StringBuffer sb = new StringBuffer();
    for( ;; ) {
        int i = in.read();
        if( i == -1 ) throw new WrongDTDException( "Premature end of DTD" ); // NOI18N EOF
        if( i == ' ' ) break;
        sb.append( (char)i );                 // next char of name
    }
    
    String markup = sb.toString();
    switch (markup) {
        case "ENTITY":
            // NOI18N
            parseEntityDefinition( in );
            break;
        case "ELEMENT":
            // NOI18N
            parseElement( in );
            break;
        case "ATTLIST":
            // NOI18N
            parseAttlist( in );
            break;
        default:
            throw new WrongDTDException( "Wrong DTD markup <!" + markup );
    }
}
 
Example #21
Source Project: wandora   Author: wandora-team   File: CSVParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Table parse(InputStream inRaw, String encoding) throws IOException {
    Table ret=new Table();

    PushbackReader in=new PushbackReader(new InputStreamReader(inRaw,encoding),20);

    Row row=null;
    while( (row=readLine(in))!=null ){
        ret.add(row);
    }

    return ret;
}
 
Example #22
Source Project: netbeans   Author: apache   File: Patch.java    License: Apache License 2.0 5 votes vote down vote up
/** Reads a line and returns the char sequence for newline */
private static String readLine(PushbackReader r, StringBuffer nl) throws IOException {
    StringBuffer line = new StringBuffer();
    int ic = r.read();
    if (ic == -1) return null;
    char c = (char) ic;
    while (c != '\n' && c != '\r') {
        line.append(c);
        ic = r.read();
        if (ic == -1) break;
        c = (char) ic;
    }
    if (nl != null) {
        nl.append(c);
    }
    if (c == '\r') {
        try {
            ic = r.read();
            if (ic != -1) {
                c = (char) ic;
                if (c != '\n') r.unread(c);
                else if (nl != null) nl.append(c);
            }
        } catch (IOException ioex) {}
    }
    return line.toString();
}
 
Example #23
Source Project: netbeans   Author: apache   File: Patch.java    License: Apache License 2.0 5 votes vote down vote up
private boolean compareText(PushbackReader source, String text) throws IOException {
    if (text == null || text.length() == 0) return true;
    text = adjustTextNL(text);
    char[] chars = new char[text.length()];
    int pos = 0;
    int n;
    String readStr = "";
    do {
        n = source.read(chars, 0, chars.length - pos);
        if (n > 0) {
            pos += n;
            readStr = readStr + new String(chars, 0, n);
        }
        if (readStr.endsWith("\r")) {
            try {
                char c = (char) source.read();
                if (c != '\n') source.unread(c);
                else readStr += c;
            } catch (IOException ioex) {}
        }
        readStr = adjustTextNL(readStr);
        pos = readStr.length();
    } while (n > 0 && pos < chars.length);
    readStr.getChars(0, readStr.length(), chars, 0);
    line += numChars('\n', chars);
    //System.out.println("Comparing text of the diff:\n'"+text+"'\nWith the read text:\n'"+readStr+"'\n");
    //System.out.println("  EQUALS = "+readStr.equals(text));
    return readStr.equals(text);
}
 
Example #24
Source Project: wandora   Author: wandora-team   File: CSVParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String parseIntPart(PushbackReader in) throws IOException {
    StringBuilder sb=new StringBuilder();
    while(true){
        int c=in.read();
        if(c>='0' && c<='9'){
            sb.append((char)c);
        }
        else {
            if(c>=0) in.unread(c);
            if(sb.length()==0) return null;
            else return sb.toString();
        }
    }
}
 
Example #25
Source Project: hj-t212-parser   Author: xiaoyao9184   File: ReaderStream.java    License: Apache License 2.0 5 votes vote down vote up
public ReaderStream<ParentMatch> use(Reader reader, int bufSize) {
    if(bufSize > 0){
        this.bufSize = bufSize;
    }
    this.reader = new PushbackReader(reader, this.bufSize);
    return this;
}
 
Example #26
Source Project: hj-t212-parser   Author: xiaoyao9184   File: ReaderStream.java    License: Apache License 2.0 5 votes vote down vote up
public ReaderStream<ParentMatch> use(PushbackReader reader, int bufSize, ParentMatch parentMatch) {
    if(bufSize < 1){
        this.reader = new PushbackReader(reader, this.bufSize);
        this.parentMatch = parentMatch;
        return this;
    }
    this.bufSize = bufSize;
    this.reader = reader;
    this.parentMatch = parentMatch;
    return this;
}
 
Example #27
Source Project: hj-t212-parser   Author: xiaoyao9184   File: ReaderStream.java    License: Apache License 2.0 5 votes vote down vote up
public ReaderStream<ParentMatch> use(Reader reader, int bufSize, ParentMatch parentMatch) {
    if(bufSize > 0){
        this.bufSize = bufSize;
    }
    this.reader = new PushbackReader(reader, this.bufSize);
    this.parentMatch = parentMatch;
    return this;
}
 
Example #28
Source Project: javamoney-examples   Author: JavaMoney   File: OFXTransactionExtracter.java    License: Apache License 2.0 5 votes vote down vote up
private static String getNextTag(PushbackReader stream) throws IOException {
	String tag = null;
	int ch = 0;

	while ((ch = stream.read()) != -1) {
		if (ch == START_TAG) {
			tag = getTagName(stream);
			break;
		}
	}

	return tag;
}
 
Example #29
Source Project: dynamic-object   Author: rschmitt   File: StreamingTest.java    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Test
public void streamTest() {
    String edn = "{:x 1}{:x 2}{:x 3}";
    PushbackReader reader = new PushbackReader(new StringReader(edn));

    Stream<StreamingType> stream = deserializeStream(reader, StreamingType.class);

    assertEquals(6, stream.mapToInt(StreamingType::x).sum());
}
 
Example #30
Source Project: big-c   Author: yncxcw   File: CsvRecordInput.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of CsvRecordInput */
public CsvRecordInput(InputStream in) {
  try {
    stream = new PushbackReader(new InputStreamReader(in, "UTF-8"));
  } catch (UnsupportedEncodingException ex) {
    throw new RuntimeException(ex);
  }
}