List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:com.dao.ShopThread.java
private boolean doJSShop() throws Exception { LogUtil.debugPrintf("?----------->"); // loadCookie(); boolean result = true; LogUtil.webPrintf("??..."); String postParams = addJSDynamicParams(); LogUtil.webPrintf("???"); LogUtil.webPrintf("?..."); HttpURLConnection loginConn = getHttpPostConn(this.jsshopurl); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);/*from w w w. ja v a2 s .com*/ wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.jsshopurl); LogUtil.debugPrintf("Post parameters : " + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("??HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { result = false; LogUtil.webPrintf("?!"); } else { LogUtil.webPrintf("??!"); LogUtil.debugPrintf("cookie====" + cookie); LogUtil.debugPrintf("Location :" + loginConn.getURL().toString()); setCookies(cookie); LogUtil.webPrintf("?..."); String payurl = getPayKey(loginConn, "js"); LogUtil.webPrintf("??"); if (payurl != null && !payurl.equals("")) { LogUtil.debugPrintf("?url:" + payurl); LogUtil.webPrintf("..."); pay(payurl); LogUtil.webPrintf("?"); } else { LogUtil.webPrintf("?"); LogUtil.debugPrintf("?url"); } } LogUtil.debugPrintf("??----------->"); // System.out.println(list.toHtml()); return result; }
From source file:com.almunt.jgcaap.systemupdater.MainActivity.java
public void RebootRecovery(boolean update) { AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this); builder1.setTitle("Recovery Reboot"); if (update)// ww w . j a v a2s. com builder1.setMessage( "Would you like to reboot into recovery now to complete update?\nClear ORS will delete the OpenRecoveryScript to stop TWRP from automatically installing any files."); else builder1.setMessage("Would you like to reboot into recovery now.\n" + "Clear ORS will delete the current OpenRecoveryScript and stop any automatic update installations in TWRP"); builder1.setCancelable(true); builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { Process su = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(su.getOutputStream()); outputStream.writeBytes("reboot recovery\n"); outputStream.flush(); outputStream.writeBytes("exit\n"); outputStream.flush(); su.waitFor(); } catch (IOException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } catch (InterruptedException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } } }); builder1.setNeutralButton("Clear ORS", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { Process su = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(su.getOutputStream()); outputStream.writeBytes("cd /cache/recovery/\n"); outputStream.flush(); outputStream.writeBytes("rm openrecoveryscript\n"); outputStream.flush(); outputStream.writeBytes("exit\n"); outputStream.flush(); su.waitFor(); Toast.makeText(MainActivity.this, "OpenRecoveryScript file was cleared", Toast.LENGTH_LONG) .show(); } catch (IOException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } catch (InterruptedException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } } }); builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); if (update) builder1.setNegativeButton("Reboot Later", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert11 = builder1.create(); alert11.show(); }
From source file:com.github.gcauchis.scalablepress4j.api.AbstractRestApi.java
/** * Call request for entity./* w w w. java2s . c o m*/ * * @param <T> the generic type * @param url the url * @param requestMethod the http request method * @param request the request * @param responseType the response type * @param urlVariables the url variables * @return the response */ private <T> Response<T> forEntity(String url, String requestMethod, Object request, Class<T> responseType, Map<String, ?> urlVariables) { StringBuilder response = new StringBuilder(); HttpURLConnection connection = prepareConnection(url, requestMethod, urlVariables); try { // // Send request DataOutputStream wr = null; if (request != null) { String content = objectMapper.writeValueAsString(request); wr = new DataOutputStream(connection.getOutputStream()); wr.write(content.getBytes(StandardCharsets.UTF_8)); wr.flush(); } // Get Response BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } if (wr != null) { wr.close(); } rd.close(); log.trace("Response {}", response); } catch (IOException e) { log.error("Fail to send request", e); ErrorResponse errorResponse = new ErrorResponse(); try { errorResponse.setStatusCode(connection.getResponseCode() + ""); errorResponse.setMessage(connection.getResponseMessage()); } catch (IOException e1) { errorResponse.setStatusCode("500"); errorResponse.setMessage(e.getMessage()); } throw new ScalablePressBadRequestException(errorResponse); } Response<T> responseEntity = new Response<>(); responseEntity.headers = connection.getHeaderFields(); log.debug("Header: {}", responseEntity.headers); try { responseEntity.body = objectMapper.readValue(response.toString(), responseType); } catch (IOException e) { log.error("Fail to parse response", e); ErrorResponse errorResponse = null; try { log.error("Response error: {} {}", connection.getResponseCode(), connection.getResponseMessage()); errorResponse = objectMapper.readValue(response.toString(), ErrorResponse.class); } catch (IOException ioe) { log.error("Fail to parse error", ioe); } if (errorResponse != null) { log.error("Response error object: {}", errorResponse); throw new ScalablePressBadRequestException(errorResponse); } } return responseEntity; }
From source file:ioc.wiki.processingmanager.http.HttpFileSender.java
/** * Prepara la comanda a enviar al servidor, l'envia i rep la resposta en un string. * Cont informaci sobre el xit de guardar el fitxer al servidor. * @return Retorna un string amb la resposta del servidor. *///ww w. j av a 2 s . c om @Override public String sendCommand() { super.prepareCommand(); try { ((HttpURLConnection) urlConnection).setRequestMethod(REQUEST_METHOD); urlConnection.setRequestProperty(PROPERTY_CONTENT_TYPE, content_type + boundary); DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream()); //Capalera fitxer request.writeBytes(twoHyphens + boundary + crlf); request.writeBytes(contentDispositionFile + quote + this.destFilename + quote + crlf); request.writeBytes(contentTypeFile + crlf); request.writeBytes(contentTransferEncodingFile + crlf); request.writeBytes(crlf); //IMAGE String base64Image = Base64.encodeBase64String(this.image); request.writeBytes(base64Image); //Tancament fitxer request.writeBytes(crlf); request.writeBytes(twoHyphens + boundary + twoHyphens + crlf); request.flush(); request.close(); } catch (IOException ex) { throw new ProcessingRtURLException(ex); } return super.receiveResponse(); }
From source file:com.dao.ShopThread.java
private void pay(String payurl) { LogUtil.debugPrintf("----------->"); try {//w w w.j a v a 2 s .co m String postParams = getPayDynamicParams(payurl); HttpsURLConnection loginConn = getHttpSConn(payurl, "POST", Integer.toString(postParams.length())); if (null != this.cookies) { loginConn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies)); } LogUtil.debugPrintf("HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + payurl); LogUtil.debugPrintf("Post parameters :" + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("conn.getHeaderFields():" + header); BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(2000); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String payresponse = response.toString(); LogUtil.debugPrintf("payresponse:" + payresponse); List<String> cookie = header.get("Set-Cookie"); String loginInfo; if (responseCode != 302) { LogUtil.debugPrintf("----------->"); loginInfo = ""; } else { LogUtil.debugPrintf("?----------->"); if (null != cookie && cookie.size() > 0) { LogUtil.debugPrintf("cookie====" + cookie); setCookies(cookie); } loginInfo = "?"; } LogUtil.webPrintf(loginInfo); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.haulmont.cuba.core.app.filestorage.amazon.AmazonS3FileStorage.java
@Override public long saveStream(FileDescriptor fileDescr, InputStream inputStream) throws FileStorageException { Preconditions.checkNotNullArgument(fileDescr.getSize()); int chunkSize = amazonS3Config.getChunkSize(); long fileSize = fileDescr.getSize(); URL amazonUrl = getAmazonUrl(fileDescr); // set the markers indicating we're going to send the upload as a series // of chunks: // -- 'x-amz-content-sha256' is the fixed marker indicating chunked // upload // -- 'content-length' becomes the total size in bytes of the upload // (including chunk headers), // -- 'x-amz-decoded-content-length' is used to transmit the actual // length of the data payload, less chunk headers Map<String, String> headers = new HashMap<>(); headers.put("x-amz-storage-class", "REDUCED_REDUNDANCY"); headers.put("x-amz-content-sha256", AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256); headers.put("content-encoding", "aws-chunked"); headers.put("x-amz-decoded-content-length", "" + fileSize); AWS4SignerForChunkedUpload signer = new AWS4SignerForChunkedUpload(amazonUrl, "PUT", "s3", amazonS3Config.getRegionName()); // how big is the overall request stream going to be once we add the signature // 'headers' to each chunk? long totalLength = AWS4SignerForChunkedUpload.calculateChunkedContentLength(fileSize, chunkSize); headers.put("content-length", "" + totalLength); String authorization = signer.computeSignature(headers, null, // no query parameters AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256, amazonS3Config.getAccessKey(), amazonS3Config.getSecretAccessKey()); // place the computed signature into a formatted 'Authorization' header // and call S3 headers.put("Authorization", authorization); // start consuming the data payload in blocks which we subsequently chunk; this prefixes // the data with a 'chunk header' containing signature data from the prior chunk (or header // signing, if the first chunk) plus length and other data. Each completed chunk is // written to the request stream and to complete the upload, we send a final chunk with // a zero-length data payload. try {//from w w w . ja v a2 s.co m // first set up the connection HttpURLConnection connection = HttpUtils.createHttpConnection(amazonUrl, "PUT", headers); // get the request stream and start writing the user data as chunks, as outlined // above; int bytesRead; byte[] buffer = new byte[chunkSize]; DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); //guarantees that it will read as many bytes as possible, this may not always be the case for //subclasses of InputStream while ((bytesRead = IOUtils.read(inputStream, buffer, 0, chunkSize)) > 0) { // process into a chunk byte[] chunk = signer.constructSignedChunk(bytesRead, buffer); // send the chunk outputStream.write(chunk); outputStream.flush(); } // last step is to send a signed zero-length chunk to complete the upload byte[] finalChunk = signer.constructSignedChunk(0, buffer); outputStream.write(finalChunk); outputStream.flush(); outputStream.close(); // make the call to Amazon S3 HttpUtils.HttpResponse httpResponse = HttpUtils.executeHttpRequest(connection); if (!httpResponse.isStatusOk()) { String message = String.format("Could not save file %s. %s", getFileName(fileDescr), getInputStreamContent(httpResponse)); throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, message); } } catch (IOException e) { throw new RuntimeException("Error when sending chunked upload request", e); } return fileDescr.getSize(); }
From source file:com.norconex.committer.idol.IdolCommitter.java
/** * Add/Remove/Commit documents based on the parameters passed to the method. * @param url URL to post//w ww . j ava 2 s . c om * @param the content to post */ private void postToIDOL(String url, String content) { HttpURLConnection con = null; DataOutputStream wr = null; try { con = createURLConnection(url); wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(content); wr.flush(); //Get the response int responseCode = con.getResponseCode(); if (LOG.isDebugEnabled()) { LOG.debug("Sending 'POST' request to URL : " + url); LOG.debug("Post parameters : " + content); LOG.debug("Server Response Code : " + responseCode); } String response = IOUtils.toString(con.getInputStream()); if ((isCFS() && !StringUtils.contains(response, "SUCCESS")) || (!isCFS() && !StringUtils.contains(response, "INDEXID"))) { throw new CommitterException("Unexpected HTTP response: " + response); } wr.close(); } catch (IOException e) { throw new CommitterException("Cannot post content to " + createURL(), e); } finally { if (con != null) { con.disconnect(); } IOUtils.closeQuietly(wr); } }
From source file:it.unimi.dsi.sux4j.io.ChunkedHashStore.java
/** Returns the size of this store. Note that if you set up * a {@linkplain #filter(Predicate) filter}, the first call to * this method will require a scan to the whole store. * /*from w w w.j a va2 s . co m*/ * @return the number of (possibly filtered) triples of this store. */ public long size() throws IOException { if (filter == null) return size; if (filteredSize == -1) { long c = 0; final long[] triple = new long[3]; for (int i = 0; i < DISK_CHUNKS; i++) { if (filter == null) c += count[i]; else { for (DataOutputStream d : dos) d.flush(); final DataInputStream dis = new DataInputStream( new FastBufferedInputStream(new FileInputStream(file[i]))); for (int j = 0; j < count[i]; j++) { triple[0] = dis.readLong(); triple[1] = dis.readLong(); triple[2] = dis.readLong(); if (hashMask == 0) dis.readLong(); if (filter.evaluate(triple)) c++; } dis.close(); } } filteredSize = c; } return filteredSize; }
From source file:com.webkey.Ipc.java
public void comBinAuth(String turl, String postData) { readAuthKey();/*from www . j av a2s .c o m*/ try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context); port = prefs.getString("port", "80"); Socket s = new Socket("127.0.0.1", Integer.parseInt(port)); //outgoing stream redirect to socket DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream()); byte[] utf = postData.getBytes("UTF-8"); dataOutputStream.writeBytes("POST /" + authKey + turl + " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n"); dataOutputStream.write(utf, 0, utf.length); dataOutputStream.flush(); dataOutputStream.close(); s.close(); } catch (IOException e1) { //e1.printStackTrace(); } /* // Log.d(TAG,"post data"); String target = "http://127.0.0.1:"+port+"/"+authKey+turl; //Log.d(TAG,target); URL url = new URL(target); URLConnection conn = url.openConnection(); // Set connection parameters. conn.setDoInput (true); conn.setDoOutput (true); conn.setUseCaches (false); //Make server believe we are form data... conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream (conn.getOutputStream ()); // Write out the bytes of the content string to the stream. out.writeBytes(postData); out.flush (); out.close (); // Read response BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ())); String temp; String response = null; while ((temp = in.readLine()) != null){ response += temp + "\n"; } temp = null; in.close (); System.out.println("Server response:\n'" + response + "'"); }catch(Exception e){ Log.d(TAG,e.toString()); } */ }
From source file:com.webkey.Ipc.java
public void sendMessage(String message) { readAuthKey();//from w w w . ja v a 2s. c o m try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context); port = prefs.getString("port", "80"); Socket s = new Socket("127.0.0.1", Integer.parseInt(port)); //outgoing stream redirect to socket DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream()); byte[] utf = message.getBytes("UTF-8"); dataOutputStream.writeBytes("POST /" + authKey + "phonewritechatmessage HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n"); dataOutputStream.write(utf, 0, utf.length); dataOutputStream.flush(); dataOutputStream.close(); s.close(); } catch (IOException e1) { //e1.printStackTrace(); } }