Java Code Examples for java.io.Reader

The following are top voted examples for showing how to use java.io.Reader. 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: AndroidApktool   File: Yaml.java   Source Code and License 7 votes vote down vote up
/**
 * Parse all YAML documents in a stream and produce corresponding
 * representation trees.
 * 
 * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a>
 * @param yaml
 *            stream of YAML documents
 * @return parsed root Nodes for all the specified YAML documents
 */
public Iterable<Node> composeAll(Reader yaml) {
    final Composer composer = new Composer(new ParserImpl(new StreamReader(yaml)), resolver);
    constructor.setComposer(composer);
    Iterator<Node> result = new Iterator<Node>() {
        public boolean hasNext() {
            return composer.checkNode();
        }

        public Node next() {
            return composer.getNode();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
    return new NodeIterable(result);
}
 
Example 2
Project: the-vigilantes   File: JDBC4ServerPreparedStatement.java   Source Code and License 6 votes vote down vote up
/**
 * @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader, long)
 */
public void setNCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
    // can't take if characterEncoding isn't utf8
    if (!this.charEncoding.equalsIgnoreCase("UTF-8") && !this.charEncoding.equalsIgnoreCase("utf8")) {
        throw SQLError.createSQLException("Can not call setNCharacterStream() when connection character set isn't UTF-8", getExceptionInterceptor());
    }

    checkClosed();

    if (reader == null) {
        setNull(parameterIndex, java.sql.Types.BINARY);
    } else {
        BindValue binding = getBinding(parameterIndex, true);
        resetToType(binding, MysqlDefs.FIELD_TYPE_BLOB);

        binding.value = reader;
        binding.isLongData = true;

        if (this.connection.getUseStreamLengthsInPrepStmts()) {
            binding.bindLength = length;
        } else {
            binding.bindLength = -1;
        }
    }
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: SSLOptionTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBuildIOException() {
  new MockUp<Properties>() {
    @Mock
    public synchronized void load(Reader reader) throws IOException {
      throw new IOException();
    }
  };
  boolean validAssert = true;
  try {
    SSLOption option = SSLOption.build(DIR + "/server.ssl.properties");
    Assert.assertEquals("revoke.crl", option.getCrl());
  } catch (Exception e) {
    Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName());
    validAssert = false;
  }
  Assert.assertFalse(validAssert);
}
 
Example 4
Project: TextEmoji   File: HttpRequest.java   Source Code and License 6 votes vote down vote up
/**
 * Copy from reader to writer
 *
 * @param input
 * @param output
 * @return this request
 * @throws IOException
 */
protected HttpRequest copy(final Reader input, final Writer output)
    throws IOException {
  return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) {

    @Override
    public HttpRequest run() throws IOException {
      final char[] buffer = new char[bufferSize];
      int read;
      while ((read = input.read(buffer)) != -1) {
        output.write(buffer, 0, read);
        totalWritten += read;
        progress.onUpload(totalWritten, -1);
      }
      return HttpRequest.this;
    }
  }.call();
}
 
Example 5
Project: mun3code   File: CsvReader.java   Source Code and License 6 votes vote down vote up
/**
 * Reads from the provided reader until the end and returns a CsvContainer containing the data.
 *
 * This library uses built-in buffering, so you do not need to pass in a buffered Reader
 * implementation such as {@link java.io.BufferedReader}.
 * Performance may be even likely better if you do not.
 *
 * @param reader the data source to read from.
 * @return the entire file's data - never {@code null}.
 * @throws IOException if an I/O error occurs.
 */
public CsvContainer read(final Reader reader) throws IOException {
    final CsvParser csvParser =
        parse(Objects.requireNonNull(reader, "reader must not be null"));

    final List<CsvRow> rows = new ArrayList<>();
    CsvRow csvRow;
    while ((csvRow = csvParser.nextRow()) != null) {
        rows.add(csvRow);
    }

    if (rows.isEmpty()) {
        return null;
    }

    final List<String> header = containsHeader ? csvParser.getHeader() : null;
    return new CsvContainer(header, rows);
}
 
Example 6
Project: GitHub   File: JSONReaderScannerTest_int.java   Source Code and License 6 votes vote down vote up
public void test_scanInt() throws Exception {
    StringBuffer buf = new StringBuffer();
    buf.append('[');
    for (int i = 0; i < 1024; ++i) {
        if (i != 0) {
            buf.append(',');
        }
        buf.append(i);
    }
    buf.append(']');

    Reader reader = new StringReader(buf.toString());

    JSONReaderScanner scanner = new JSONReaderScanner(reader);

    DefaultJSONParser parser = new DefaultJSONParser(scanner);
    JSONArray array = (JSONArray) parser.parse();
    for (int i = 0; i < array.size(); ++i) {
        Assert.assertEquals(i, ((Integer) array.get(i)).intValue()); 
    }
}
 
