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

The following examples show how to use java.io.Reader#close() . 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: PrimitivesTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  // create an SqlSessionFactory
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/primitives/mybatis-config.xml");
  sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  reader.close();

  // populate in-memory database
  SqlSession session = sqlSessionFactory.openSession();
  Connection conn = session.getConnection();
  reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/primitives/CreateDB.sql");
  ScriptRunner runner = new ScriptRunner(conn);
  runner.setLogWriter(null);
  runner.runScript(reader);
  reader.close();
  session.close();
}
 
Example 2
Source File: CommandUtils.java    From frpMgr with MIT License 6 votes vote down vote up
public static String execute(String command, String charsetName) throws IOException {
	Process process = Runtime.getRuntime().exec(command);
	// 记录dos命令的返回信息
	StringBuffer stringBuffer = new StringBuffer();
	// 获取返回信息的流
	InputStream in = process.getInputStream();
	Reader reader = new InputStreamReader(in, charsetName);
	BufferedReader bReader = new BufferedReader(reader);
	String res = bReader.readLine();
	while (res != null) {
		stringBuffer.append(res);
		stringBuffer.append("\n");
		res = bReader.readLine();
	}
	bReader.close();
	reader.close();
	return stringBuffer.toString();
}
 
Example 3
Source File: ExtendedHTMLEditorKit.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
public ExtendedHTMLEditorKit() {
	styleSheet = new StyleSheet();
	try {
		InputStream is = HTMLEditorKit.class.getResourceAsStream(DEFAULT_CSS);
		Reader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));
		styleSheet.loadRules(r, null);
		r.close();
	} catch (Exception e) {
		// LogService.getRoot().log(Level.WARNING, "Cannot install stylesheet: "+e, e);
		LogService.getRoot().log(
				Level.WARNING,
				I18N.getMessage(LogService.getRoot().getResourceBundle(),
						"com.rapidminer.gui.tools.ExtendedHTMLEditorKit.installing_stylesheet_error", e), e);
		// on error we simply have no styles... the html
		// will look mighty wrong but still function.
	}
}
 
Example 4
Source File: NestedResultHandlerAssociationTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  // create an SqlSessionFactory
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/nestedresulthandler_association/mybatis-config.xml");
  sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  reader.close();

  // populate in-memory database
  SqlSession session = sqlSessionFactory.openSession();
  Connection conn = session.getConnection();
  reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/nestedresulthandler_association/CreateDB.sql");
  ScriptRunner runner = new ScriptRunner(conn);
  runner.setLogWriter(null);
  runner.runScript(reader);
  reader.close();
  session.close();
}
 
Example 5
Source File: MoreItemsJsonParserTest.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    final InputStream inputStream = MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_more_items_response.json");
    assertNotNull(inputStream);

    final Reader reader = new InputStreamReader(inputStream, Utils.STRING_ENCODING);

    Gson gson = ZooniverseClient.createGson();
    final ZooniverseClient.SubjectsResponse response = gson.fromJson(reader, new TypeToken<ZooniverseClient.SubjectsResponse>() {}.getType());
    assertNotNull(response);

    mSubjects = response.subjects;
    assertNotNull(mSubjects);

    reader.close();
}
 
Example 6
Source File: JavaReaderToXUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
    String initialString = "With Commons IO";
    final Reader initialReader = new StringReader(initialString);
    final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);

    String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
    assertThat(finalString, equalTo(initialString));

    initialReader.close();
    targetStream.close();
}
 
Example 7
Source File: JsonLoader.java    From Cubes with MIT License 6 votes vote down vote up
private static Multimap<JsonStage, JsonValue> load(Map<String, FileHandle> map) throws IOException {
  Multimap<JsonStage, JsonValue> m = new Multimap<JsonStage, JsonValue>();
  for (Map.Entry<String, FileHandle> entry : map.entrySet()) {
    JsonStage stage = null;
    if (entry.getKey().startsWith("block")) {
      stage = JsonStage.BLOCK;
    } else if (entry.getKey().startsWith("item")) {
      stage = JsonStage.ITEM;
    } else if (entry.getKey().startsWith("recipe")) {
      stage = JsonStage.RECIPE;
    } else {
      throw new CubesException("Invalid json file path \"" + entry.getKey() + "\"");
    }

    Reader reader = entry.getValue().reader();
    try {
      m.put(stage, Json.parse(reader));
    } finally {
      reader.close();
    }
  }
  return m;
}
 
Example 8
Source File: IOUtils.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts a SQL-Clob object into a String. If the Clob is larger than 2^31 characters, we cannot convert it. If
 * there are errors converting it, this method will log the cause and return null.
 *
 * @param clob the clob to be read as string.
 * @return the string or null in case of errors.
 */
