java.io.Reader Java Examples
The following examples show how to use
java.io.Reader.
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: CSVRecordReader.java From nifi with Apache License 2.0 | 6 votes |
public CSVRecordReader(final InputStream in, final ComponentLog logger, final RecordSchema schema, final CSVFormat csvFormat, final boolean hasHeader, final boolean ignoreHeader, final String dateFormat, final String timeFormat, final String timestampFormat, final String encoding) throws IOException { super(logger, schema, hasHeader, ignoreHeader, dateFormat, timeFormat, timestampFormat); final Reader reader = new InputStreamReader(new BOMInputStream(in), encoding); CSVFormat withHeader; if (hasHeader) { withHeader = csvFormat.withSkipHeaderRecord(); if (ignoreHeader) { withHeader = withHeader.withHeader(schema.getFieldNames().toArray(new String[0])); } else { withHeader = withHeader.withFirstRecordAsHeader(); } } else { withHeader = csvFormat.withHeader(schema.getFieldNames().toArray(new String[0])); } csvParser = new CSVParser(reader, withHeader); }
Example #2
Source File: XSLTProcessor.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
public void processString(final String template, Object model, Writer out) { TemplateSource stringTemplateSource = new TemplateSource() { public long lastModified() { return System.currentTimeMillis(); } public InputStream getResource(String name) { return null; } public Reader getReader(String encoding) throws IOException { return new StringReader(template); } public void close() throws IOException { } }; process(stringTemplateSource, model, out); }
Example #3
Source File: PayloadMediaTypeJsonXmlDefaultTestCase.java From micro-integrator with Apache License 2.0 | 6 votes |
@Test(groups = "wso2.esb", description = "sending xml request using media-type application/xml") public void invokeServiceFromXmlRequest() throws Exception { // xml request payload String payload = "<xml><id_str>84315710834212866</id_str>\n" + "\t<entities>\n" + "\t\t<hashtags>\n" + "\t\t\t<text>peterfalk</text>\n" + "\t\t\t<indices>35</indices>\n" + "\t\t\t<indices>45</indices>\n" + "\t\t</hashtags>\n" + "\t</entities>\n" + "\t<text>Maybe he'll finally find his keys. #peterfalk</text>\n" + "\t<user>\n" + "\t\t<id_str>819797</id_str>\n" + "\t\t<id>819797</id>\n" + "\t</user></xml>"; Reader data = new StringReader(payload); Writer writer = new StringWriter(); String response = HttpURLConnectionClient .sendPostRequestAndReadResponse(data, new URL(serviceURL), writer, "application/xml"); assertNotNull(response, "Response is null"); assertTrue(response.contains("\"id_str\": \"peterfalk\"")); }
Example #4
Source File: TeeReaderTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldDuplicateStreams() { String expected = "{\"key\": \"value\"}"; Reader source = new StringReader(expected); StringWriter writer = new StringWriter(); Reader tee = new TeeReader(source, writer); try (JsonInput reader = new Json().newInput(tee)) { reader.beginObject(); assertEquals("key", reader.nextName()); reader.skipValue(); reader.endObject(); assertEquals(expected, writer.toString()); } }
Example #5
Source File: NntpUtil.java From scava with Eclipse Public License 2.0 | 6 votes |
public static String getArticleBody(NNTPClient client, long articleNumber) throws IOException { String articleBody = null; //We convert the full message into a MIME message for getting exactly the text message clean Reader reader = (DotTerminatedMessageReader) client.retrieveArticle(articleNumber); if (reader != null) { InputStream inputStream = new ByteArrayInputStream(CharStreams.toString(reader).getBytes(Charsets.UTF_8)); try { Session session = Session.getInstance(new Properties()); //For parsing the messages correctly MimeMessage message = new MimeMessage(session, inputStream); Object contentObject = message.getContent(); if(!(contentObject instanceof MimeMultipart)) articleBody = (String)contentObject; else articleBody = getBodyPart((MimeMultipart) contentObject); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { return articleBody; } return articleBody; }
Example #6
Source File: CellResource.java From io with Apache License 2.0 | 6 votes |
/** * PROPPATCHメソッドの処理. * @param requestBodyXml Request Body * @return JAX-RS Response */ @WebDAVMethod.PROPPATCH public Response proppatch(final Reader requestBodyXml) { AccessContext ac = this.cellRsCmp.getAccessContext(); // トークンの有効性チェック // トークンがINVALIDでもACL設定でPrivilegeがallに設定されているとアクセスを許可する必要があるのでこのタイミングでチェック ac.updateBasicAuthenticationStateForResource(null); if (AccessContext.TYPE_INVALID.equals(ac.getType())) { ac.throwInvalidTokenException(this.cellRsCmp.getAcceptableAuthScheme()); } else if (AccessContext.TYPE_ANONYMOUS.equals(ac.getType())) { throw DcCoreAuthzException.AUTHORIZATION_REQUIRED.realm(ac.getRealm(), this.cellRsCmp.getAcceptableAuthScheme()); } // アクセス制御 CellレベルPROPPATCHはユニットユーザのみ可能とする if (!ac.isUnitUserToken()) { throw DcCoreException.Auth.UNITUSER_ACCESS_REQUIRED; } return this.cellRsCmp.doProppatch(requestBodyXml); }
Example #7
Source File: JbpmBpmn2TestCase.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private String toString(Reader reader) throws IOException { StringBuilder sb = new StringBuilder(1024); int charValue; while ((charValue = reader.read()) != -1) { sb.append((char) charValue); } return sb.toString(); }
Example #8
Source File: StreamUtil.java From iaf with Apache License 2.0 | 5 votes |
public static void copyReaderToWriter(Reader reader, Writer writer, int chunkSize, boolean resolve, boolean xmlEncode) throws IOException { if (reader!=null) { char buffer[]=new char[chunkSize]; int charsRead=1; while (charsRead>0) { charsRead=reader.read(buffer,0,chunkSize); if (charsRead>0) { // if (log.isDebugEnabled()) { log.debug(new String(buffer).substring(0,bytesRead)); } if (resolve) { String resolved = StringResolver.substVars(new String (buffer,0,charsRead),null); if (xmlEncode) { writer.write(XmlUtils.encodeChars(resolved)); } else { writer.write(resolved); } } else { if (xmlEncode) { writer.write(XmlUtils.encodeChars(buffer,0,charsRead)); } else { writer.write(buffer,0,charsRead); } } } else { reader.close(); } } } }
Example #9
Source File: Util.java From rxjava-jdbc with Apache License 2.0 | 5 votes |
private static <T> Object getObject(final ResultSet rs, Class<T> cls, int i) { try { if (rs.getObject(i) == null) { return null; } final int type = rs.getMetaData().getColumnType(i); // TODO java.util.Calendar support // TODO XMLGregorian Calendar support if (type == Types.DATE) return rs.getDate(i, Calendar.getInstance()); else if (type == Types.TIME) return rs.getTime(i, Calendar.getInstance()); else if (type == Types.TIMESTAMP) return rs.getTimestamp(i, Calendar.getInstance()); else if (type == Types.CLOB && cls.equals(String.class)) { return toString(rs.getClob(i)); } else if (type == Types.CLOB && Reader.class.isAssignableFrom(cls)) { Clob c = rs.getClob(i); Reader r = c.getCharacterStream(); return createFreeOnCloseReader(c, r); } else if (type == Types.BLOB && cls.equals(byte[].class)) { return toBytes(rs.getBlob(i)); } else if (type == Types.BLOB && InputStream.class.isAssignableFrom(cls)) { final Blob b = rs.getBlob(i); final InputStream is = rs.getBlob(i).getBinaryStream(); return createFreeOnCloseInputStream(b, is); } else return rs.getObject(i); } catch (SQLException e) { throw new SQLRuntimeException(e); } }
Example #10
Source File: MtasTokenizer.java From mtas with Apache License 2.0 | 5 votes |
/** * Prints the. * * @param r the r * @throws MtasParserException the mtas parser exception */ public void print(final Reader r) throws MtasParserException { try { setReader(r); reset(); if (tokenCollection != null) { tokenCollection.print(); } end(); close(); } catch (IOException e) { log.error(e); throw new MtasParserException(e.getClass() + " : " + e.getMessage()); } }
Example #11
Source File: CheckSpecificConfigurationTest.java From revapi with Apache License 2.0 | 5 votes |
@Test public void testCheckConfigured() throws Exception { class FakeCheck extends CheckBase { Boolean testCheck = null; @Override public EnumSet<Type> getInterest() { return null; } @Nullable @Override public String getExtensionId() { return "testCheck"; } @Nullable @Override public Reader getJSONSchema() { return new StringReader("{\"type\": \"boolean\"}"); } @Override public void initialize(@Nonnull AnalysisContext analysisContext) { testCheck = analysisContext.getConfiguration().asBoolean(); } } FakeCheck check = new FakeCheck(); JavaApiAnalyzer analyzer = new JavaApiAnalyzer(Collections.singleton(check), Collections.emptyList()); String config = "{\"checks\": {\"testCheck\": true}}"; analyzer.initialize(AnalysisContext.builder().build().copyWithConfiguration(ModelNode.fromJSONString(config))); Assert.assertTrue(check.testCheck); }
Example #12
Source File: ProjectTemplateStore.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public static boolean hasProjectSpecificTempates(IProject project) { String pref= new ProjectScope(project).getNode(JavaUI.ID_PLUGIN).get(KEY, null); if (pref != null && pref.trim().length() > 0) { Reader input= new StringReader(pref); TemplateReaderWriter reader= new TemplateReaderWriter(); TemplatePersistenceData[] datas; try { datas= reader.read(input); return datas.length > 0; } catch (IOException e) { // ignore } } return false; }
Example #13
Source File: ConversationRepository.java From Game-of-Thrones with Apache License 2.0 | 5 votes |
private void initConversations() { try { Gson gson = new Gson(); InputStream inputStream = context.getAssets().open("conversations.json"); Reader reader = new InputStreamReader(inputStream, "UTF-8"); Conversation[] parsedList = gson.fromJson(reader, Conversation[].class); for (Conversation conversation : parsedList) { conversations.put(conversation.getId(), conversation); } } catch (Exception e) { Log.e(TAG, "initConversations: ", e); } }
Example #14
Source File: Strings.java From rxjava-extras with Apache License 2.0 | 5 votes |
public static Observable<String> from(final Func0<Reader> readerFactory) { Func1<Reader, Observable<String>> observableFactory = new Func1<Reader, Observable<String>>() { @Override public Observable<String> call(Reader reader) { return from(reader); } }; return Observable.using(readerFactory, observableFactory, DisposeActionHolder.INSTANCE, true); }
Example #15
Source File: MessageDecoder.java From diirt with MIT License | 5 votes |
@Override public Message decode(Reader reader) throws DecodeException, IOException { JsonReader jReader = Json.createReader(reader); JsonObject jObject = jReader.readObject(); String messageType = jObject.getString("message", null); switch (messageType) { case "subscribe": return new MessageSubscribe(jObject); case "write": return new MessageWrite(jObject); case "pause": return new MessagePause(jObject); case "resume": return new MessageResume(jObject); case "unsubscribe": return new MessageUnsubscribe(jObject); case "event": String eventType = jObject.getString("type"); switch(eventType) { case "connection": return new MessageConnectionEvent(jObject); case "value": return new MessageValueEvent(jObject); case "writeCompleted": return new MessageWriteCompletedEvent(jObject); case "error": return new MessageErrorEvent(jObject); default: throw new DecodeException("", "Event " + eventType + " is not supported"); } default: throw MessageDecodeException.unsupportedMessage(jObject); } }
Example #16
Source File: Scanner.java From multiregexp with MIT License | 5 votes |
public void reset(final Reader reader) { this.reader = reader; this.start = 0; this.end = 0; this.endOfReader = false; this.type = null; this.readerLength = Integer.MAX_VALUE; this.readUntil = 0; }
Example #17
Source File: SPTest.java From mybatis with Apache License 2.0 | 5 votes |
@BeforeClass public static void initDatabase() throws Exception { Connection conn = null; try { Class.forName("org.hsqldb.jdbcDriver"); conn = DriverManager.getConnection("jdbc:hsqldb:mem:sptest", "sa", ""); Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/sptests/CreateDB.sql"); ScriptRunner runner = new ScriptRunner(conn); runner.setDelimiter("go"); runner.setLogWriter(null); runner.setErrorLogWriter(null); runner.runScript(reader); conn.commit(); reader.close(); reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/sptests/MapperConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); reader.close(); } finally { if (conn != null) { conn.close(); } } }
Example #18
Source File: NashornScriptEngine.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
private static Source makeSource(final Reader reader, final ScriptContext ctxt) throws ScriptException { try { return sourceFor(getScriptName(ctxt), reader); } catch (final IOException e) { throw new ScriptException(e); } }
Example #19
Source File: JSONImportTest.java From enhydrator with Apache License 2.0 | 5 votes |
VirtualSinkSource getSource(final String fileName) throws FileNotFoundException { final Path pathToContent = Paths.get(fileName); Reader script = new FileReader("./src/test/files/converter.js"); Source source = new ScriptableSource(pathToContent, script, "UTF-8"); VirtualSinkSource vss = new VirtualSinkSource(); Pump pump = new Pump.Engine(). from(source). to(vss). to(new LogSink()). build(); pump.start(); return vss; }
Example #20
Source File: AuthlibAgent.java From authlib-agent with MIT License | 5 votes |
private static Properties readProperties() { Properties properties = new Properties(); try (Reader reader = new InputStreamReader(AuthlibAgent.class.getResourceAsStream("/transform.properties"), "UTF-8")) { properties.load(reader); } catch (IOException e) { LOGGER.warning("failed to read properties: " + e); e.printStackTrace(); } return properties; }
Example #21
Source File: WordsElementsFactory.java From jackrabbit-filevault with Apache License 2.0 | 5 votes |
public static WordsElementsFactory create(DocumentSource source, String text) { try { Reader reader = new StringReader(text); return create(source, reader); } catch (IOException e) { throw new IllegalArgumentException(e.toString()); } }
Example #22
Source File: Handler.java From cloudsync with GNU General Public License v2.0 | 5 votes |
private void readCSVStructure(final Path cacheFilePath) throws CloudsyncException { final Map<String, Item> mapping = new HashMap<>(); mapping.put("", root); try { final Reader in = new FileReader(cacheFilePath.toFile()); final Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in); for (final CSVRecord record : records) { final Item item = Item.fromCSV(record); final String childPath = Helper.trim(record.get(0), Item.SEPARATOR); final String parentPath = childPath.length() == item.getName().length() ? "" : StringUtils.removeEnd(FilenameUtils.getPath(childPath), Item.SEPARATOR); mapping.put(childPath, item); // System.out.println(parentPath+":"+item.getName()); Item parent = mapping.get(parentPath); item.setParent(parent); parent.addChild(item); } } catch (final IOException e) { throw new CloudsyncException("Can't read cache from file '" + cacheFilePath.toString() + "'", e); } }
Example #23
Source File: VTITemplate.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * @see java.sql.ResultSet * * @exception SQLException on unexpected JDBC error */ public void updateCharacterStream(int columnIndex, java.io.Reader x, int length) throws SQLException { throw new SQLException("updateCharacterStream"); }
Example #24
Source File: StatementsTest.java From r-course with MIT License | 4 votes |
public void testStreamChange() throws Exception { createTable("testStreamChange", "(field1 varchar(32), field2 int, field3 TEXT, field4 BLOB)"); this.pstmt = this.conn.prepareStatement("INSERT INTO testStreamChange VALUES (?, ?, ?, ?)"); try { this.pstmt.setString(1, "A"); this.pstmt.setInt(2, 1); char[] cArray = { 'A', 'B', 'C' }; Reader r = new CharArrayReader(cArray); this.pstmt.setCharacterStream(3, r, cArray.length); byte[] bArray = { 'D', 'E', 'F' }; ByteArrayInputStream bais = new ByteArrayInputStream(bArray); this.pstmt.setBinaryStream(4, bais, bArray.length); assertEquals(1, this.pstmt.executeUpdate()); this.rs = this.stmt.executeQuery("SELECT field3, field4 from testStreamChange where field1='A'"); this.rs.next(); assertEquals("ABC", this.rs.getString(1)); assertEquals("DEF", this.rs.getString(2)); char[] ucArray = { 'C', 'E', 'S', 'U' }; this.pstmt.setString(1, "CESU"); this.pstmt.setInt(2, 3); Reader ucReader = new CharArrayReader(ucArray); this.pstmt.setCharacterStream(3, ucReader, ucArray.length); this.pstmt.setBinaryStream(4, null, 0); assertEquals(1, this.pstmt.executeUpdate()); this.rs = this.stmt.executeQuery("SELECT field3, field4 from testStreamChange where field1='CESU'"); this.rs.next(); assertEquals("CESU", this.rs.getString(1)); assertEquals(null, this.rs.getString(2)); } finally { if (this.rs != null) { this.rs.close(); this.rs = null; } if (this.pstmt != null) { this.pstmt.close(); this.pstmt = null; } } }
Example #25
Source File: SFAsyncResultSet.java From snowflake-jdbc with Apache License 2.0 | 4 votes |
@Override public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { raiseSQLExceptionIfResultSetIsClosed(); }
Example #26
Source File: StubJdbcRowSetImpl.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
@Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); }
Example #27
Source File: JtdsCallableStatement.java From jTDS with GNU Lesser General Public License v2.1 | 4 votes |
@Override public void setNClob(String parameterName, Reader reader) throws SQLException { // TODO Auto-generated method stub throw new AbstractMethodError(); }
Example #28
Source File: StubCachedRowSetImpl.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
@Override public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); }
Example #29
Source File: SingleHopResultSet.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
public Reader getCharacterStream(String columnLabel) throws SQLException { return this.currentResultSet.getCharacterStream(columnLabel); }
Example #30
Source File: ResultSetEmul.java From jmeter-plugins with Apache License 2.0 | 4 votes |
@Override public void updateNCharacterStream(int i, Reader reader, long l) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }