List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:com.chiorichan.util.WebUtils.java
public static boolean sendTracking(String category, String action, String label) { String url = "http://www.google-analytics.com/collect"; try {/*from w w w. ja v a 2s. com*/ URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); String urlParameters = "v=1&tid=UA-60405654-1&cid=" + Loader.getClientId() + "&t=event&ec=" + category + "&ea=" + action + "&el=" + label; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); Loader.getLogger().fine("Analytics Response [" + category + "]: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return true; } catch (IOException e) { return false; } }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * Makes HTTP request using java.net.HTTPURLConnection and optional settings * for the connection//from w w w. j a v a 2 s. c o m * * @param urlStr * the URL String * @param requestMethod * Method type * @param body * Body to pass in request. * @param header * Header parameters * @param connectionSettings * The connection settings to apply * @return Response Object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body, final Map<String, String> header, Optional<ConnectionSettings> connectionSettings) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } connectionSettings.ifPresent(settings -> settings.apply(conn)); if (MethodType.POST.toString().equalsIgnoreCase(requestMethod) || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (body != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.write(body.getBytes("UTF-8")); out.flush(); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:Main.java
public static String upLoad(File file, String RequestURL) { String BOUNDER = UUID.randomUUID().toString(); String PREFIX = "--"; String END = "/r/n"; try {//from ww w.j a v a 2s .c o m URL url = new URL(RequestURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(TIME_OUT); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Charset", CHARSET); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Cotent-Type", CONTENT_TYPE + ";boundary=" + BOUNDER); if (file != null) { OutputStream outputStream = connection.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(outputStream); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDER + END); dataOutputStream.write(sb.toString().getBytes()); InputStream in = new FileInputStream(file); byte[] b = new byte[1024]; int l = 0; while ((l = in.read()) != -1) { outputStream.write(b, 0, l); } in.close(); dataOutputStream.write(END.getBytes()); dataOutputStream.write((PREFIX + BOUNDER + PREFIX + END).getBytes()); dataOutputStream.flush(); int i = connection.getResponseCode(); if (i == 200) { return SUCCESS; } } } catch (IOException e) { e.printStackTrace(); } return FALIURE; }
From source file:com.doctoror.surprise.SurpriseService.java
private static Result execute(final List<String> commands, final boolean surpriseBinary) { final Result result = new Result(); Process process = null;// ww w .j a v a 2 s.c o m DataOutputStream os = null; BufferedReader is = null; try { process = new ProcessBuilder().command(surpriseBinary ? COMMAND_SURPRISE : COMMAND_SU) .redirectErrorStream(true).start(); os = new DataOutputStream(process.getOutputStream()); is = new BufferedReader(new InputStreamReader(process.getInputStream())); for (final String command : commands) { os.writeBytes(command + "\n"); } os.flush(); os.writeBytes("exit\n"); os.flush(); final StringBuilder output = new StringBuilder(); String line; try { while ((line = is.readLine()) != null) { if (output.length() != 0) { output.append('\n'); } output.append(line); } } catch (EOFException ignored) { } result.output = output.toString(); result.exitCode = process.waitFor(); } catch (Exception e) { e.printStackTrace(); result.exitCode = -666; result.output = e.getMessage(); } finally { if (os != null) { try { os.close(); } catch (Exception ignored) { } } if (is != null) { try { is.close(); } catch (Exception ignored) { } } if (process != null) { try { process.destroy(); } catch (Exception ignored) { } } } return result; }
From source file:io.hops.metadata.HdfsVariables.java
private static ByteArrayVariable serializeBlockKey(BlockKey key, Variable.Finder keyType) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(os); key.write(dos);/*from ww w. j av a 2 s . com*/ dos.flush(); return new ByteArrayVariable(keyType, os.toByteArray()); }
From source file:Main.java
public static String runAsRoot(String[] cmds) throws Exception { Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); InputStream is = p.getInputStream(); String result = null;//from w w w. j a v a 2 s . c o m for (String tmpCmd : cmds) { os.writeBytes(tmpCmd + "\n"); int readed = 0; byte[] buff = new byte[4096]; while (is.available() <= 0) { try { Thread.sleep(5000); } catch (Exception ex) { } } while (is.available() > 0) { readed = is.read(buff); if (readed <= 0) break; String seg = new String(buff, 0, readed); result = seg; //result is a string to show in textview } } os.writeBytes("exit\n"); os.flush(); return result; }
From source file:com.fota.Link.sdpApi.java
public static String getCtnInfo(String ncn) throws JDOMException { String resultStr = ""; String logData = ""; try {/*from ww w . ja v a 2 s .c o m*/ String cpId = PropUtil.getPropValue("sdp3g.id"); String cpPw = PropUtil.getPropValue("sdp3g.pw"); String authorization = cpId + ":" + cpPw; logData = "\r\n---------- Get Ctn Req Info start ----------\r\n"; logData += " getCtnRequestInfo - authorization : " + authorization; byte[] encoded = Base64.encodeBase64(authorization.getBytes()); authorization = new String(encoded); String contractType = "0"; String contractNum = ncn.substring(0, 9); String customerId = ncn.substring(10, ncn.length() - 1); JSONObject reqJObj = new JSONObject(); reqJObj.put("transactionid", ""); reqJObj.put("sequenceno", ""); reqJObj.put("userid", ""); reqJObj.put("screenid", ""); reqJObj.put("CONTRACT_NUM", contractNum); reqJObj.put("CUSTOMER_ID", customerId); reqJObj.put("CONTRACT_TYPE", contractType); authorization = "Basic " + authorization; String endPointUrl = PropUtil.getPropValue("sdp.oif555.url"); logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl; logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization; logData += "\r\n getCtnRequestInfo - Content-type : application/json"; logData += "\r\n getCtnRequestInfo - RequestMethod : POST"; logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString(); logData += "\r\n---------- Get Ctn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", authorization); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(reqJObj.toJSONString()); wr.flush(); wr.close(); // input BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine = ""; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONParser jsonParser = new JSONParser(); JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString()); // String respTransactionId = (String) respJsonObject.get("transactionid"); // String respSequenceNo = (String) respJsonObject.get("sequenceno"); // String respReturnCode = (String) respJsonObject.get("returncode"); // String respReturnDescription = (String) respJsonObject.get("returndescription"); // String respErrorCode = (String) respJsonObject.get("errorcode"); // String respErrorDescription = (String) respJsonObject.get("errordescription"); String respCtn = (String) respJsonObject.get("ctn"); // String respSubStatus = (String) respJsonObject.get("sub_status"); // String respSubStatusDate = (String) respJsonObject.get("sub_status_date"); resultStr = respCtn; //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Sends an HTTPS POST request and returns the response * * @param conn the HTTPS connection object * @param payload the payload for the POST request * @return the response from the remote server * *//*w ww . j a v a 2 s . co m*/ public static int sendPost(HttpsURLConnection conn, String payload) { OutputStream outputStream = null; DataOutputStream wr = null; InputStream is = null; int response = 0; logger.debug("Attempting HTTPS POST..."); try { outputStream = conn.getOutputStream(); wr = new DataOutputStream(outputStream); wr.write(payload.getBytes("UTF-8")); wr.flush(); is = conn.getInputStream(); response = conn.getResponseCode(); } catch (IOException e) { logger.debug("IOException when attempting to send a post message. "); } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an input stream. "); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an output stream. "); } } if (wr != null) { try { wr.close(); } catch (IOException e) { logger.debug("IOException when attempting to close a data output stream. "); } } } logger.debug("HTTPS POST Response: " + response); return response; }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Sends an HTTPS POST request and returns the response in String format * * @param conn the HTTPS connection object * @param payload the payload for the POST request * @return the response from the remote server in String format * *//*from w w w .j ava2 s . com*/ public static String sendPostGetStringResponse(HttpsURLConnection conn, String payload) { OutputStream outputStream = null; DataOutputStream wr = null; InputStream is = null; String response = ""; logger.debug("Attempting HTTPS POST"); try { outputStream = conn.getOutputStream(); wr = new DataOutputStream(outputStream); wr.write(payload.getBytes("UTF-8")); wr.flush(); is = conn.getInputStream(); response = IOUtils.toString(is, "UTF-8"); } catch (IOException e) { logger.debug("IOException when attempting to send a post message. "); } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an input stream. "); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { logger.debug("IOException when attempting to close an output stream. "); } } if (wr != null) { try { wr.close(); } catch (IOException e) { logger.debug("IOException when attempting to close a data output stream. "); } } } return response; }
From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java
/** * Run command as root./*www . j av a 2 s.com*/ * * @param command command * @return true, if command was successfully executed */ private static boolean runAsRoot(final String command) { Log.i(TAG, "running command as root: ", command); try { Runtime r = Runtime.getRuntime(); Process p = r.exec("su"); DataOutputStream d = new DataOutputStream(p.getOutputStream()); d.writeBytes(command); d.writeBytes("\nexit\n"); d.flush(); int retval = p.waitFor(); Log.i(TAG, "done"); return (retval == 0); } catch (Exception e) { Log.e(TAG, "runAsRoot", e); return false; } }