public String readClob( final Clob clob ) throws IOException, SQLException {
  final long length = clob.length();
  if ( length > Integer.MAX_VALUE ) {
    logger.warn( "This CLOB contains more than 2^31 characters. We cannot handle that." );
    throw new IOException( "This CLOB contains more than 2^31 characters. We cannot handle that." );
  }

  final Reader inStream = clob.getCharacterStream();
  final MemoryStringWriter outStream = new MemoryStringWriter( (int) length, 65536 );
  try {
    IOUtils.getInstance().copyWriter( inStream, outStream );
  } finally {
    try {
      inStream.close();
    } catch ( IOException e ) {
      logger.warn( "Failed to close input stream. No worries, we will be alright anyway.", e );
    }
  }
  return outStream.toString();
}
 
Example 9
Source File: ForEachMapTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
  // create a SqlSessionFactory
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/foreach_map/mybatis-config.xml");
  sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  reader.close();

  // populate in-memory database
  SqlSession session = sqlSessionFactory.openSession();
  Connection conn = session.getConnection();
  reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/foreach_map/CreateDB.sql");
  ScriptRunner runner = new ScriptRunner(conn);
  runner.setLogWriter(null);
  runner.runScript(reader);
  reader.close();
  session.close();
}
 
Example 10
Source File: ProcessCleaner.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
private void printStackTrace(int pid) {
    try {
        ProcessBuilder pb = new ProcessBuilder(getJavaTool("jstack").getAbsolutePath(), "" + pid);
        pb.redirectErrorStream(true);
        Process p = pb.start();

        Reader r = new InputStreamReader(p.getInputStream());
        BufferedReader br = new BufferedReader(r);

        String line;
        while ((line = br.readLine()) != null) {
            System.err.println(line);
        }

        br.close();
        r.close();
    } catch (Exception e) {
        System.err.println("Cannot print stack trace of the process with pid " + pid);
    }
}
 
Example 11
Source File: LobStreamsTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private boolean compareClobReader2CharArray(
        char[] cArray,
        Reader charReader) throws Exception
{
    char[] clobChars = new char[cArray.length];

    int readChars = 0;
    int totalCharsRead = 0;

    do {
        readChars = charReader.read(clobChars, totalCharsRead, cArray.length - totalCharsRead);
        if (readChars != -1)
            totalCharsRead += readChars;
    } while (readChars != -1 && totalCharsRead < cArray.length);
    charReader.close();
    if (!java.util.Arrays.equals(cArray, clobChars))
        return false;

    return true;
}
 
Example 12
Source File: SuppressionDecorator.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param rawIn
 * @throws IOException
 */
private void processPackageList(@WillClose Reader rawIn) throws IOException {
    try (BufferedReader in = new BufferedReader(rawIn)) {
        String s;
        while ((s = in.readLine()) != null) {
            s = s.trim();
            if (s.length() == 0) {
                continue;
            }
            String packageName = s.substring(1).trim();
            if (s.charAt(0) == '+') {
                check.add(packageName);
                dontCheck.remove(packageName);
            } else if (s.charAt(0) == '-') {
                dontCheck.add(packageName);
                check.remove(packageName);
            } else {
                throw new IllegalArgumentException("Can't parse " + category + " filter line: " + s);
            }
        }
    } finally {
        rawIn.close();
    }
}
 
Example 13
Source File: FeignException.java    From feign with Apache License 2.0 5 votes vote down vote up
private static String getResponseBodyPreview(byte[] body, Charset charset) {
  try {
    Reader reader = new InputStreamReader(new ByteArrayInputStream(body), charset);
    CharBuffer result = CharBuffer.allocate(MAX_BODY_CHARS_LENGTH);

    reader.read(result);
    reader.close();
    ((Buffer) result).flip();
    return result.toString() + "... (" + body.length + " bytes)";
  } catch (IOException e) {
    return e.toString() + ", failed to parse response";
  }
}
 
Example 14
Source File: DSLTokenizedMappingFileTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseFileWithEscaptedBrackets() {
    String file = "[when]ATTRIBUTE \"{attr}\" IS IN \\[{list}\\]=Attribute( {attr} in ({list}) )";
    try {
        final Reader reader = new StringReader( file );
        this.file = new DSLTokenizedMappingFile();

        final boolean parsingResult = this.file.parseAndLoad( reader );
        reader.close();

        assertTrue(parsingResult, this.file.getErrors().toString());
        assertTrue( this.file.getErrors().isEmpty() );

        assertEquals( 1,
                      this.file.getMapping().getEntries().size() );

        DSLMappingEntry entry = (DSLMappingEntry) this.file.getMapping().getEntries().get( 0 );

        assertEquals( DSLMappingEntry.CONDITION,
                      entry.getSection() );
        assertEquals( DSLMappingEntry.EMPTY_METADATA,
                      entry.getMetaData() );
        
        assertEquals( lookbehind + "ATTRIBUTE\\s+\"(.*?)\"\\s+IS\\s+IN\\s+\\[(.*?)\\](?=\\W|$)",
                      entry.getKeyPattern().toString() );
        //Attribute( {attr} in ({list}) )
        assertEquals( "Attribute( {attr} in ({list}) )",
                      entry.getValuePattern() );

    } catch ( final IOException e ) {
        e.printStackTrace();
        fail( "Should not raise exception " );
    }

}
 
