List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:edu.uci.ics.jung.io.GraphMLReader.java
protected void parse(Reader reader) throws IOException { try {//from w w w . j ava 2 s.c om saxp.parse(new InputSource(reader), this); reader.close(); } catch (SAXException saxe) { throw new IOException(saxe.getMessage()); } }
From source file:org.jahia.loganalyzer.internal.JahiaLogAnalyzerImpl.java
@Override public boolean analyze(java.awt.Component uiComponent, Task task) throws IOException { File inputFile = logParserConfiguration.getInputFile(); if (!inputFile.exists()) { log.warn("Couldn't find file " + inputFile); return true; }//from w w w. java 2 s . c o m String jvmIdentifier = "jvm"; long totalBytesToProcess = 0; if (inputFile.isDirectory()) { SortedSet<File> sortedFiles = new TreeSet<File>(FileUtils.listFiles(inputFile, null, true)); for (File file : sortedFiles) { if (file.isFile()) { totalBytesToProcess += file.length(); } } if (!logParserConfiguration.getOutputDirectory().exists()) { createOutputDirectory(logParserConfiguration); } List<ProcessedLogFile> processedLogFiles = getProcessedLogFiles(); LogParserImpl logParser = new LogParserImpl(); logParser.setElasticSearchService(elasticSearchService); logParser.setLogParserConfiguration(logParserConfiguration); long totalBytesRead = 0; for (File file : sortedFiles) { if (file.getCanonicalPath() .startsWith(logParserConfiguration.getOutputDirectory().getCanonicalPath())) { continue; } ProcessedLogFile processedLogFile = new ProcessedLogFile(logParserConfiguration.getInputFile(), file); if (processedLogFiles.contains(processedLogFile)) { log.info("File " + file + " already parsed previously, skipping"); continue; } String filePath = file.getPath(); int jvmIdentifierPos = filePath.indexOf("jvm-"); if (jvmIdentifierPos >= 0) { int fileSeparatorPos = filePath.indexOf(File.separator, jvmIdentifierPos); if (fileSeparatorPos >= 0) { jvmIdentifier = filePath.substring(jvmIdentifierPos + "jvm-".length(), fileSeparatorPos); } else { jvmIdentifier = filePath.substring(jvmIdentifierPos + "jvm-".length()); } } Reader reader = getFileReader(uiComponent, file, new TotalBytesMonitor(task, totalBytesToProcess, totalBytesRead)); log.info("Parsing file " + file + "..."); processedLogFile = logParser.parse(reader, file, jvmIdentifier, processedLogFile.getLastParsedTimestamp()); log.info("Parsing of file " + file + " completed."); reader.close(); totalBytesRead += file.length(); processedLogFiles.add(processedLogFile); } logParser.stop(); saveProcessedLogFiles(processedLogFiles); } else { long totalBytesRead = 0; File file = logParserConfiguration.getInputFile(); if (!logParserConfiguration.getOutputDirectory().exists()) { createOutputDirectory(logParserConfiguration); } List<ProcessedLogFile> processedLogFiles = getProcessedLogFiles(); ProcessedLogFile processedLogFile = new ProcessedLogFile( logParserConfiguration.getInputFile().getParentFile(), file); if (processedLogFiles.contains(processedLogFile)) { // we instantiate the log parser just to make sure the embedded ElasticSearch is started. LogParserImpl logParser = new LogParserImpl(); logParser.setElasticSearchService(elasticSearchService); logParser.setLogParserConfiguration(logParserConfiguration); logParser.stop(); } else { LogParserImpl logParser = new LogParserImpl(); logParser.setElasticSearchService(elasticSearchService); logParser.setLogParserConfiguration(logParserConfiguration); Reader reader = getFileReader(uiComponent, file, new TotalBytesMonitor(task, totalBytesToProcess, totalBytesRead)); log.info("Parsing file " + file + "..."); processedLogFile = logParser.parse(reader, file, jvmIdentifier, processedLogFile.getLastParsedTimestamp()); log.info("Parsing of file " + file + " completed."); reader.close(); totalBytesRead += file.length(); logParser.stop(); processedLogFiles.add(processedLogFile); saveProcessedLogFiles(processedLogFiles); } } return true; }
From source file:at.general.solutions.android.ical.remote.HttpDownloadThread.java
@Override public void run() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(params, USER_AGENT); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient client = new DefaultHttpClient(cm, params); if (useAuthentication) { client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(remoteUsername, remotePassword)); }/* ww w . ja v a2 s . c o m*/ HttpGet get = new HttpGet(remoteUrl); try { super.sendInitMessage(R.string.downloading); HttpResponse response = client.execute(get); Log.d(LOG_TAG, response.getStatusLine().getReasonPhrase() + " " + isGoodResponse(response.getStatusLine().getStatusCode())); if (isGoodResponse(response.getStatusLine().getStatusCode())) { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); if (instream == null) { super.sendErrorMessage(R.string.couldnotConnectToRemoteserver); return; } if (entity.getContentLength() > Integer.MAX_VALUE) { super.sendErrorMessage(R.string.remoteFileTooLarge); return; } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = encoding; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); super.sendMaximumMessage(i); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); super.sendProgressMessage(buffer.length()); } } finally { reader.close(); } super.sendFinishedMessage(buffer.toString()); } else { int errorMsg = R.string.couldnotConnectToRemoteserver; if (isAccessDenied(response.getStatusLine().getStatusCode())) { errorMsg = R.string.accessDenied; } else if (isFileNotFound(response.getStatusLine().getStatusCode())) { errorMsg = R.string.remoteFileNotFound; } super.sendErrorMessage(errorMsg); } } catch (UnknownHostException e) { super.sendErrorMessage(R.string.unknownHostException, e); Log.e(LOG_TAG, "Error occured", e); } catch (Throwable e) { super.sendErrorMessage(R.string.couldnotConnectToRemoteserver, e); Log.e(LOG_TAG, "Error occured", e); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.lucidtechnics.blackboard.util.JavascriptingUtil.java
public Script compileScript(String _scriptResource) { Reader reader = null; try {//www . ja va 2s .c o m if (getScriptResourceMap().containsKey(_scriptResource) == false) { reader = new InputStreamReader(findScript(_scriptResource)); Script script = Context.getCurrentContext().compileReader(reader, _scriptResource, 0, null); synchronized (getScriptResourceMap()) { getScriptResourceMap().put(_scriptResource, script); } } } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } return getScriptResourceMap().get(_scriptResource); }
From source file:com.cheesmo.nzb.client.NNTPConnection.java
public boolean downloadSegment(String group, String string, String downloadName) { try {//from w ww. j a v a 2 s . com tryConnect(); client.selectNewsgroup(group); Reader reader = client.retrieveArticleBody(string); if (reader != null) { FileOutputStream fos = new FileOutputStream( config.getCacheDir() + java.io.File.separator + downloadName); char[] buffer = new char[512]; int charsRead = reader.read(buffer); while (charsRead > -1 && client.isConnected()) { fos.write(Charset.forName("ISO-8859-1").encode(CharBuffer.wrap(buffer, 0, charsRead)).array()); charsRead = reader.read(buffer); } if (!client.isConnected()) { System.out.println("Client disconnected."); } reader.close(); fos.flush(); fos.close(); return true; } else { //System.out.println("Problem retrieving " + string); } } catch (SocketException e) { System.out.println("Client disconnected."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }
From source file:de.tudarmstadt.ukp.dkpro.tc.weka.util.WekaUtils.java
/** * Read instances from uncompressed or compressed arff files. Compression is determined by * filename suffix. For bz2 files, it is expected that the first two bytes mark the compression * types (BZ) - thus, the first bytes of the stream are skipped. <br> * For arff files with single-label outcome, the class attribute is expected at the end of the * attribute set. For arff files with multi-label outcome, the class attribute is expected at * the beginning of the attribute set; additionally the number of class labels must be specified * in the relation tag behind a "-C" argument, e.g. "-C 3". * * @param instancesFile// w w w.jav a 2s.c o m * arff File * @param multiLabel * whether this arff file contains single- or multi-label outcome * @return instances with class attribute set * @throws FileNotFoundException * @throws IOException */ public static Instances getInstances(File instancesFile, boolean multiLabel) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(instancesFile); BufferedInputStream bufStr = new BufferedInputStream(fis); InputStream underlyingStream = null; if (instancesFile.getName().endsWith(".gz")) { underlyingStream = new GZIPInputStream(bufStr); } else if (instancesFile.getName().endsWith(".bz2")) { // skip bzip2 prefix that we added manually fis.read(); fis.read(); underlyingStream = new CBZip2InputStream(bufStr); } else { underlyingStream = bufStr; } Reader reader = new InputStreamReader(underlyingStream, "UTF-8"); Instances trainData = new Instances(reader); if (multiLabel) { String relationTag = trainData.relationName(); // for multi-label classification, class labels are expected at beginning of attribute // set and their number must be specified with the -C parameter in the relation tag Matcher m = Pattern.compile("-C\\s\\d+").matcher(relationTag); m.find(); trainData.setClassIndex(Integer.parseInt(m.group().split("-C ")[1])); } else { // for single-label classification, class label expected as last attribute trainData.setClassIndex(trainData.numAttributes() - 1); } reader.close(); return trainData; }
From source file:com.icesoft.applications.faces.auctionMonitor.beans.ReadmeBean.java
/** * Method to load a default readme file (at readme.html) The file will be * read in and converted to a displayable string * * @return boolean true on successful read *//*from w w w. java 2 s . co m*/ private boolean loadDefaultReadmeFile() { try { Reader readmeReader = new InputStreamReader(this.getClass().getClassLoader() .getResourceAsStream("com/icesoft/applications/faces/auctionMonitor/readme.html")); StringWriter readmeWriter = new StringWriter(); char[] buf = new char[2000]; int len; try { while ((len = readmeReader.read(buf)) > -1) { readmeWriter.write(buf, 0, len); } } catch (IOException e) { if (log.isErrorEnabled()) { log.error("Something went wrong while parsing the readme file, likely because of " + e); } } // clean up the stream reader readmeReader.close(); this.readmeText = readmeWriter.toString(); // clean up the writer readmeWriter.close(); return true; } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("General error while attempting to load the readme file, cause may be " + e); } } return false; }
From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java
protected String readFileFromNode(Node fileNode) throws IOException, ValueFormatException, PathNotFoundException, RepositoryException { CharArrayWriter writer = null; InputStream in = null;//w ww.j a v a 2 s .co m Reader reader = null; try { in = fileNode.getNode(JcrConstants.JCR_CONTENT).getProperty(JcrConstants.JCR_DATA).getStream(); writer = new CharArrayWriter(); reader = new InputStreamReader(in); char[] buffer = new char[8]; int c = 0; while ((c = reader.read(buffer)) != -1) { writer.write(buffer, 0, c); } return new String(writer.toCharArray()); } catch (IOException ioex) { return null; } finally { if (reader != null) { reader.close(); } if (in != null) { in.close(); } if (writer != null) { writer.close(); } } }
From source file:org.apache.manifoldcf.elasticsearch.MCFAuthorizerUtils.java
/** Get access tokens given a username */ protected static List<String> getAccessTokens(Map<String, String> domainMap) throws MCFAuthorizerException { try {/*from www .j av a 2s . c o m*/ StringBuilder urlBuffer = new StringBuilder(AUTHORITY_BASE_URL); urlBuffer.append("/UserACLs"); int i = 0; for (String domain : domainMap.keySet()) { if (i == 0) urlBuffer.append("?"); else urlBuffer.append("&"); // For backwards compatibility, handle the singleton case specially if (domainMap.size() == 1 && domain.length() == 0) { urlBuffer.append("username=").append(URLEncoder.encode(domainMap.get(domain), "utf-8")); } else { urlBuffer.append("username_").append(Integer.toString(i)).append("=") .append(URLEncoder.encode(domainMap.get(domain), "utf-8")).append("&").append("domain_") .append(Integer.toString(i)).append("=").append(URLEncoder.encode(domain, "utf-8")); } i++; } String theURL = urlBuffer.toString(); HttpGet method = new HttpGet(theURL); try { HttpResponse httpResponse = httpClient.execute(method); int rval = httpResponse.getStatusLine().getStatusCode(); if (rval != 200) { String response = EntityUtils.toString(httpResponse.getEntity(), "utf-8"); throw new MCFAuthorizerException( "Couldn't fetch user's access tokens from ManifoldCF authority service: " + Integer.toString(rval) + "; " + response); } InputStream is = httpResponse.getEntity().getContent(); try { String charSet = ContentType.getOrDefault(httpResponse.getEntity()).getCharset().toString(); if (charSet == null) charSet = "utf-8"; Reader r = new InputStreamReader(is, charSet); try { BufferedReader br = new BufferedReader(r); try { // Read the tokens, one line at a time. If any authorities are down, we have no current way to note that, but someday we will. List<String> tokenList = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; if (line.startsWith("TOKEN:")) { tokenList.add(line.substring("TOKEN:".length())); log.info(line); } else { // It probably says something about the state of the authority(s) involved, so log it log.info("Saw authority response " + line); } } return tokenList; } finally { br.close(); } } finally { r.close(); } } finally { is.close(); } } finally { method.abort(); } } catch (IOException e) { throw new MCFAuthorizerException("IO exception: " + e.getMessage(), e); } }
From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java
private EmailTemplate generateEmail(ProjectPojo projectInfo, EmailContentMap map) { Reader reader = null; try {//from w w w .j a v a 2 s. c om reader = new InputStreamReader(new FileInputStream(templateFileLocation)); } catch (FileNotFoundException e1) { log.error(e1.getMessage()); } VelocityContext velContext = initializeVelocityContext(projectInfo, map); EmailTemplate emailTemplate = evaluateVelocityContext(velContext, reader); try { reader.close(); } catch (IOException e) { log.error("Error closing reader", e); } return emailTemplate; }