Example 7
Project: lams   File: SingleLineSqlCommandExtractor.java   Source Code and License 6 votes vote down vote up
@Override
public String[] extractCommands(Reader reader) {
	BufferedReader bufferedReader = new BufferedReader( reader );
	List<String> statementList = new LinkedList<String>();
	try {
		for ( String sql = bufferedReader.readLine(); sql != null; sql = bufferedReader.readLine() ) {
			String trimmedSql = sql.trim();
			if ( StringHelper.isEmpty( trimmedSql ) || isComment( trimmedSql ) ) {
				continue;
			}
			if ( trimmedSql.endsWith( ";" ) ) {
				trimmedSql = trimmedSql.substring( 0, trimmedSql.length() - 1 );
			}
			statementList.add( trimmedSql );
		}
		return statementList.toArray( new String[statementList.size()] );
	}
	catch ( IOException e ) {
		throw new ImportScriptException( "Error during import script parsing.", e );
	}
}
 
Example 8
Project: Guardian.java   File: RequestTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldNotFailIfDeleteHasBody() throws Exception {
    getRequest("DELETE", getUrl("/user/123"))
            .setParameter("some", "parameter")
            .execute();

    verify(converter).serialize(mapCaptor.capture());
    verify(converter).parse(any(Class.class), any(Reader.class));
    verifyNoMoreInteractions(converter);
    Map<String, Object> body = mapCaptor.getValue();
    assertThat(body, hasEntry("some", (Object) "parameter"));

    verify(client).newCall(requestCaptor.capture());
    okhttp3.Request request = requestCaptor.getValue();

    assertThat(request.method(), is(equalTo("DELETE")));
    assertThat(request.url().encodedPath(), is(equalTo("/user/123")));
}
 
Example 9
Project: myfaces-trinidad   File: FileUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a Reader for reading the UTF-8 encoded file at the specified
 * path.
 */
static public Reader getUTF8Reader(String path)
  throws FileNotFoundException
{
  FileInputStream in = new FileInputStream(path);
  InputStreamReader reader = null;

  try
  {
    reader = new InputStreamReader(in, _UTF8_ENCODING);
  }
  catch (UnsupportedEncodingException e)
  {
    // UTF-8 should always be supported!
    assert false;
    return null;
  }

  return new BufferedReader(reader);
}
 
Example 10
Project: elasticsearch_my   File: CustomAnalyzer.java   Source Code and License 5 votes vote down vote up
@Override
protected Reader initReader(String fieldName, Reader reader) {
    if (charFilters != null && charFilters.length > 0) {
        for (CharFilterFactory charFilter : charFilters) {
            reader = charFilter.create(reader);
        }
    }
    return reader;
}
 
Example 11
Project: Auto.js   File: JavaScriptSource.java   Source Code and License 5 votes vote down vote up
@NonNull
public Reader getNonNullScriptReader() {
    Reader reader = getScriptReader();
    if (reader == null) {
        return new StringReader(getScript());
    }
    return reader;
}
 
Example 12
Project: sstore-soft   File: JDBC4ResultSet.java   Source Code and License 5 votes vote down vote up
@Override
public Reader getCharacterStream(int columnIndex) throws SQLException {
    checkColumnBounds(columnIndex);
    try {
        String value = table.getString(columnIndex - 1);
        if (!wasNull())
            return new StringReader(value);
        return null;
    } catch (Exception x) {
        throw SQLError.get(x);
    }
}
 
Example 13
Project: careconnect-reference-implementation   File: ImmunizationResourceProvider.java   Source Code and License 5 votes vote down vote up
@Read
public Immunization getImmunizationById(HttpServletRequest httpRequest, @IdParam IdType internalId) {

    ProducerTemplate template = context.createProducerTemplate();



    Immunization immunization = null;
    IBaseResource resource = null;
    try {
        InputStream inputStream = (InputStream)  template.sendBody("direct:FHIRImmunization",
                ExchangePattern.InOut,httpRequest);


        Reader reader = new InputStreamReader(inputStream);
        resource = ctx.newJsonParser().parseResource(reader);
    } catch(Exception ex) {
        log.error("JSON Parse failed " + ex.getMessage());
        throw new InternalErrorException(ex.getMessage());
    }
    if (resource instanceof Immunization) {
        immunization = (Immunization) resource;
    }else if (resource instanceof OperationOutcome)
    {

        OperationOutcome operationOutcome = (OperationOutcome) resource;
        log.info("Sever Returned: "+ctx.newJsonParser().encodeResourceToString(operationOutcome));

        OperationOutcomeFactory.convertToException(operationOutcome);
    } else {
        throw new InternalErrorException("Unknown Error");
    }

    return immunization;
}
 