Example 15
Source File: POXMembershipsResponse.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public POXMembershipsResponse(Reader reader) {

        try {
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            parser.parse(new InputSource(reader), handler);
            reader.close();
        } catch (Exception e) {
            log.error("Failed to parse memberships xml.", e);
        }
    }
 
Example 16
Source File: CsrfGuardUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unconditionally close an <code>Reader</code>.
 * Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
 *
 * @param input A (possibly null) Reader to close
 */
public static void closeQuietly(Reader input) {
	if (input == null) {
		return;
	}

	try {
		input.close();
	} catch (IOException ioe) {
	}
}
 
Example 17
Source File: GroupTemplate.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Program loadScript(Resource res)
{

	Reader scriptReader  = null;
	try
	{
		scriptReader = res.openReader();
		Program program = engine.createProgram(res, scriptReader, Collections.EMPTY_MAP,
				System.getProperty("line.separator"), this);
		return program;

	}

	catch (BeetlException ex)
	{
		ErrorGrammarProgram ep = new ErrorGrammarProgram(res, this, System.getProperty("line.separator"));
		ex.pushResource(res);
		ep.setException(ex);
		return ep;
	}finally {
		if(scriptReader!=null) {
			try {
				scriptReader.close();
			} catch (IOException e) {
				
			}
		}
	}

}
 
Example 18
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSetPomModelReuse() throws IOException {
    String namespace = "org.kie.test";

    ReleaseId releaseId = KieServices.Factory.get().newReleaseId( namespace,
                                                                  "pomModelReuse",
                                                                  "1.0" );

    String pom = KieBuilderImpl.generatePomXml( releaseId );
    KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
    kfs.writePomXML( pom );

    //Create a KieBuilder instance
    KieBuilder kieBuilder1 = createKieBuilder( kfs );
    kieBuilder1.buildAll();

    //Get PomModel to re-use in second KieBuilder instance
    PomModel pomModel = ( (KieBuilderImpl) kieBuilder1 ).getPomModel();

    kfs.writePomXML( pom );

    //Create another KieBuilder instance with the same KieFileSystem, setting PomModel
    KieBuilder kieBuilder2 = createKieBuilder( kfs );
    ( (KieBuilderImpl) kieBuilder2 ).setPomModel( pomModel );
    kieBuilder2.buildAll();

    //Read pom.xml from first KieBuilder's KieModule
    InternalKieModule kieModule1 = (InternalKieModule) ( (KieBuilderImpl) kieBuilder1 ).getKieModuleIgnoringErrors();
    final Reader reader1 = kieModule1.getResource( "META-INF/maven/org.kie.test/pomModelReuse/pom.xml" ).getReader();
    int charCode;
    String readPom1 = "";
    while ( ( charCode = reader1.read() ) != -1 ) {
        readPom1 = readPom1 + (char) charCode;
    }
    reader1.close();

    assertEquals( pom,
                  readPom1 );

    //Read pom.xml from second KieBuilder's KieModule
    InternalKieModule kieModule2 = (InternalKieModule) ( (KieBuilderImpl) kieBuilder2 ).getKieModuleIgnoringErrors();
    final Reader reader2 = kieModule2.getResource( "META-INF/maven/org.kie.test/pomModelReuse/pom.xml" ).getReader();
    String readPom2 = "";
    while ( ( charCode = reader2.read() ) != -1 ) {
        readPom2 = readPom2 + (char) charCode;
    }
    reader1.close();

    assertEquals( pom,
                  readPom2 );
}
 
Example 19
Source File: AutodiscoverTest.java    From mybaties with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/autodiscover/MapperConfig.xml");
  sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  reader.close();
}
 
Example 20
Source File: IOUtils.java    From dubbox with Apache License 2.0 2 votes vote down vote up
/**
 * write string.
 * 
 * @param writer Writer instance.
 * @param string String.
 * @throws IOException
 */
public static long write(Writer writer, String string) throws IOException
{
	Reader reader = new StringReader(string);
	try{ return write(reader, writer); }finally{ reader.close(); }
}