List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:com.ichi2.libanki.sync.BasicHttpSyncer.java
public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData, Connection.CancelCallback cancelCallback) { File tmpFileBuffer = null;/*from ww w . j a v a2 s . com*/ try { String bdry = "--" + BOUNDARY; StringWriter buf = new StringWriter(); // compression flag and session key as post vars buf.write(bdry + "\r\n"); buf.write("Content-Disposition: form-data; name=\"c\"\r\n\r\n" + (comp != 0 ? 1 : 0) + "\r\n"); if (hkey) { buf.write(bdry + "\r\n"); buf.write("Content-Disposition: form-data; name=\"k\"\r\n\r\n" + mHKey + "\r\n"); } 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 = Collection.SYNC_URL; 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 = url + "sync/" + 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-" + AnkiDroidApp.getPkgVersion()); 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); return httpClient.execute(httpPost); } catch (SSLException e) { Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e); return null; } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e); return null; } catch (JSONException e) { throw new RuntimeException(e); } finally { if (tmpFileBuffer != null && tmpFileBuffer.exists()) { tmpFileBuffer.delete(); } } }
From source file:com.hichinaschool.flashcards.libanki.sync.BasicHttpSyncer.java
public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData, Connection.CancelCallback cancelCallback) { File tmpFileBuffer = null;/* w w w . j a va2 s . co m*/ try { String bdry = "--" + BOUNDARY; StringWriter buf = new StringWriter(); HashMap<String, Object> vars = new HashMap<String, Object>(); // compression flag and session key as post vars vars.put("c", comp != 0 ? 1 : 0); if (hkey) { vars.put("k", mHKey); vars.put("s", mSKey); } for (String key : vars.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, vars.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 = Collection.SYNC_URL; 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 = url + "sync/" + 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-" + AnkiDroidApp.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); return httpClient.execute(httpPost); } catch (SSLException e) { Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e); return null; } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e); return null; } catch (JSONException e) { throw new RuntimeException(e); } finally { if (tmpFileBuffer != null && tmpFileBuffer.exists()) { tmpFileBuffer.delete(); } } }
From source file:edu.lternet.pasta.dml.download.DownloadHandler.java
/** * Get data from ecogrid server base on given end point and identifier. * This method will handle the distribution url for ecogrid or srb protocol * This method will be called by getContentFromSource(). * //from www. ja v a2 s . c o m * @param endPoint the end point of ecogrid service * @param identifier the entity identifier in ecogrid service */ protected boolean getContentFromEcoGridSource(String endPoint, String identifier) { // create a ecogrid client object and get the full record from the // client //System.out.println("=================the endpoint is "+endPoint); //System.out.println("=================the identifier is "+identifier); boolean successFlag = false; if (endPoint != null && identifier != null) { //log.debug("Get " + identifier + " from " + endPoint); try { //fatory //log.debug("This is instance pattern"); //log.debug("Get from EcoGrid: " + identifier); NeededOutputStream[] outputStreamList = getOutputStreamList(); if (outputStreamList != null) { boolean oneLoopSuccess = true; for (int i = 0; i < outputStreamList.length; i++) { NeededOutputStream stream = outputStreamList[i]; if (stream != null && stream.getNeeded()) { BufferedOutputStream bos = new BufferedOutputStream(stream.getOutputStream()); //use the appropriate client URL endPointURL = new URL(endPoint); if (sessionId != null) { AuthenticatedQueryServiceGetToStreamClient authenticatedEcogridClient = new AuthenticatedQueryServiceGetToStreamClient( endPointURL); authenticatedEcogridClient.get(identifier, sessionId, bos); } else { QueryServiceGetToStreamClient ecogridClient = new QueryServiceGetToStreamClient( endPointURL); ecogridClient.get(identifier, bos); } bos.flush(); bos.close(); if (oneLoopSuccess) { successFlag = true; } } else if (stream != null) { if (oneLoopSuccess) { successFlag = true; } } else { oneLoopSuccess = false; successFlag = false; } } } else { successFlag = false; } return successFlag; } catch (Exception ee) { log.error("DownloadHandler - error getting content from Ecogrid ", ee); ee.printStackTrace(); successFlag = false; return successFlag; } } else { //System.out.println("in else path of get data from other source"); // this is not ecogrid source, we need download by other protocol //return getContentFromSource(identifier); return false; } }
From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java
private void copyFile(FileChannel inChannel, BufferedOutputStream bufferedOutputStream) throws IOException { MappedByteBuffer inBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, mSourceFile.getSize()); int count = -1; byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; try {//from w w w . j a va 2s . com while (inBuffer.hasRemaining() && count != 0) { int tempPosition = inBuffer.position(); try { // try normal way of getting bytes ByteBuffer tempByteBuffer = inBuffer.get(buffer); count = tempByteBuffer.position() - tempPosition; } catch (BufferUnderflowException exception) { exception.printStackTrace(); // not enough bytes left in the channel to read, iterate over each byte and store // in the buffer // reset the counter bytes count = 0; for (int i = 0; i < buffer.length && inBuffer.hasRemaining(); i++) { buffer[i] = inBuffer.get(); count++; } } if (count != -1 && !progressHandler.getCancelled()) { bufferedOutputStream.write(buffer, 0, count); ServiceWatcherUtil.position = inBuffer.position(); } else break; } } finally { bufferedOutputStream.flush(); } }
From source file:InstallJars.java
protected void pumpGZip(String target, GZIPInputStream zis) throws IOException { String curName = null;/*from w w w . java 2 s .c o m*/ long curSize = 0, remainingSize = 0; char curType = 0; int curMajor = 0, curMinor = 0; boolean inFile = false; BufferedOutputStream curOs = null; int instFiles = 0, instDirs = 0; byte[] buf = new byte[bufferSize]; top: while (true) { int loaded = loadBytes(buf, zis); if (loaded < 0) { break; } // System.out.println("pumpGZip: loaded=" + loaded); // process each buffer of data for (int index = 0; index < loaded; index += BLOCK_SIZE) { // System.out.println("pumpGZip: infile=" + inFile + ", remaining=" + // remainingSize); if (inFile && remainingSize > 0) { // process body part int xsize = Math.min((int) remainingSize, BLOCK_SIZE); if (curOs != null) { curOs.write(buf, index, xsize); } remainingSize -= xsize; } else { // process header block if (inFile) { inFile = false; if (curOs != null) { try { curOs.flush(); curOs.close(); } catch (IOException ioe) { } println(); } } if (isEmptyBlock(buf, index)) { // check logical end of archive break top; } // System.out.println("pumpGZip: header=" + (new String(buf, 0, index, // 512))); curName = extractString(buf, index + OFFSET_NAME, 100); curType = extractChar(buf, index + OFFSET_TYPE); curSize = extractLong(buf, index + OFFSET_SIZE, 12); remainingSize = curSize; if (remainingSize > Integer.MAX_VALUE) { throw new IOException("entry size too large - " + remainingSize); } String mod = ""; String magic = extractString(buf, index + OFFSET_MAGIC, 6); if (magic.equals(MAGIC)) { curName = extractString(buf, index + OFFSET_PREFIX, 155) + curName; extractInt(buf, index + OFFSET_VERSION, 2); curMajor = extractInt(buf, index + OFFSET_DEVMAJOR, 8); curMinor = extractInt(buf, index + OFFSET_DEVMINOR, 8); if (curMajor > 0 || curMinor > 0) { mod = "[" + curMajor + '.' + curMinor + "]"; } } // System.out.println("pumpGZip: " + // magic + "," + // curName + "," + // curType + "," + // curSize + "," + // curVersion + "," + // curMajor + "," + // curMinor); String path = target + File.separator + curName; path = path.replace('\\', '/'); curOs = null; if (curType == 0 || curType == '0') { // a file print("Copying " + curName + mod + " to " + path); prepDirs(path, false); curOs = new BufferedOutputStream(new FileOutputStream(path), BLOCK_SIZE * BLOCK_COUNT); inFile = true; instFiles++; } else if (curType == '1' || curType == '2') { // a link if (curSize > 0) { throw new IOException("link entries cannot have content - " + curSize); } println("Link ignored - " + curName + mod); } else if (curType == '5') { // a directory if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } println("Mkdir " + curName + mod + " to " + path); prepDirs(path, true); instDirs++; } else { if (curSize > 0) { // throw new IOException("entry type " + curType + " cannot have a // content - size=" + curSize); inFile = true; } print("Entry type " + curType + " ignored - " + curName + mod); } } } } println("Installed " + instFiles + " files and " + instDirs + " directories"); }
From source file:org.dswarm.graph.resources.GDMResource.java
@POST @Path("/searchrecords") @Consumes(MediaType.APPLICATION_JSON)//w w w. j a v a2 s . c o m @Produces(MediaType.APPLICATION_JSON) public Response searchGDMRecords(final String jsonObjectString, @Context final GraphDatabaseService database) throws DMPGraphException { GDMResource.LOG.debug("try to {} in graph db", SEARCH_GDM_RECORDS_TYPE); final ObjectNode requestJSON = deserializeJSON(jsonObjectString, READ_GDM_RECORD_TYPE); final String keyAPString = requestJSON.get(DMPStatics.KEY_ATTRIBUTE_PATH_IDENTIFIER).asText(); final String searchValue = requestJSON.get(DMPStatics.SEARCH_VALUE_IDENTIFIER).asText(); final String dataModelUri = requestJSON.get(DMPStatics.DATA_MODEL_URI_IDENTIFIER).asText(); final Optional<Integer> optionalVersion = getIntValue(DMPStatics.VERSION_IDENTIFIER, requestJSON); final TransactionHandler tx = new Neo4jTransactionHandler(database); final NamespaceIndex namespaceIndex = new NamespaceIndex(database, tx); final String prefixedDataModelURI = namespaceIndex.createPrefixedURI(dataModelUri); final AttributePath keyAP = AttributePathUtil.parseAttributePathString(keyAPString); final AttributePath prefixedKeyAP = prefixAttributePath(keyAP, namespaceIndex); GDMResource.LOG.info( "try to search GDM records for key attribute path = '{}' ('{}') and search value = '{}' in data model '{}' ('{}') with version = '{}' from graph db", keyAP, prefixedKeyAP, searchValue, dataModelUri, prefixedDataModelURI, optionalVersion); final Collection<String> recordURIs = GraphDBUtil.determineRecordUris(searchValue, prefixedKeyAP, prefixedDataModelURI, database); if (recordURIs == null || recordURIs.isEmpty()) { GDMResource.LOG.info( "couldn't find any record for key attribute path = '{}' ('{}') and search value = '{}' in data model '{}' ('{}') with version = '{}' from graph db", keyAP, prefixedKeyAP, searchValue, dataModelUri, prefixedDataModelURI, optionalVersion); final StreamingOutput stream = os -> { final BufferedOutputStream bos = new BufferedOutputStream(os, 1024); final ModelBuilder modelBuilder = new ModelBuilder(bos); modelBuilder.build(); bos.flush(); os.flush(); bos.close(); os.close(); }; return Response.ok(stream, MediaType.APPLICATION_JSON_TYPE).build(); } final StreamingOutput stream = os -> { try { final BufferedOutputStream bos = new BufferedOutputStream(os, 1024); final ModelBuilder modelBuilder = new ModelBuilder(bos); int resourcesSize = 0; long statementsSize = 0; for (final String recordUri : recordURIs) { final GDMResourceReader gdmReader = new PropertyGraphGDMResourceByURIReader(recordUri, prefixedDataModelURI, optionalVersion, database, tx, namespaceIndex); try { final Resource resource = gdmReader.read(); modelBuilder.addResource(resource); resourcesSize++; statementsSize += resource.size(); } catch (final DMPGraphException e) { GDMResource.LOG.debug("couldn't retrieve record for record URI '{}'", recordUri); } } modelBuilder.build(); bos.flush(); os.flush(); bos.close(); os.close(); if (resourcesSize > 0) { GDMResource.LOG.info( "finished reading '{} records with '{}' GDM statements for key attribute path = '{}' ('{}') and search value = '{}' in data model '{}' ('{}') with version = '{}' from graph db", resourcesSize, statementsSize, keyAP, prefixedKeyAP, searchValue, dataModelUri, prefixedDataModelURI, optionalVersion); } else { GDMResource.LOG.info( "couldn't retrieve any record for key attribute path = '{}' ('{}') and search value = '{}' in data model '{}' ('{}') with version = '{}' from graph db", keyAP, prefixedKeyAP, searchValue, dataModelUri, prefixedDataModelURI, optionalVersion); } } catch (final DMPGraphException e) { throw new WebApplicationException(e); } }; return Response.ok(stream, MediaType.APPLICATION_JSON_TYPE).build(); }
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 a v a 2s . 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;//from ww w. j a va2 s.co 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(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.ridgelineapps.wallpaper.photosite.FlickrUtils.java
/** * Downloads the specified photo at the specified size in the specified destination. * * @param photo The photo to download./*from w w w . ja v a 2 s.co m*/ * @param size The size of the photo to download. * @param destination The output stream in which to write the downloaded photo. * * @throws IOException If any network exception occurs during the download. */ void downloadPhoto(Photo photo, PhotoSize size, OutputStream destination) throws IOException { final BufferedOutputStream out = new BufferedOutputStream(destination, IO_BUFFER_SIZE); final String url = photo.getUrl(size); final HttpGet get = new HttpGet(url); HttpEntity entity = null; try { final HttpResponse response = mClient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); entity.writeTo(out); out.flush(); } } finally { if (entity != null) { entity.consumeContent(); } } }
From source file:org.universAAL.itests.IntegrationTest.java
/** * Helper method for extracting zipped archive provided as input stream into * given directory.//from w w w . j a v a 2 s . c om * * @param is * @param destDirStr */ private void unzipInpuStream(final InputStream is, final String destDirStr) { try { File destDir = new File(destDirStr); final int BUFFER = 1024; BufferedOutputStream dest = null; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); if (entry.getName().startsWith("META-INF")) { // META-INF (which includes MANIFEST) should not be // unpacked. It should be just ignored continue; } if (entry.isDirectory()) { File newDir = new File(destDir, entry.getName()); newDir.mkdirs(); } else { int count; byte[] data = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(new File(destDir, entry.getName())); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } zis.close(); } catch (Exception e) { e.printStackTrace(); } }