Example 14
Project: LoRaWAN-Smart-Parking   File: Util.java   Source Code and License 5 votes vote down vote up
/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
  try {
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
      writer.write(buffer, 0, count);
    }
    return writer.toString();
  } finally {
    reader.close();
  }
}
 
Example 15
Project: incubator-netbeans   File: HTMLDocView.java   Source Code and License 5 votes vote down vote up
/** Sets the javadoc content as HTML document */
public void setContent(final String content, final String reference) {
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            Reader in = new StringReader("<HTML><BODY>"+content+"</BODY></HTML>");//NOI18N                
            try{
                Document doc = getDocument();
                doc.remove(0, doc.getLength());
                getEditorKit().read(in, getDocument(), 0);  //!!! still too expensive to be called from AWT
                setCaretPosition(0);
                if (reference != null) {
                    SwingUtilities.invokeLater(new Runnable(){
                        public void run(){
                            scrollToReference(reference);
                        }
                    });
                } else {
                    scrollRectToVisible(new Rectangle(0,0,0,0));
                }
            }catch(IOException ioe){
                ioe.printStackTrace();
            }catch(BadLocationException ble){
                ble.printStackTrace();
            }
        }
    });
}
 
Example 16
Project: dev-courses   File: SessionData.java   Source Code and License 5 votes vote down vote up
private void allocateClobSegments(long lobID, long offset,
                                  Reader reader) throws IOException {

    int             bufferLength  = session.getStreamBlockSize();
    CharArrayWriter charWriter    = new CharArrayWriter(bufferLength);
    long            currentOffset = offset;

    while (true) {
        charWriter.reset();
        charWriter.write(reader, bufferLength);

        char[] charArray = charWriter.getBuffer();

        if (charWriter.size() == 0) {
            return;
        }

        Result actionResult = database.lobManager.setChars(lobID,
            currentOffset, charArray, charWriter.size());

        currentOffset += charWriter.size();

        if (charWriter.size() < bufferLength) {
            return;
        }
    }
}
 
Example 17
Project: googles-monorepo-demo   File: ReaderInputStream.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new input stream that will encode the characters from {@code reader} into bytes using
 * the given character set. Malformed input and unmappable characters will be replaced.
 *
 * @param reader input source
 * @param charset character set used for encoding chars to bytes
 * @param bufferSize size of internal input and output buffers
 * @throws IllegalArgumentException if bufferSize is non-positive
 */
ReaderInputStream(Reader reader, Charset charset, int bufferSize) {
  this(
      reader,
      charset
          .newEncoder()
          .onMalformedInput(CodingErrorAction.REPLACE)
          .onUnmappableCharacter(CodingErrorAction.REPLACE),
      bufferSize);
}
 
Example 18
Project: googles-monorepo-demo   File: SourceSinkFactories.java   Source Code and License 5 votes vote down vote up
@Override
public String getSinkContents() throws IOException {
  File file = getFile();
  Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8);
  StringBuilder builder = new StringBuilder();
  CharBuffer buffer = CharBuffer.allocate(100);
  while (reader.read(buffer) != -1) {
    buffer.flip();
    builder.append(buffer);
    buffer.clear();
  }
  return builder.toString();
}
 
Example 19
Project: util   File: PropertiesUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 从字符串内容加载Properties
 */
public static Properties loadFromString(String content) {
	Properties p = new Properties();
	Reader reader = new StringReader(content);
	try {
		p.load(reader);
	} catch (IOException ignored) {
	} finally {
		IOUtil.closeQuietly(reader);
	}

	return p;
}
 
Example 20
Project: elasticsearch_my   File: XMoreLikeThis.java   Source Code and License 5 votes vote down vote up
/**
 * Adds term frequencies found by tokenizing text from reader into the Map words
 *
 * @param r a source of text to be tokenized
 * @param termFreqMap a Map of terms and their frequencies
 * @param fieldName Used by analyzer for any special per-field analysis
 */
