List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:com.cmput301w15t15.travelclaimsapp.FileManager.java
/** * Saves claimlist to file and attempts to save online if there is an internet connection. * // ww w . j a va2 s. c o m * @param ClaimList claimList * @param String username */ public void saveClaimLInFile(ClaimList claimList, String username) { Thread thread = new onlineSaveClaimListThread(claimList, username); thread.start(); try { //openFileOutput is a Activity method FileOutputStream fos = context.openFileOutput(CLAIMLISTFILENAME, 0); OutputStreamWriter osw = new OutputStreamWriter(fos); gson.toJson(claimList, osw); osw.flush(); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.d(TAG, "saveClaimLInFile could not find file: " + e.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "saveClaimLInFile did not work: " + e.getMessage()); } }
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
private byte[] newRequest() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final OutputStreamWriter osw = new OutputStreamWriter(baos, "US-ASCII"); int add = 16; int num = 0;// w w w .j a va2 s.c o m for (int i = 0; i < 16384; i += add) { if (++add == 32) { add = 16; } osw.write(getHeader("field" + (num++))); osw.flush(); for (int j = 0; j < i; j++) { baos.write((byte) j); } osw.write("\r\n"); } osw.write(getFooter()); osw.close(); return baos.toByteArray(); }
From source file:com.doomy.padlock.MainActivity.java
public void androidDebugBridge(String mPort) { Runtime mRuntime = Runtime.getRuntime(); Process mProcess = null;//from ww w . jav a2 s .c o m OutputStreamWriter mWrite = null; try { mProcess = mRuntime.exec("su"); mWrite = new OutputStreamWriter(mProcess.getOutputStream()); mWrite.write("setprop service.adb.tcp.port " + mPort + "\n"); mWrite.flush(); mWrite.write("stop adbd\n"); mWrite.flush(); mWrite.write("start adbd\n"); mWrite.flush(); mWrite.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.apache.solr.client.solrj.TestSolrJErrorHandling.java
@Test public void testHttpURLConnection() throws Exception { String bodyString = getJsonDocs(200000); // sometimes succeeds with this size, but larger can cause OOM from command line HttpSolrClient client = (HttpSolrClient) getSolrClient(); String urlString = client.getBaseURL() + "/update"; HttpURLConnection conn = null; URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true);/*from w w w . j av a 2s . c om*/ conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); writer.write(bodyString); writer.flush(); int code = 1; try { code = conn.getResponseCode(); } catch (Throwable th) { log.error("ERROR DURING conn.getResponseCode():", th); } /*** java.io.IOException: Error writing to server at __randomizedtesting.SeedInfo.seed([2928C6EE314CD076:947A81A74F582526]:0) at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:665) at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:677) at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1533) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440) at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) */ log.info("CODE=" + code); InputStream is; if (code == 200) { is = conn.getInputStream(); } else { log.info("Attempting to get error stream."); is = conn.getErrorStream(); if (is == null) { log.info("Can't get error stream... try input stream?"); is = conn.getInputStream(); } } String rbody = IOUtils.toString(is, StandardCharsets.UTF_8); log.info("RESPONSE BODY:" + rbody); }
From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java
/** * Gets the input stream from the {@link URLConnection} and stores it in * the {@link YADAQueryResult} in {@code yq} * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery) *///w ww . ja va 2 s. c om @Override public void execute(YADAQuery yq) throws YADAAdaptorExecutionException { boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST) || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH); resetCountParameter(yq); int rows = yq.getData().size() > 0 ? yq.getData().size() : 1; /* * Remember: * A row is an set of YADA URL parameter values, e.g., * * x,y,z in this: * ...yada/q/queryname/p/x,y,z * so 1 row * * or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this: * ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}] * so 2 rows */ for (int row = 0; row < rows; row++) { String result = ""; // creates result array and assigns it yq.setResult(); YADAQueryResult yqr = yq.getResult(); String urlStr = yq.getUrl(row); for (int i = 0; i < yq.getParamCount(row); i++) { Matcher m = PARAM_URL_RX.matcher(urlStr); if (m.matches()) { String param = yq.getVals(row).get(i); urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param); } } l.debug("REST url w/params: [" + urlStr + "]"); try { URL url = new URL(urlStr); URLConnection conn = null; if (this.hasProxy()) { String[] proxyStr = this.proxy.split(":"); Proxy proxySvr = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1]))); conn = url.openConnection(proxySvr); } else { conn = url.openConnection(); } // basic auth if (url.getUserInfo() != null) { //TODO issue with '@' sign in pw, must decode first String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes())); conn.setRequestProperty("Authorization", basicAuth); } // cookies if (yq.getCookies() != null && yq.getCookies().size() > 0) { String cookieStr = ""; for (HttpCookie cookie : yq.getCookies()) { cookieStr += cookie.getName() + "=" + cookie.getValue() + ";"; } conn.setRequestProperty("Cookie", cookieStr); } if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) { l.debug("Processing custom headers..."); @SuppressWarnings("unchecked") Iterator<String> keys = yq.getHttpHeaders().keys(); while (keys.hasNext()) { String name = keys.next(); String value = yq.getHttpHeaders().getString(name); l.debug("Custom header: " + name + " : " + value); conn.setRequestProperty(name, value); if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) { l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]"); this.method = YADARequest.METHOD_POST; } } } HttpURLConnection hConn = (HttpURLConnection) conn; if (!this.method.equals(YADARequest.METHOD_GET)) { hConn.setRequestMethod(this.method); if (isPostPutPatch) { //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object. It // is not a YADA param String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0]; hConn.setDoOutput(true); OutputStreamWriter writer; writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(payload.toString()); writer.flush(); } } // debug Map<String, List<String>> map = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); } try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { result += String.format("%1s%n", inputLine); } } yqr.addResult(row, result); } catch (MalformedURLException e) { String msg = "Unable to access REST source due to a URL issue."; throw new YADAAdaptorExecutionException(msg, e); } catch (IOException e) { String msg = "Unable to read REST response."; throw new YADAAdaptorExecutionException(msg, e); } } }
From source file:objective.taskboard.RequestBuilder.java
private RequestResponse doActualRequest(String method) { OutputStreamWriter writer = null; try {/*from w w w . j a v a2s . co m*/ conn.setRequestMethod(method); if (!StringUtils.isEmpty(body)) { conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); writer.write(body); writer.flush(); } int responseCode = conn.getResponseCode(); String content; try { content = IOUtils.toString(conn.getInputStream(), "UTF-8"); } catch (IOException e) { content = e.getMessage(); } if (responseCode < lowerAcceptableStatus || responseCode > upperAcceptableStatus) throw new IllegalStateException("Failed : HTTP error code : " + responseCode); return new RequestResponse(responseCode, content, conn.getHeaderFields()); } catch (Exception e) { throw new IllegalStateException(e); } finally { try { if (writer != null) writer.close(); } catch (IOException e) { throw new IllegalStateException(e); } } }
From source file:fi.hip.sicx.store.HIPStoreClient.java
@Override public boolean deleteFile(String cloudFile, StorageClientObserver sco) { boolean ok = false; HttpURLConnection conn = null; try {/*www .ja v a 2 s. c om*/ String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8"); conn = getConnection("/store/erase"); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); ok = true; } catch (Exception e) { e.printStackTrace(); failed = true; } closeConnection(conn); return ok; }
From source file:dbf.parser.pkg2.handler.java
private void sendPost(String json) throws Exception { System.out.println("Adding url .."); String url = "http://shorewindowcleaning:withwindows@ironside.ddns.net:5984/shorewindowcleaning/_bulk_docs"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); //con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Type", "application/json"); String basicAuth = "Basic " + new String(new Base64().encode(obj.getUserInfo().getBytes())); con.setRequestProperty("Authorization", basicAuth); //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; System.out.println("Adding output .."); // Send post request con.setDoOutput(true);/*from www. j a v a 2 s . c o m*/ OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(json); wr.flush(); wr.close(); System.out.println("geting content .."); // System.out.println(con.getResponseMessage()); int responseCode = con.getResponseCode(); System.out.println("Adding checking response .."); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + json); System.out.println("Response Code : " + responseCode); System.out.println(con.getResponseMessage()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); }
From source file:at.lame.hellonzb.parser.NzbParser.java
/** * This method is called to save the currently loaded parser data * to a file (to be loaded later on)./*from www.j a va 2s . c o m*/ * * @param logger The central logger object * @param counter File(name) counter * @param filename File name to use * @param dlFiles The vector of DownloadFile to write * @return Success status (true or false) */ public synchronized static boolean saveParserData(MyLogger logger, int counter, String filename, Vector<DownloadFile> dlFiles) { String newline = System.getProperty("line.separator"); if (dlFiles.size() < 1) return true; try { String datadirPath = System.getProperty("user.home") + "/.HelloNzb/"; // create home directory File datadir = new File(datadirPath); if (datadir.exists()) { if (datadir.isFile()) { logger.msg("Can't create data directory: " + datadirPath, MyLogger.SEV_ERROR); return false; } } else datadir.mkdirs(); File file = new File(datadirPath, counter + "-" + filename + ".nzb"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); // XML header writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); writer.write(newline); // XML doctype writer.write("<!DOCTYPE nzb PUBLIC \"-//newzBin//DTD NZB 1.0//EN\" " + "\"http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd\">"); writer.write(newline); // HelloNzb signature line writer.write("<!-- NZB generated by HelloNzb, the Binary Usenet tool -->"); writer.write(newline); // XML namespace writer.write("<nzb xmlns=\"http://www.newzbin.com/DTD/2003/nzb\">"); writer.write(newline); writer.write(newline); // now write all files passed to this method for (DownloadFile dlFile : dlFiles) writeDlFileToXml(writer, dlFile); // end <nzb> element writer.write(newline); writer.write("</nzb>"); // flush and close file writer.flush(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
From source file:hudson.Util.java
/** * Escapes non-ASCII characters in URL./* w w w .j a v a2 s . c om*/ * * <p> * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters, * such as '#'. * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only * a single path component to that method (it will encode /, but this method does not). */ public static String encode(String s) { try { boolean escaped = false; StringBuilder out = new StringBuilder(s.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(buf, "UTF-8"); for (int i = 0; i < s.length(); i++) { int c = s.charAt(i); if (c < 128 && c != ' ') { out.append((char) c); } else { // 1 char -> UTF8 w.write(c); w.flush(); for (byte b : buf.toByteArray()) { out.append('%'); out.append(toDigit((b >> 4) & 0xF)); out.append(toDigit(b & 0xF)); } buf.reset(); escaped = true; } } return escaped ? out.toString() : s; } catch (IOException e) { throw new Error(e); // impossible } }