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

The following examples show how to use java.io.Reader#close() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mybatis   File: PrimitivesTest.java    License: 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
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 3
@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 4
Source Project: Cubes   File: JsonLoader.java    License: 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 5
/**
 * 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 6
Source Project: mybaties   File: ForEachMapTest.java    License: 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 7
Source Project: gemfirexd-oss   File: LobStreamsTest.java    License: 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 8
/**
 * @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 9
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 10
@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 11
Source Project: frpMgr   File: CommandUtils.java    License: 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 12
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 13
/**
 * 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 14
Source Project: feign   File: FeignException.java    License: 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 15
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
@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 17
Source Project: tutorials   File: JavaReaderToXUnitTest.java    License: MIT License 5 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 18
Source Project: kogito-runtimes   File: KieBuilderTest.java    License: 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 Project: mybaties   File: AutodiscoverTest.java    License: 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 Project: dubbox   File: IOUtils.java    License: 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(); }
}