private void addTermFrequencies(Reader r, Map<String, Int> termFreqMap, String fieldName)
        throws IOException {
    if (analyzer == null) {
        throw new UnsupportedOperationException("To use MoreLikeThis without " +
                "term vectors, you must provide an Analyzer");
    }
    try (TokenStream ts = analyzer.tokenStream(fieldName, r)) {
        int tokenCount = 0;
        // for every token
        CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
        ts.reset();
        while (ts.incrementToken()) {
            String word = termAtt.toString();
            tokenCount++;
            if (tokenCount > maxNumTokensParsed) {
                break;
            }
            if (isNoiseWord(word)) {
                continue;
            }
            if (isSkipTerm(fieldName, word)) {
                continue;
            }

            // increment frequency
            Int cnt = termFreqMap.get(word);
            if (cnt == null) {
                termFreqMap.put(word, new Int());
            } else {
                cnt.x++;
            }
        }
        ts.end();
    }
}
 
Example 21
Project: CF-rating-prediction   File: JsonReader.java   Source Code and License 5 votes vote down vote up
private static String readWhole(Reader reader) throws IOException {
    StringBuilder text = new StringBuilder();
    char[] cbuf = new char[BUFFER_SIZE];
    int readed = 0;
    while (readed != -1) {
        readed = reader.read(cbuf);
        if (readed > 0) {
            text.append(Arrays.copyOfRange(cbuf, 0, readed));
        }
    }
    return text.toString();
}
 
Example 22
Project: BaseClient   File: PlayerProfileCache.java   Source Code and License 5 votes vote down vote up
/**
 * Load the cached profiles from disk
 */
public void load()
{
    BufferedReader bufferedreader = null;

    try
    {
        bufferedreader = Files.newReader(this.usercacheFile, Charsets.UTF_8);
        List<PlayerProfileCache.ProfileEntry> list = (List)this.gson.fromJson((Reader)bufferedreader, TYPE);
        this.usernameToProfileEntryMap.clear();
        this.uuidToProfileEntryMap.clear();
        this.gameProfiles.clear();

        for (PlayerProfileCache.ProfileEntry playerprofilecache$profileentry : Lists.reverse(list))
        {
            if (playerprofilecache$profileentry != null)
            {
                this.addEntry(playerprofilecache$profileentry.getGameProfile(), playerprofilecache$profileentry.getExpirationDate());
            }
        }
    }
    catch (FileNotFoundException var9)
    {
        ;
    }
    catch (JsonParseException var10)
    {
        ;
    }
    finally
    {
        IOUtils.closeQuietly((Reader)bufferedreader);
    }
}
 
Example 23
Project: lams   File: RollingCharBuffer.java   Source Code and License 5 votes vote down vote up
/** Clear array and switch to new reader. */
public void reset(Reader reader) {
  this.reader = reader;
  nextPos = 0;
  nextWrite = 0;
  count = 0;
  end = false;
}
 
Example 24
Project: OpenJSharp   File: XMLStreamReaderFactory.java   Source Code and License 5 votes vote down vote up
@Override
public XMLStreamReader doCreate(String systemId, Reader in, boolean rejectDTDs) {
    try {
        return xif.get().createXMLStreamReader(systemId,in);
    } catch (XMLStreamException e) {
        throw new XMLReaderException("stax.cantCreate",e);
    }
}
 
Example 25
Project: jdk8u-jdk   File: DTDInputStream.java   Source Code and License 5 votes vote down vote up
/**
 * Push an entire input stream
 */
void push(Reader in) throws IOException {
    stack.push(new Integer(ln));
    stack.push(new Integer(ch));
    stack.push(this.in);
    this.in = in;
    ch = in.read();
}
 
Example 26
Project: openjdk-jdk10   File: ValidatorHandlerImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Resolves the given resource and adapts the <code>LSInput</code>
 * returned into an <code>InputSource</code>.
 */
public InputSource resolveEntity(String name, String publicId,
        String baseURI, String systemId) throws SAXException, IOException {
    if (fEntityResolver != null) {
        LSInput lsInput = fEntityResolver.resolveResource(XML_TYPE, null, publicId, systemId, baseURI);
        if (lsInput != null) {
            final String pubId = lsInput.getPublicId();
            final String sysId = lsInput.getSystemId();
            final String baseSystemId = lsInput.getBaseURI();
            final Reader charStream = lsInput.getCharacterStream();
            final InputStream byteStream = lsInput.getByteStream();
            final String data = lsInput.getStringData();
            final String encoding = lsInput.getEncoding();

            /**
             * An LSParser looks at inputs specified in LSInput in
             * the following order: characterStream, byteStream,
             * stringData, systemId, publicId. For consistency
             * with the DOM Level 3 Load and Save Recommendation
             * use the same lookup order here.
             */
            InputSource inputSource = new InputSource();
            inputSource.setPublicId(pubId);
            inputSource.setSystemId((baseSystemId != null) ? resolveSystemId(sysId, baseSystemId) : sysId);

            if (charStream != null) {
                inputSource.setCharacterStream(charStream);
            }
            else if (byteStream != null) {
                inputSource.setByteStream(byteStream);
            }
            else if (data != null && data.length() != 0) {
                inputSource.setCharacterStream(new StringReader(data));
            }
            inputSource.setEncoding(encoding);
            return inputSource;
        }
    }
    return null;
}
 
