List of usage examples for java.io BufferedOutputStream write
@Override public synchronized void write(int b) throws IOException
From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHandler.java
/** * @param is//from w ww. j a va2s .co m * @param rootPath * @param fileName */ @Override public void createNewTmpFile(InputStream is, int uid, String dir, String fileName, String realFileName) { File path = new File(getAbsolutePath(FOLDER_TMP_FOR_ATTACHMENT_FILES) + separator() + Database.getDomainName() + separator() + uid + separator() + dir); if (!path.exists()) { try { path.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + path); } } // ?START try { String filepath = path + separator() + fileName; File file = new File(filepath); if (!file.createNewFile()) { throw new RuntimeException("createNewFile error"); } int c; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is, 1024 * 1024); bos = new BufferedOutputStream(new FileOutputStream(filepath), 1024 * 1024); while ((c = bis.read()) != -1) { bos.write(c); } } catch (IOException e) { logger.error("ALDefaultStorageHandler.createNewTmpFile", e); } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(bos); } // ?END PrintWriter w = null; try { w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filepath + EXT_FILENAME), "UTF-8")); w.println(realFileName); } catch (IOException e) { logger.error("ALDefaultStorageHandler.createNewTmpFile", e); } finally { if (w != null) { try { w.flush(); w.close(); } catch (Throwable e) { // ignore } } } } catch (FileNotFoundException e) { logger.error("ALDefaultStorageHandler.createNewTmpFile", e); } catch (IOException e) { logger.error("ALDefaultStorageHandler.createNewTmpFile", e); } }
From source file:com.ichi2.libanki.sync.HttpSyncer.java
public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData, Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException { File tmpFileBuffer = null;/*from w w w . j ava 2 s . c o m*/ try { String bdry = "--" + BOUNDARY; StringWriter buf = new StringWriter(); // post vars mPostVars.put("c", comp != 0 ? 1 : 0); for (String key : mPostVars.keySet()) { buf.write(bdry + "\r\n"); buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key, mPostVars.get(key))); } tmpFileBuffer = File.createTempFile("syncer", ".tmp", new File(AnkiDroidApp.getCacheStorageDirectory())); FileOutputStream fos = new FileOutputStream(tmpFileBuffer); BufferedOutputStream bos = new BufferedOutputStream(fos); GZIPOutputStream tgt; // payload as raw data or json if (fobj != null) { // header buf.write(bdry + "\r\n"); buf.write( "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n"); buf.close(); bos.write(buf.toString().getBytes("UTF-8")); // write file into buffer, optionally compressing int len; BufferedInputStream bfobj = new BufferedInputStream(fobj); byte[] chunk = new byte[65536]; if (comp != 0) { tgt = new GZIPOutputStream(bos); while ((len = bfobj.read(chunk)) >= 0) { tgt.write(chunk, 0, len); } tgt.close(); bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true)); } else { while ((len = bfobj.read(chunk)) >= 0) { bos.write(chunk, 0, len); } } bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8")); } else { buf.close(); bos.write(buf.toString().getBytes("UTF-8")); } bos.flush(); bos.close(); // connection headers String url = Consts.SYNC_BASE; if (method.equals("register")) { url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password=" + registerData.getString("p"); } else if (method.startsWith("upgrade")) { url = url + method; } else { url = syncURL() + method; } HttpPost httpPost = new HttpPost(url); HttpEntity entity = new ProgressByteEntity(tmpFileBuffer); // body httpPost.setEntity(entity); httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY); // HttpParams HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + VersionUtils.getPkgVersionName()); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT); // Registry SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry); if (cancelCallback != null) { cancelCallback.setConnectionManager(cm); } try { HttpClient httpClient = new DefaultHttpClient(cm, params); HttpResponse httpResponse = httpClient.execute(httpPost); // we assume badAuthRaises flag from Anki Desktop always False // so just throw new RuntimeException if response code not 200 or 403 assertOk(httpResponse); return httpResponse; } catch (SSLException e) { Timber.e(e, "SSLException while building HttpClient"); throw new RuntimeException("SSLException while building HttpClient"); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { Timber.e(e, "BasicHttpSyncer.sync: IOException"); throw new RuntimeException(e); } catch (JSONException e) { throw new RuntimeException(e); } finally { if (tmpFileBuffer != null && tmpFileBuffer.exists()) { tmpFileBuffer.delete(); } } }
From source file:website.openeng.libanki.sync.HttpSyncer.java
public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData, Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException { File tmpFileBuffer = null;//www . j a v a 2s .c om try { String bdry = "--" + BOUNDARY; StringWriter buf = new StringWriter(); // post vars mPostVars.put("c", comp != 0 ? 1 : 0); for (String key : mPostVars.keySet()) { buf.write(bdry + "\r\n"); buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key, mPostVars.get(key))); } tmpFileBuffer = File.createTempFile("syncer", ".tmp", new File(KanjiDroidApp.getCacheStorageDirectory())); FileOutputStream fos = new FileOutputStream(tmpFileBuffer); BufferedOutputStream bos = new BufferedOutputStream(fos); GZIPOutputStream tgt; // payload as raw data or json if (fobj != null) { // header buf.write(bdry + "\r\n"); buf.write( "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n"); buf.close(); bos.write(buf.toString().getBytes("UTF-8")); // write file into buffer, optionally compressing int len; BufferedInputStream bfobj = new BufferedInputStream(fobj); byte[] chunk = new byte[65536]; if (comp != 0) { tgt = new GZIPOutputStream(bos); while ((len = bfobj.read(chunk)) >= 0) { tgt.write(chunk, 0, len); } tgt.close(); bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true)); } else { while ((len = bfobj.read(chunk)) >= 0) { bos.write(chunk, 0, len); } } bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8")); } else { buf.close(); bos.write(buf.toString().getBytes("UTF-8")); } bos.flush(); bos.close(); // connection headers String url = Consts.SYNC_BASE; if (method.equals("register")) { url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password=" + registerData.getString("p"); } else if (method.startsWith("upgrade")) { url = url + method; } else { url = syncURL() + method; } HttpPost httpPost = new HttpPost(url); HttpEntity entity = new ProgressByteEntity(tmpFileBuffer); // body httpPost.setEntity(entity); httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY); // HttpParams HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); params.setParameter(CoreProtocolPNames.USER_AGENT, "KanjiDroid-" + VersionUtils.getPkgVersionName()); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT); // Registry SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry); if (cancelCallback != null) { cancelCallback.setConnectionManager(cm); } try { HttpClient httpClient = new DefaultHttpClient(cm, params); HttpResponse httpResponse = httpClient.execute(httpPost); // we assume badAuthRaises flag from Anki Desktop always False // so just throw new RuntimeException if response code not 200 or 403 assertOk(httpResponse); return httpResponse; } catch (SSLException e) { Timber.e(e, "SSLException while building HttpClient"); throw new RuntimeException("SSLException while building HttpClient"); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { Timber.e(e, "BasicHttpSyncer.sync: IOException"); throw new RuntimeException(e); } catch (JSONException e) { throw new RuntimeException(e); } finally { if (tmpFileBuffer != null && tmpFileBuffer.exists()) { tmpFileBuffer.delete(); } } }
From source file:com.siblinks.ws.service.impl.CommentServiceImpl.java
/** * {@inheritDoc}//from w ww . j av a 2s. c o m */ @Override @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody public ResponseEntity<Response> uploadFile(@RequestParam("uploadfile") final MultipartFile uploadfile) { String filename = ""; String name = ""; String filepath = ""; SimpleResponse reponse = null; try { String directory = environment.getProperty("directoryImageComment"); String directoryGetImage = environment.getProperty("directoryGetImageComment"); String linkToImage = null; name = uploadfile.getContentType(); boolean status = name.contains("image"); if (directory != null && status) { RandomString randomName = new RandomString(); filename = randomName.random(); filepath = Paths.get(directory, filename + ".png").toString(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filepath))); stream.write(uploadfile.getBytes()); stream.close(); linkToImage = directoryGetImage + filename; reponse = new SimpleResponse(SibConstants.SUCCESS, linkToImage); } else { reponse = new SimpleResponse(SibConstants.FAILURE, "Your photos couldn't be uploaded. Photos should be saved as JPG, PNG, GIF or BMP files."); } } catch (Exception e) { e.printStackTrace(); reponse = new SimpleResponse(SibConstants.FAILURE, e.getMessage()); } return new ResponseEntity<Response>(reponse, HttpStatus.OK); }
From source file:com.android.volley.toolbox.DiskBasedCache.java
/** * Puts the entry with the specified key into the cache. *//*from w ww.jav a 2 s . com*/ @Override public synchronized void put(String key, Entry entry) { pruneIfNeeded(entry.data.length); File file = getFileForKey(key); try { BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); CacheHeader e = new CacheHeader(key, entry); boolean success = e.writeHeader(fos); if (!success) { fos.close(); VolleyLog.d("Failed to write header for %s", file.getAbsolutePath()); throw new IOException(); } fos.write(entry.data); fos.close(); putEntry(key, e); return; } catch (IOException e) { } boolean deleted = file.delete(); if (!deleted) { VolleyLog.d("Could not clean up file %s", file.getAbsolutePath()); } }