List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:gov.nih.nci.caintegrator.application.analysis.grid.comparativemarker.ComparativeMarkerSelectionGridRunner.java
private void postUpload(ComparativeMarkerSelMAGESvcContextClient analysisClient, ComparativeMarkerSelectionParameters parameters, File gctFile, File clsFile) throws IOException, ConnectionException { TransferServiceContextReference up = analysisClient.submitData(parameters.createParameterList()); TransferServiceContextClient tClient = new TransferServiceContextClient(up.getEndpointReference()); BufferedInputStream bis = null; Set<File> fileSet = new HashSet<File>(); fileSet.add(clsFile);/*from ww w .ja v a2 s . co m*/ fileSet.add(gctFile); File zipFile = new File(ZipUtils.writeZipFile(fileSet)); try { long size = zipFile.length(); bis = new BufferedInputStream(new FileInputStream(zipFile)); TransferClientHelper.putData(bis, size, tClient.getDataTransferDescriptor()); } catch (Exception e) { // For some reason TransferClientHelper throws "Exception", going to rethrow a connection exception. throw new ConnectionException("Unable to transfer data to the server.", e); } finally { if (bis != null) { bis.close(); } FileUtils.deleteQuietly(zipFile); } tClient.setStatus(Status.Staged); }
From source file:easyshop.downloadhelper.HttpPageGetter.java
public HttpPage getHttpPage(PageRef thisRef, HttpClient client, String charSet) { client.getParams().setParameter(HttpMethodParams.USER_AGENT, HTTP_USER_AGENT); //?IE String urlStr = thisRef.getUrlStr(); // try { // urlStr=new String(urlStr.getBytes("utf-8"),"gb2312"); // } catch (UnsupportedEncodingException e1) { // // log error here // log.error(e1.getMessage()); // }// w w w . j a va 2 s . c o m // System.out.println(urlStr); // get.setRequestHeader("connection","keep-alive"); GetMethod get = null; try { get = new GetMethod(urlStr); get.setFollowRedirects(true); //???? long startTime = System.currentTimeMillis(); int iGetResultCode = client.executeMethod(get); Header[] rheaders = get.getRequestHeaders(); Header[] headers = get.getResponseHeaders(); boolean is11 = get.isHttp11(); boolean redirect = get.getFollowRedirects(); if (get.getResponseContentLength() >= 2024000) { log.info("content is too large, can't download!"); ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(-1, urlStr, null, null, conRes, null); } BufferedInputStream remoteBIS = new BufferedInputStream(get.getResponseBodyAsStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buf = new byte[1024]; int bytesRead = 0; while (bytesRead >= 0) { baos.write(buf, 0, bytesRead); bytesRead = remoteBIS.read(buf); } remoteBIS.close(); byte[] content = baos.toByteArray(); // byte[] content=get.getResponseBody(); long timeTaken = System.currentTimeMillis() - startTime; if (timeTaken < 100) timeTaken = 500; int bytesPerSec = (int) ((double) content.length / ((double) timeTaken / 1000.0)); // log.info("Downloaded " + content.length + " bytes, " + bytesPerSec + " bytes/sec"); // log.info("urlstr:"+urlStr); ConnResponse conRes = new ConnResponse(get.getResponseHeader("Content-type").getValue(), null, 0, 0, get.getStatusCode()); String charset = conRes.getCharSet(); if (charset == null) { String cc = new String(content); if (cc.indexOf("content=\"text/html; charset=gb2312") > 0) charset = "gb2312"; else if (cc.indexOf("content=\"text/html; charset=utf-8") > 0) charset = "utf-8"; else if (cc.indexOf("content=\"text/html; charset=gbk") > 0) charset = "gbk"; } return new HttpPage(urlStr, content, conRes, charset); } catch (IOException ioe) { log.warn("Caught IO Exception: " + ioe.getMessage(), ioe); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(-1, urlStr, null, null, conRes, null); } catch (Exception e) { log.warn("Caught Exception: " + e.getMessage(), e); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(-1, urlStr, null, null, conRes, null); } finally { get.releaseConnection(); } /**/ }
From source file:Strings.java
/** Process one file */ protected void process(String fileName, InputStream inStream) { try {/*from ww w.ja v a2 s . c o m*/ int i; char ch; // This line alone cuts the runtime by about 66% on large files. BufferedInputStream is = new BufferedInputStream(inStream); StringBuffer sb = new StringBuffer(); // Read a byte, cast it to char, check if part of printable string. while ((i = is.read()) != -1) { ch = (char) i; if (isStringChar(ch) || (sb.length() > 0 && ch == ' ')) // If so, build up string. sb.append(ch); else { // if not, see if anything to output. if (sb.length() == 0) continue; if (sb.length() >= minLength) { report(fileName, sb); } sb.setLength(0); } } is.close(); } catch (IOException e) { System.out.println("IOException: " + e); } }
From source file:com.twitterdev.rdio.app.RdioApp.java
private void next(final boolean manualPlay) { if (player != null) { player.stop();/*from w w w. j av a 2 s . com*/ player.release(); player = null; } final Track track = trackQueue.poll(); if (trackQueue.size() < 3) { Log.i(TAG, "Track queue depleted, loading more tracks"); LoadMoreTracks(); } if (track == null) { Log.e(TAG, "Track is null! Size of queue: " + trackQueue.size()); return; } // Load the next track in the background and prep the player (to start buffering) // Do this in a bkg thread so it doesn't block the main thread in .prepare() AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() { @Override protected Track doInBackground(Track... params) { Track track = params[0]; final String trackName = track.artistName; final String artist = track.trackName; try { player = rdio.getPlayerForTrack(track.key, null, manualPlay); player.prepare(); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { next(false); } }); player.start(); new getSearch().execute(track.trackName); runOnUiThread(new Runnable() { @Override public void run() { TextView a = (TextView) findViewById(R.id.artist); //a.setText(artist); TextView t = (TextView) findViewById(R.id.track); //t.setText(trackName); } }); } catch (Exception e) { Log.e("Test", "Exception " + e); } return track; } @Override protected void onPostExecute(Track track) { updatePlayPause(true); } }; task.execute(track); // Fetch album art in the background and then update the UI on the main thread AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() { @Override protected Bitmap doInBackground(Track... params) { Track track = params[0]; try { String artworkUrl = track.albumArt.replace("square-200", "square-600"); Log.i(TAG, "Downloading album art: " + artworkUrl); Bitmap bm = null; try { URL aURL = new URL(artworkUrl); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); } catch (IOException e) { Log.e(TAG, "Error getting bitmap", e); } return bm; } catch (Exception e) { Log.e(TAG, "Error downloading artwork", e); return null; } } @Override protected void onPostExecute(Bitmap artwork) { if (artwork != null) { int imageWidth = artwork.getWidth(); int imageHeight = artwork.getHeight(); DisplayMetrics dimension = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dimension); int newWidth = dimension.widthPixels; float scaleFactor = (float) newWidth / (float) imageWidth; int newHeight = (int) (imageHeight * scaleFactor); artwork = Bitmap.createScaledBitmap(artwork, newWidth, newHeight, true); //albumArt.setImageBitmap(bitmap); albumArt.setAdjustViewBounds(true); albumArt.setImageBitmap(artwork); } else albumArt.setImageResource(R.drawable.blank_album_art); } }; artworkTask.execute(track); //Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName, track.albumName, track.artistName), Toast.LENGTH_LONG).show(); }
From source file:com.greenline.guahao.biz.manager.storage.impl.DefaultStorageManagerImpl.java
/** * ?/*w ww. j av a2 s . c o m*/ * * @param in * @param path * @return */ public StoreResult create(InputStream inputStream, String path) { StoreResult ret = new StoreResult(); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(inputStream); out = new BufferedOutputStream(new FileOutputStream(rootDirectory + path)); ret.setPath(path); int len = 0; byte[] bytes = new byte[DEFAULT_BUFFER_SIZE]; while (-1 != (len = in.read(bytes))) { out.write(bytes, 0, len); } } catch (Exception e) { logger.error(".", e); ret.setResult(ResultEnum.ERROR); ret.setMessage(e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } return ret; }
From source file:gov.nih.nci.caintegrator.application.analysis.grid.gistic.GisticGridRunner.java
private void postUpload(GisticContextClient analysisClient, GisticParameters parameters, File segmentFile, File markersFile, File cnvFile) throws IOException, ConnectionException { TransferServiceContextReference up = analysisClient.submitData(parameters.createParameterList(), parameters.createGenomeBuild()); TransferServiceContextClient tClient = new TransferServiceContextClient(up.getEndpointReference()); BufferedInputStream bis = null; Set<File> fileSet = createGisticInputFileSet(segmentFile, markersFile, cnvFile); File zipFile = new File(ZipUtils.writeZipFile(fileSet)); try {// w w w .j a v a 2s .c om long size = zipFile.length(); bis = new BufferedInputStream(new FileInputStream(zipFile)); TransferClientHelper.putData(bis, size, tClient.getDataTransferDescriptor()); } catch (Exception e) { // For some reason TransferClientHelper throws "Exception", going to rethrow a connection exception. throw new ConnectionException("Unable to transfer data to the server.", e); } finally { if (bis != null) { bis.close(); } for (File file : fileSet) { FileUtils.deleteQuietly(file); } FileUtils.deleteQuietly(zipFile); } tClient.setStatus(Status.Staged); }
From source file:org.dswarm.graph.gdm.test.BaseGDMResourceTest.java
protected void writeGDMToDBInternal(final ObjectNode metadata, final String fileName) throws java.io.IOException { LOG.debug("start writing GDM statements for GDM resource at {} DB", dbType); final URL fileURL = Resources.getResource(fileName); final ByteSource byteSource = Resources.asByteSource(fileURL); final InputStream is = byteSource.openStream(); final BufferedInputStream bis = new BufferedInputStream(is, 1024); final String requestJsonString = objectMapper.writeValueAsString(metadata); // Construct a MultiPart with two body parts final MultiPart multiPart = new MultiPart(); multiPart.bodyPart(new BodyPart(requestJsonString, MediaType.APPLICATION_JSON_TYPE)) .bodyPart(new BodyPart(bis, MediaType.APPLICATION_OCTET_STREAM_TYPE)); // POST the request final ClientResponse response = target().path("/put").type("multipart/mixed").post(ClientResponse.class, multiPart);/* www . j ava2 s .c o m*/ Assert.assertEquals("expected 200", 200, response.getStatus()); multiPart.close(); bis.close(); is.close(); LOG.debug("finished writing GDM statements for GDM resource at {} DB", dbType); }
From source file:com.autoupdateapk.AutoUpdateApk.java
private String MD5Hex(String filename) { final int BUFFER_SIZE = 8192; byte[] buf = new byte[BUFFER_SIZE]; int length;/*from w ww .j a v a2 s .c om*/ try { FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis); MessageDigest md = java.security.MessageDigest.getInstance("MD5"); while ((length = bis.read(buf)) != -1) { md.update(buf, 0, length); } bis.close(); byte[] array = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } Log_v(TAG, "md5sum: " + sb.toString()); return sb.toString(); } catch (Exception e) { Log_e(TAG, e.getMessage()); } return "md5bad"; }
From source file:net.sf.xmm.moviemanager.http.HttpUtil.java
public byte[] readDataToByteArray(URL url) throws Exception { byte[] data = null; if (!isSetup()) setup();//from www . ja va2 s .co m GetMethod method = new GetMethod(url.toString()); try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { BufferedInputStream inputStream = new BufferedInputStream(method.getResponseBodyAsStream()); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(inputStream.available()); byte[] tmpBuf = new byte[1000]; int bytesRead; while ((bytesRead = inputStream.read(tmpBuf, 0, tmpBuf.length)) != -1) { byteStream.write(tmpBuf, 0, bytesRead); } inputStream.close(); data = byteStream.toByteArray(); } else { log.warn("HttpStatus statusCode:" + statusCode); log.warn("HttpStatus.SC_OK:" + HttpStatus.SC_OK); } } catch (Exception e) { log.warn("Exception:" + e.getMessage(), e); throw new Exception(e.getMessage()); } finally { method.releaseConnection(); } return data; }
From source file:com.ibm.jaql.lang.expr.system.RFn.java
@Override public JsonValue eval(Context context) throws Exception { try {//from ww w . j a v a 2 s . c o m if (proc == null) { init(context); } JsonString fn = (JsonString) exprs[INDEX_FN].eval(context); if (fn == null) { throw new IllegalArgumentException("R(init, fn, ...): R function required"); } binary = ((JsonBool) exprs[INDEX_BINARY].eval(context)).get(); JsonValue tmp = exprs[INDEX_OUT_SCHEMA].eval(context); if (tmp != null) { if (!(tmp instanceof JsonSchema)) throw new IllegalArgumentException("Invalid outSchema."); schema = ((JsonSchema) tmp).get(); } else if (binary) { schema = SchemaFactory.binarySchema(); } if (LOG.isDebugEnabled()) LOG.debug("Initialized outSchema to: " + schema); String sep = ""; File rOut = null; if (binary) { String tmpFileName = RUtil.getTempFileName(); rOut = new File(tmpFileName); tmpFileName = rOut.getAbsolutePath(); tmpFileName = tmpFileName.replace('\\', '/'); rOut.deleteOnExit(); stdin.print("cat(toBinary(file='"); stdin.print(tmpFileName); stdin.print("',"); } else { stdin.print("cat(toJSON("); } stdin.print("("); stdin.print(fn); stdin.print(")"); tmp = exprs[INDEX_ARGS].eval(context); if (tmp != null) // we have args { if (!(tmp instanceof JsonArray)) { throw new IllegalArgumentException( "Arguments to function " + fn + " must be enclosed as an array."); } JsonArray args = (JsonArray) tmp; tmp = exprs[INDEX_IN_SCHEMA].eval(context); JsonArray argSchema = null; if (tmp != null) { if (!(tmp instanceof JsonArray)) { throw new IllegalArgumentException( "Schema for arguments of function " + fn + " must be enclosed in an array"); } argSchema = (JsonArray) tmp; } Schema inferred = exprs[INDEX_ARGS].getSchema(); stdin.print("("); for (int i = 0; i < args.count(); i++) { JsonValue value = args.get(i); Schema elemSchema = null; if (argSchema != null) { tmp = argSchema.get(i); if (!(tmp instanceof JsonSchema)) { throw new IllegalArgumentException("Argument schema at index " + i + " not an instance of " + JsonSchema.class.getCanonicalName()); } elemSchema = ((JsonSchema) tmp).get(); } else { elemSchema = inferred.element(new JsonLong(i)); } stdin.print(sep); processFnArgument(context, value, elemSchema); sep = ","; } stdin.print(")"); } stdin.println("),'\n')"); stdin.flush(); // parser.ReInit(stdout); // TODO: we can read directly from the stdout stream, but error reporting is not so good... String s = stdout.readLine(); if (s == null) { throw new RuntimeException("unexpected EOF from R"); } if (binary) { byte[] buffer = new byte[4096]; ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(rOut), 4096); int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); rOut.delete(); byte[] rBin = out.toByteArray(); //System.err.println("Output: " + new String(rBin)); return new JsonBinary(rBin); } else { parser.ReInit(new StringReader(s)); try { JsonValue result = parser.JsonVal(); return result; } catch (Exception e) { System.err.println("Bad JSON from R:\n" + s); throw e; } } } catch (Throwable e) { if (error == null) { error = e; } if (stdin != null) { try { stdin.close(); } catch (Throwable t) { } stdin = null; } if (stdout != null) { try { stdout.close(); } catch (Throwable t) { } stdout = null; } if (proc != null) { try { proc.destroy(); } catch (Throwable t) { } proc = null; } if (error instanceof Exception) { throw (Exception) error; } throw new UndeclaredThrowableException(error); } }