Example 27
Project: Equella   File: AbstractOffice2007Extracter.java   Source Code and License 5 votes vote down vote up
private static void gatherValuesForTagName(String tagName, Reader xml, StringBuilder gatherer, int maxSize)
	throws XmlPullParserException, IOException
{
	XmlPullParser parser = new MXParser();
	parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
	parser.setInput(xml);

	int event = parser.getEventType();
	while( event != XmlPullParser.END_DOCUMENT )
	{
		if( event == XmlPullParser.START_TAG && parser.getName().equals(tagName) )
		{
			while( parser.next() == XmlPullParser.TEXT )
			{
				String s = parser.getText();
				if( s != null )
				{
					// Removal all tabs, newlines, returns, etc.. and trim
					// white space
					s = s.replaceAll("\\cM?\r?\r\n\t", "").trim();
					if( s.length() > 0 )
					{
						gatherer.append(s);
						gatherer.append(' ');
					}
				}
			}

			if( gatherer.length() >= maxSize )
			{
				return;
			}
		}
		event = parser.next();
	}
}
 
Example 28
Project: PACE   File: SignatureConfigBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Read the configuration from a Reader.
 *
 * @param in
 *          Stream to read from.
 * @return builder.
 */
public SignatureConfigBuilder readFromFile(Reader in) throws IOException {
  Ini configIni = new Ini(in);
  Section section = configIni.get(SignatureConfig.SECTION_NAME);

  setSigner(ValueSigner.fromString(section.get("algorithm")));
  setDestination(section.containsKey("destination") ? Destination.fromString(section.get("destination")) : Destination.VALUE);
  setProvider(section.get("provider")).setDestinationTable(section.get("table"));
  setDefaultVisibility(section.containsKey("defaultVisibility") ? section.get("defaultVisibility").getBytes(VISIBILITY_CHARSET) : null);

  return this;
}
 
Example 29
Project: InstaShare   File: JsonReader.java   Source Code and License 5 votes vote down vote up
private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}
 
Example 30
Project: bibliome-java-utils   File: JSONUtils.java   Source Code and License 5 votes vote down vote up
public static void main(String args[]) throws ParserConfigurationException, IOException, TransformerException {
	Reader reader = new FileReader(args[0]);
	Object object = JSONValue.parse(reader);
	reader.close();
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = dbf.newDocumentBuilder();
	Document doc = toXML(docBuilder, object);
	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	Source source = new DOMSource(doc);
	Result result = new StreamResult(new File(args[1]));
	transformer.transform(source, result);
}
 
Example 31
Project: nativead   File: IOUtils.java   Source Code and License 5 votes vote down vote up
private static void close(Object obj) {
	if (obj == null) {
		return;
	}
	
	if (obj instanceof InputStream) {
		closeIS((InputStream) obj);
	} else if (obj instanceof OutputStream) {
		closeOS((OutputStream) obj);
	} else if (obj instanceof Writer) {
		closeWriter((Writer) obj);
	} else if (obj instanceof Reader) {
		closeReader((Reader) obj);
	} else if (obj instanceof RandomAccessFile) {
		closeFile((RandomAccessFile) obj);
	} else if (obj instanceof Socket) {
		closeSocket((Socket) obj);
	} else if (obj instanceof ServerSocket) {
		closeServerSocket((ServerSocket) obj);
	} else if (obj instanceof Process) {
		closeProcess((Process) obj);
	} else if (obj instanceof Cursor) {
		closeCursor((Cursor) obj);
	} else if (obj instanceof Closeable) {
		close((Closeable) obj);
	} else {
		throw new RuntimeException("unSupport");
	}
}
 
Example 32
Project: flume-release-1.7.0   File: TestAbstractZooKeeperConfigurationProvider.java   Source Code and License 5 votes vote down vote up
protected void addData() throws Exception {
  Reader in = new InputStreamReader(getClass().getClassLoader()
      .getResourceAsStream(FLUME_CONF_FILE), Charsets.UTF_8);
  try {
    String config = IOUtils.toString(in);
    client.setData().forPath(AGENT_PATH, config.getBytes());
  } finally {
    in.close();
  }
}
 
