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 File: PGCopyPreparedStatement.java    From phoebus with 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 File: CSVParser.java    From wandora with 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 #3
Source File: XmlReader.java    From knopflerfish.org with 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 #4
Source File: ReaderStreamTest.java    From hj-t212-parser with 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 #5
Source File: XmlReader.java    From knopflerfish.org with 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 #6
Source File: DataLevelMapDeserializer.java    From hj-t212-parser with 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 #7
Source File: IonBinary.java    From ion-java with 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 #8
Source File: DTDParser.java    From netbeans with 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 #9
Source File: CSVParser.java    From wandora with 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 File: XmlReader.java    From knopflerfish.org with 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 #11
Source File: StreamingTest.java    From dynamic-object with 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 #12
Source File: JsonParser.java    From everrest with 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 #13
Source File: TokenReplacingReader.java    From extract with 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 #14
Source File: XmlReader.java    From knopflerfish.org with 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 #15
Source File: CSVParser.java    From wandora with 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 #16
Source File: MyTreebankReader.java    From fnlp with 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 File: ReaderStream.java    From hj-t212-parser with 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 #18
Source File: ReaderStream.java    From hj-t212-parser with 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 #19
Source File: ReaderStream.java    From hj-t212-parser with 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 #20
Source File: XmlReader.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
boolean tagShouldBeIgnored(PushbackReader r)
    throws Exception
{
  char first = readNextChar(r);
  char second = readNextChar(r);
  r.unread(second);
  r.unread(first);
  return second == '!' || second == '?';
}
 
Example #21
Source File: OFXTransactionExtracter.java    From javamoney-examples with 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 #22
Source File: XmlReader.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void read(PushbackReader r)
    throws Exception
{
  while (readToNextTag(r)) {

    if (tagShouldBeIgnored(r)) {
      ignoreTag(r);
    } else if (isEndTag(r)) {
      return;
    } else {
      readElement(r);
    }
  }
}
 
Example #23
Source File: StreamingTest.java    From dynamic-object with 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 #24
Source File: XmlReader.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
String readElementType(PushbackReader r)
    throws Exception
{
  String elementType = readXMLName(r);
  char c = readAndPushbackNextChar(r);
  // Turn into a method
  if (c != '>' && c != '/' && isNotXMLWhitespace(c)) {
    throwMessage("Error while reading element type after: " + elementType);
  }
  return elementType;
}
 
Example #25
Source File: StreamingTest.java    From dynamic-object with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Test
public void heterogeneousStreamTest() {
    List expected = asList(42L, "string", Clojure.read("{:key :value}"), asList('a', 'b', 'c'));
    String edn = "42 \"string\" {:key :value} [\\a \\b \\c]";
    PushbackReader reader = new PushbackReader(new StringReader(edn));

    List actual = deserializeStream(reader, Object.class).collect(toList());

    assertEquals(expected, actual);
}
 
Example #26
Source File: XmlReader.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void readEndTag(String startTagElementType, PushbackReader r)
    throws Exception
{
  readStartOfEndTag(r);
  readAndMatchElementType(startTagElementType, r);
  readEndOfTag(r);
}
 
Example #27
Source File: OFXTransactionExtracter.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
private static String getTagName(PushbackReader stream) throws IOException {
	StringBuffer tag = new StringBuffer();
	int ch = 0;

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

		tag.append((char) ch);
	}

	return tag.toString().trim();
}
 
Example #28
Source File: CsvRecordInput.java    From big-c with 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);
  }
}
 
Example #29
Source File: XmlReader.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
boolean isEndTag(PushbackReader r)
    throws Exception
{
  char first = readNextChar(r);
  char second = readNextChar(r);
  r.unread(second);
  r.unread(first);
  return first == '<' && second == '/';
}
 
Example #30
Source File: TexParser.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses the document
 * 
 * @throws IOException
 */
public void parseDocument(String input, boolean checkForMissingSections) throws IOException {
    
    // remove trailing ws (this is because a discrepancy in the lexer's 
    // and IDocument's line counting for trailing whitespace)
    input = this.rmTrailingWhitespace(input);
    
    this.extractPreamble(input);
    
    try {
        // start the parse
        LatexLexer lexer = new LatexLexer(new PushbackReader(new StringReader(input), 4096));
        //LatexLexer lexer = this.getLexer(input); 
        if (this.preamble != null) {
            OutlineNode on = new OutlineNode("Preamble",
                    OutlineNode.TYPE_PREAMBLE,
                    1, null);
            lparser.parse(lexer, on, checkForMissingSections);
        } else {
            lparser.parse(lexer, checkForMissingSections);
        }
        this.errors = lparser.getErrors();
        this.fatalErrors = lparser.isFatalErrors();
    } catch (LexerException e) {
        // we must parse the lexer exception into a suitable format
        String msg = e.getMessage();
        int first = msg.indexOf('[');
        int last = msg.indexOf(']');
        String numseq = msg.substring(first + 1, last);
        String[] numbers = numseq.split(",");
        this.errors = new ArrayList<ParseErrorMessage>(1);
        this.errors.add(new ParseErrorMessage(Integer.parseInt(numbers[0]),
                Integer.parseInt(numbers[1]),
                2,
                msg.substring(last+2),
                IMarker.SEVERITY_ERROR));
        this.fatalErrors = true;
    }
}