Example 33
Project: jdk8u-jdk   File: StubWebRowSetImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void setClob(String parameterName, Reader reader) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 34
Project: FSTestTools   File: MockingGenerationContext.java   Source Code and License 4 votes vote down vote up
@Override
public TemplateDocument parse(final Reader reader) throws IOException {
    return null;
}
 
Example 35
Project: org.ops4j.pax.transx   File: StubResultSet.java   Source Code and License 4 votes vote down vote up
/** {@inheritDoc} */
public void updateCharacterStream(int columnIndex, Reader x) throws SQLException
{
}
 
Example 36
Project: openjdk-jdk10   File: StubWebRowSetImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void setClob(String parameterName, Reader reader, long length) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 37
Project: openjdk-jdk10   File: StubJoinRowSetImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void setClob(String parameterName, Reader reader) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 38
Project: dacapobench   File: TargetJDK1_4.java   Source Code and License 4 votes vote down vote up
public JavaParserTokenManager createJavaParserTokenManager(Reader in) {
    return new JavaParserTokenManager(new JavaCharStream(in));
}
 
Example 39
Project: OpenVertretung   File: JDBC4MysqlSQLXML.java   Source Code and License 4 votes vote down vote up
Reader toReader() {
    return new StringReader(this.buf.toString());
}
 
Example 40
Project: OpenJSharp   File: SourceReaderFactory.java   Source Code and License 4 votes vote down vote up
public static XMLStreamReader createSourceReader(Source source, boolean rejectDTDs, String charsetName) {
    try {
        if (source instanceof StreamSource) {
            StreamSource streamSource = (StreamSource) source;
            InputStream is = streamSource.getInputStream();

            if (is != null) {
                // Wrap input stream in Reader if charset is specified
                if (charsetName != null) {
                    return XMLStreamReaderFactory.create(
                        source.getSystemId(), new InputStreamReader(is, charsetName), rejectDTDs);
                }
                else {
                    return XMLStreamReaderFactory.create(
                        source.getSystemId(), is, rejectDTDs);
                }
            }
            else {
                Reader reader = streamSource.getReader();
                if (reader != null) {
                    return XMLStreamReaderFactory.create(
                        source.getSystemId(), reader, rejectDTDs);
                }
                else {
                    return XMLStreamReaderFactory.create(
                        source.getSystemId(), new URL(source.getSystemId()).openStream(), rejectDTDs );
                }
            }
        }
        else if (source.getClass() == fastInfosetSourceClass) {
            return FastInfosetUtil.createFIStreamReader((InputStream)
                fastInfosetSource_getInputStream.invoke(source));
        }
        else if (source instanceof DOMSource) {
            DOMStreamReader dsr =  new DOMStreamReader();
            dsr.setCurrentNode(((DOMSource) source).getNode());
            return dsr;
        }
        else if (source instanceof SAXSource) {
            // TODO: need SAX to StAX adapter here -- Use transformer for now
            Transformer tx =  XmlUtil.newTransformer();
            DOMResult domResult = new DOMResult();
            tx.transform(source, domResult);
            return createSourceReader(
                new DOMSource(domResult.getNode()),
                rejectDTDs);
        }
        else {
            throw new XMLReaderException("sourceReader.invalidSource",
                    source.getClass().getName());
        }
    }
    catch (Exception e) {
        throw new XMLReaderException(e);
    }
}
 
Example 41
Project: apache-tomcat-7.0.73-with-comment   File: Statement.java   Source Code and License 4 votes vote down vote up
@Override
public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException {
    // TODO Auto-generated method stub

}
 
Example 42
Project: agroal   File: MockResultSet.java   Source Code and License 4 votes vote down vote up
@Override
default void updateCharacterStream(String columnLabel, Reader reader) throws SQLException {
}
 
Example 43
Project: Agent-Benchmarks   File: SimulateResultSet.java   Source Code and License 4 votes vote down vote up
@Override public Reader getNCharacterStream(int columnIndex) throws SQLException {
    return null;
}
 
Example 44
Project: openjdk-jdk10   File: StubCachedRowSetImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 45
Project: aliyun-maxcompute-data-collectors   File: MockResultSet.java   Source Code and License 4 votes vote down vote up
@Override
public void updateNClob(int columnIndex, Reader reader) throws SQLException {
}
 
Example 46
Project: jdk8u-jdk   File: StubCachedRowSetImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void setNCharacterStream(String parameterName, Reader value) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 47
Project: incubator-netbeans   File: CreateLicenseSummary.java   Source Code and License 4 votes vote down vote up
static Map<String, Map<String, String>> findBinary2LicenseHeaderMapping(Set<String> cvsFiles, File d) throws IOException {
    Map<String, Map<String, String>> binary2LicenseHeaders = new HashMap<>();
    for (String n : cvsFiles) {
        if (!n.endsWith("-license.txt")) {
            continue;
        }
        Map<String, String> headers = new HashMap<>();
        try (InputStream is = new FileInputStream(new File(d, n))) {
            BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            while ((line = r.readLine()) != null && line.length() > 0) {
                Matcher m = Pattern.compile("([a-zA-Z]+): (.+)").matcher(line);
                if (m.matches()) {
                    headers.put(m.group(1), m.group(2));
                }
            }
            r.close();
        }
        String files = headers.remove("Files");
        if (files != null) {
            for (String file : files.split("[, ]+")) {
                binary2LicenseHeaders.put(file, headers);
            }
        } else {
            binary2LicenseHeaders.put(n.replaceFirst("-license\\.txt$", ".jar"), headers);
            binary2LicenseHeaders.put(n.replaceFirst("-license\\.txt$", ".zip"), headers);
            binary2LicenseHeaders.put(n.replaceFirst("-license\\.txt$", ".xml"), headers);
            binary2LicenseHeaders.put(n.replaceFirst("-license\\.txt$", ".js"), headers);
            binary2LicenseHeaders.put(n.replaceFirst("-license\\.txt$", ".dylib"), headers);
        }
        File notice = new File(d, n.replace("-license.txt", "-notice.txt"));
        if (notice.canRead()) {
            StringBuilder noticeText = new StringBuilder();
            try (Reader r = new InputStreamReader(new FileInputStream(notice), "UTF-8")) {
                int read;
                while ((read = r.read()) != (-1)) {
                    noticeText.append((char) read);
                }
            }
            headers.put("notice", noticeText.toString());
        }
    }
    return binary2LicenseHeaders;
}
 
Example 48
Project: Krine   File: KrineInterpreter.java   Source Code and License 4 votes vote down vote up
public KrineInterpreter(Reader in, PrintStream out, PrintStream err, NameSpace namespace, KrineBasicInterpreter parent, String sourceFileInfo) {
    super(in, out, err, namespace, parent);
    init();
}
 
Example 49
Project: incubator-netbeans   File: VerifyLibsAndLicenses.java   Source Code and License 4 votes vote down vote up
private void testLicenseFilesAreProperlyFormattedPhysically() throws IOException {
    StringBuffer msg = new StringBuffer();
    for (String module : modules) {
        File d = new File(new File(nball, module), "external");
        FILE: for (String n : findHgControlledFiles(d)) {
            String path = module + "/external/" + n;
            if (!n.endsWith("-license.txt")) {
                continue;
            }
            File f = new File(d, n);
            InputStream is = new FileInputStream(f);
            int line = 1;
            try {
                CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder().
                        onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
                Reader r = new InputStreamReader(is, decoder);
                int column = 0;
                boolean pastHeader = false;
                boolean trailingSpace = false;
                int c;
                while ((c = r.read()) != -1) {
                    if (trailingSpace && (c == '\r' || c == '\n')) {
                        msg.append("\n" + path + " has a trailing space on line #" + line);
                        continue FILE;
                    }
                    if (c == '\r') {
                        column = 0;
                    } else if (c == '\n') {
                        if (column == 0 && line > 1 && !pastHeader) {
                            pastHeader = true;
                            //System.err.println("encountered header end in " + path + " at line " + line);
                        }
                        column = 0;
                        line++;
                    } else if (c == '\f') {
                        msg.append("\n" + path + " uses a form feed (^L) on line #" + line);
                        continue FILE;
                    } else {
                        trailingSpace = c == ' ';
                        column++;
                        if (pastHeader && column > MAX_LINE_LEN && CHECK_MAX_LINE_LEN) {
                            msg.append("\n" + path + " has line #" + line + " longer than 80 characters");
                            continue FILE;
                        }
                    }
                }
                if (column > 0) {
                    msg.append("\n" + path + " must end in a newline");
                }
            } catch (IOException x) {
                msg.append("\n" + path + " at line #" + line + ": " + x);
            } finally {
                is.close();
            }
        }
    }
    pseudoTests.put("testLicenseFilesAreProperlyFormattedPhysically", msg.length() > 0 ? "Some license files were badly formatted" + msg : null);
}
 
Example 50
Project: ytk-learn   File: MulticlassLinearOnlinePredictor.java   Source Code and License 4 votes vote down vote up
public MulticlassLinearOnlinePredictor(Reader configReader) throws Exception {
    super(configReader);
    this.K = config.getInt("k");
    loadModel();
}
 
Example 51
Project: Guardian.java   File: JsonConverter.java   Source Code and License 4 votes vote down vote up
<T> T parse(Class<T> classOfT, Reader reader) throws IOException {
    return mapper.readValue(reader, classOfT);
}
 
Example 52
Project: openjdk-jdk10   File: DOMEntityResolverWrapper.java   Source Code and License 4 votes vote down vote up
/**
 * Resolves an external parsed entity. If the entity cannot be
 * resolved, this method should return null.
 *
 * @param resourceIdentifier        description of the resource to be revsoved
 * @throws XNIException Thrown on general error.
 * @throws IOException  Thrown if resolved entity stream cannot be
 *                      opened or some other i/o error occurs.
 */
public XMLInputSource resolveEntity(XMLResourceIdentifier resourceIdentifier)
    throws XNIException, IOException {
    // resolve entity using DOM entity resolver
    if (fEntityResolver != null) {
        // For entity resolution the type of the resource would be  XML TYPE
        // DOM L3 LS spec mention only the XML 1.0 recommendation right now
        LSInput inputSource =
            resourceIdentifier == null
                ? fEntityResolver.resolveResource(
                    null,
                    null,
                    null,
                    null,
                    null)
                : fEntityResolver.resolveResource(
                    getType(resourceIdentifier),
                    resourceIdentifier.getNamespace(),
                    resourceIdentifier.getPublicId(),
                    resourceIdentifier.getLiteralSystemId(),
                    resourceIdentifier.getBaseSystemId());
        if (inputSource != null) {
            String publicId = inputSource.getPublicId();
            String systemId = inputSource.getSystemId();
            String baseSystemId = inputSource.getBaseURI();
            InputStream byteStream = inputSource.getByteStream();
            Reader charStream = inputSource.getCharacterStream();
            String encoding = inputSource.getEncoding();
            String data = inputSource.getStringData();

            /**
             * An LSParser looks at inputs specified in LSInput in
             * the following order: characterStream, byteStream,
             * stringData, systemId, publicId.
             */
            XMLInputSource xmlInputSource =
                new XMLInputSource(publicId, systemId, baseSystemId, true);

            if (charStream != null) {
                xmlInputSource.setCharacterStream(charStream);
            }
            else if (byteStream != null) {
                xmlInputSource.setByteStream((InputStream) byteStream);
            }
            else if (data != null && data.length() != 0) {
                xmlInputSource.setCharacterStream(new StringReader(data));
            }
            xmlInputSource.setEncoding(encoding);
            return xmlInputSource;
        }
    }

    // unable to resolve entity
    return null;

}
 
Example 53
Project: dswork   File: CallableStatementSpy.java   Source Code and License 4 votes vote down vote up
public Reader getNCharacterStream(String parameterName) throws SQLException
{
	return realCallableStatement.getNCharacterStream(parameterName);
}
 
Example 54
Project: trellis   File: HtmlSerializer.java   Source Code and License 4 votes vote down vote up
private Reader getReader(final String template) {
    if (template.startsWith("/")) {
        return new InputStreamReader(getClass().getResourceAsStream(template), UTF_8);
    }
    return new InputStreamReader(getClass().getResourceAsStream("/" + template), UTF_8);
}
 
Example 55
Project: sstore-soft   File: JDBC4ResultSet.java   Source Code and License 4 votes vote down vote up
@Override
public void updateCharacterStream(int columnIndex, Reader x, long length)
        throws SQLException {
    throw SQLError.noSupport();
}
 
Example 56
Project: hanlp-ext   File: SegmentWrapper.java   Source Code and License 4 votes vote down vote up
public SegmentWrapper(Reader reader, Segment segment) {
    scanner = createScanner(reader);
    this.segment = segment;
}
 
Example 57
Project: jdk8u-jdk   File: StubJoinRowSetImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 58
Project: QDrill   File: SqlAccessor.java   Source Code and License 4 votes vote down vote up
/** (See {@link SqlAccessor class description}.) */
Reader getReader(int rowOffset) throws InvalidAccessException;
 
Example 59
Project: GitHub   File: JSONReader.java   Source Code and License 4 votes vote down vote up
public JSONReader(Reader reader, Feature... features){
    this(new JSONReaderScanner(reader));
    for (Feature feature : features) {
        this.config(feature, true);
    }
}
 
Example 60
Project: dev-courses   File: TestScriptRunner.java   Source Code and License 4 votes vote down vote up
public ScriptRun(String name, Reader reader, RCData rcdata) {
    super(name);
    this.reader = reader;
    this.rcdata = rcdata;
}