List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//w w w . ja va 2 s.c om * * @param multipart DOCUMENT ME! * @param vcard DOCUMENT ME! * @param charset DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, vCard vcard, String charset) throws MessagingException { String xpath = "/tmp"; String xcontent = vcard.toString(); try { // write the vCard to a temporary file in UTF-8 format File xfile = new File(xpath); FileOutputStream xfos = new FileOutputStream(xfile); OutputStreamWriter xosw = new OutputStreamWriter(xfos, Charset.defaultCharset().displayName()); xosw.write(xcontent, 0, xcontent.length()); xosw.flush(); xosw.close(); xfos.close(); // attach the temporary file to the message attach(multipart, xfile, Charset.defaultCharset().displayName()); } catch (Exception xex) { System.out.println("vCard attachment failed: " + xex.toString()); } }
From source file:org.apache.hadoop.hdfs.qjournal.server.Journal.java
/** * Persist data for recovering the given segment from disk. *///from w w w. j ava 2 s . c o m private void persistPaxosData(long segmentTxId, PersistedRecoveryPaxosData newData) throws IOException { File f = storage.getPaxosFile(segmentTxId); boolean success = false; AtomicFileOutputStream fos = new AtomicFileOutputStream(f); try { newData.writeDelimitedTo(fos); fos.write('\n'); // Write human-readable data after the protobuf. This is only // to assist in debugging -- it's not parsed at all. OutputStreamWriter writer = new OutputStreamWriter(fos, Charsets.UTF_8); writer.write(String.valueOf(newData)); writer.write('\n'); writer.flush(); fos.flush(); success = true; } finally { if (success) { IOUtils.closeStream(fos); } else { fos.abort(); } } }
From source file:at.gv.egiz.bku.binding.DataUrlConnectionImpl.java
@Override public void transmit(SLResult slResult) throws IOException { log.trace("Sending data."); if (urlEncoded) { ///*from ww w. j ava2 s .c o m*/ // application/x-www-form-urlencoded (legacy, SL < 1.2) // OutputStream os = connection.getOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(os, HttpUtil.DEFAULT_CHARSET); // ResponseType streamWriter.write(FORMPARAM_RESPONSETYPE); streamWriter.write("="); streamWriter.write(URLEncoder.encode(DEFAULT_RESPONSETYPE, "UTF-8")); streamWriter.write("&"); // XMLResponse / Binary Response if (slResult.getResultType() == SLResultType.XML) { streamWriter.write(DataUrlConnection.FORMPARAM_XMLRESPONSE); } else { streamWriter.write(DataUrlConnection.FORMPARAM_BINARYRESPONSE); } streamWriter.write("="); streamWriter.flush(); URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter); slResult.writeTo(new StreamResult(urlEnc), false); urlEnc.flush(); // transfer parameters char[] cbuf = new char[512]; int len; for (HTTPFormParameter formParameter : httpFormParameter) { streamWriter.write("&"); streamWriter.write(URLEncoder.encode(formParameter.getName(), "UTF-8")); streamWriter.write("="); InputStreamReader reader = new InputStreamReader(formParameter.getData(), (formParameter.getCharSet() != null) ? formParameter.getCharSet() : "UTF-8"); // assume request was // application/x-www-form-urlencoded, // formParam therefore UTF-8 while ((len = reader.read(cbuf)) != -1) { urlEnc.write(cbuf, 0, len); } urlEnc.flush(); } streamWriter.close(); } else { // // multipart/form-data (conforming to SL 1.2) // ArrayList<Part> parts = new ArrayList<Part>(); // ResponseType StringPart responseType = new StringPart(FORMPARAM_RESPONSETYPE, DEFAULT_RESPONSETYPE, "UTF-8"); responseType.setTransferEncoding(null); parts.add(responseType); // XMLResponse / Binary Response SLResultPart slResultPart = new SLResultPart(slResult, XML_RESPONSE_ENCODING); if (slResult.getResultType() == SLResultType.XML) { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); slResultPart.setCharSet(XML_RESPONSE_ENCODING); } else { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); } parts.add(slResultPart); // transfer parameters for (HTTPFormParameter formParameter : httpFormParameter) { InputStreamPartSource source = new InputStreamPartSource(null, formParameter.getData()); FilePart part = new FilePart(formParameter.getName(), source, formParameter.getContentType(), formParameter.getCharSet()); part.setTransferEncoding(formParameter.getTransferEncoding()); parts.add(part); } OutputStream os = connection.getOutputStream(); Part.sendParts(os, parts.toArray(new Part[parts.size()]), boundary.getBytes()); os.close(); } // MultipartRequestEntity PostMethod InputStream is = null; try { is = connection.getInputStream(); } catch (IOException iox) { log.info("Failed to get InputStream of HTTPUrlConnection.", iox); } log.trace("Reading response."); response = new DataUrlResponse(url.toString(), connection.getResponseCode(), is); Map<String, String> responseHttpHeaders = new HashMap<String, String>(); Map<String, List<String>> httpHeaders = connection.getHeaderFields(); for (Iterator<String> keyIt = httpHeaders.keySet().iterator(); keyIt.hasNext();) { String key = keyIt.next(); StringBuffer value = new StringBuffer(); for (String val : httpHeaders.get(key)) { value.append(val); value.append(HttpUtil.SEPARATOR[0]); } String valString = value.substring(0, value.length() - 1); if ((key != null) && (value.length() > 0)) { responseHttpHeaders.put(key, valString); } } response.setResponseHttpHeaders(responseHttpHeaders); }
From source file:com.akop.bach.parser.Parser.java
protected void writeToFile(String filename, String text) { java.io.OutputStreamWriter osw = null; try {//from ww w . java 2s. co m java.io.FileOutputStream fOut = mContext.openFileOutput(filename, 0666); osw = new java.io.OutputStreamWriter(fOut); osw.write(text); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (osw != null) { try { osw.flush(); osw.close(); } catch (IOException e) { } } } }
From source file:com.wyp.module.controller.LicenseController.java
/** * wslicense/* w w w . j a va 2 s .co m*/ * * @param properties * @return */ private String getCitrixLicense(String requestJson) { String licenses = ""; OutputStreamWriter out = null; InputStream is = null; long start = System.currentTimeMillis(); try { // ws url URL url = new URL(map.get("address")); // ws connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", " application/json"); connection.setRequestMethod("POST"); connection.connect(); out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); out.append(requestJson); out.flush(); // response string is = connection.getInputStream(); int length = is.available(); if (0 < length) { long end = System.currentTimeMillis(); System.out.println("?" + (end - start)); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder tempStr = new StringBuilder(); String temp = ""; while ((temp = reader.readLine()) != null) { tempStr.append(temp); } licenses = tempStr.toString(); // utf-8? System.out.println(licenses); } } catch (IOException e) { String eMsg = e.getMessage(); if ("Read timed out".equals(eMsg) || "Connection timed out: connect".equals(eMsg) || "Software caused connection abort: recv failed".equals(eMsg)) { long end = System.currentTimeMillis(); System.out.println(eMsg + (end - start)); licenses = "TIMEOUT"; } e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (is != null) { is.close(); } } catch (IOException ex) { ex.printStackTrace(); } } System.out.println(licenses); return licenses; }
From source file:com.example.android.networkconnect.MainActivity.java
private String httpstestconnect(String urlString) throws IOException { CookieManager msCookieManager = new CookieManager(); URL url = new URL(urlString); if (url.getProtocol().toLowerCase().equals("https")) { trustAllHosts();//from w w w .j a va 2s.com HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); try { String headerName = null; for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { //data=data+"Header Nme : " + headerName; //data=data+conn.getHeaderField(i); // Log.i (TAG,headerName); Log.i(TAG, headerName + ": " + conn.getHeaderField(i)); } // Map<String, List<String>> headerFields = conn.getHeaderFields(); //List<String> cookiesHeader = headerFields.get("Set-Cookie"); //if(cookiesHeader != null) //{ // for (String cookie : cookiesHeader) // { // msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0)); //} //} } catch (Exception e) { Log.i(TAG, "Erreur Cookie" + e); } conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.setRequestProperty("User-Agent", "e-venement-app/"); //if(msCookieManager.getCookieStore().getCookies().size() > 0) //{ // conn.setRequestProperty("Cookie", // TextUtils.join(",", msCookieManager.getCookieStore().getCookies())); //} // conn= (HttpsURLConnection) url.wait(); ; //(HttpsURLConnection) url.openConnection(); final String password = "android2015@"; OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.getEncoding(); writer.write("&signin[username]=antoine"); writer.write("&signin[password]=android2015@"); //writer.write("&signin[_csrf_token]="+CSRFTOKEN); writer.flush(); //Log.i(TAG,"Writer: "+writer.toString()); // conn.connect(); String data = null; // if (conn.getInputStream() != null) { Log.i(TAG, readIt(conn.getInputStream(), 2500)); data = readIt(conn.getInputStream(), 7500); } // return conn.getResponseCode(); return data; //return readIt(inputStream,1028); } else { return url.getProtocol(); } }
From source file:com.googlecode.CallerLookup.Main.java
public void doUpdate() { showDialog(DIALOG_PROGRESS);//w w w . ja v a 2 s. c o m savePreferences(); new Thread(new Runnable() { @Override public void run() { try { URL uri = new URL(UPDATE_URL); URLConnection urlc = uri.openConnection(); long lastModified = urlc.getLastModified(); if ((lastModified == 0) || (lastModified != mPrefs.getLong(PREFS_UPDATE, 0))) { FileOutputStream file = getApplicationContext().openFileOutput(UPDATE_FILE, MODE_PRIVATE); OutputStreamWriter content = new OutputStreamWriter(file); String tmp; InputStream is = urlc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while ((tmp = br.readLine()) != null) { content.write(tmp + "\n"); } content.flush(); content.close(); file.close(); SharedPreferences.Editor prefsEditor = mPrefs.edit(); prefsEditor.putLong(PREFS_UPDATE, lastModified); prefsEditor.commit(); Message message = mUpdateHandler.obtainMessage(); message.what = MESSAGE_UPDATE_FINISHED; mUpdateHandler.sendMessage(message); } else { Message message = mUpdateHandler.obtainMessage(); message.what = MESSAGE_UPDATE_UNNECESSARY; mUpdateHandler.sendMessage(message); } } catch (MalformedURLException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } } }).start(); }
From source file:org.bankinterface.util.HttpClient.java
private InputStream sendHttpRequestStream(String method, boolean overrideTrust) throws HttpClientException { String arguments = null;/*from ww w . j a v a2 s. com*/ InputStream in = null; if (url == null) { throw new HttpClientException("Cannot process a null URL."); } if (rawStream != null) { arguments = rawStream; } else if (parameters != null) { arguments = urlEncodeArgs(parameters); } // Append the arguments to the query string if GET. if (method.equalsIgnoreCase("get") && arguments != null) { if (url.contains("?")) { url = url + "&" + arguments; } else { url = url + "?" + arguments; } } // Create the URL and open the connection. try { requestUrl = new URL(url); if (overrideTrust) { con = URLConnector.openUntrustedConnection(requestUrl, timeout, clientCertAlias, hostVerification); } else { con = URLConnector.openConnection(requestUrl, timeout, clientCertAlias, hostVerification); } if (logger.isDebugEnabled()) { logger.debug("Connection opened to : " + requestUrl.toExternalForm()); } if ((con instanceof HttpURLConnection)) { ((HttpURLConnection) con).setInstanceFollowRedirects(followRedirects); if (logger.isDebugEnabled()) { logger.debug("Connection is of type HttpURLConnection, more specifically: " + con.getClass().getName()); } } // set the content type if (contentType != null) { con.setRequestProperty("Content-type", contentType); } // connection settings con.setDoOutput(true); con.setUseCaches(false); if (keepAlive) { con.setRequestProperty("Connection", "Keep-Alive"); } if (method.equalsIgnoreCase("post")) { if (contentType == null) { con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); } con.setDoInput(true); } // if there is basicAuth info set the request property for it if (basicAuthUsername != null) { String token = basicAuthUsername + ":" + (basicAuthPassword == null ? "" : basicAuthPassword); String basicAuthString = "Basic " + Base64.encodeBase64String(token.getBytes()); con.setRequestProperty("Authorization", basicAuthString); if (logger.isDebugEnabled()) { logger.debug("Header - Authorization: " + basicAuthString); } } if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { String headerName = entry.getKey(); String headerValue = entry.getValue(); con.setRequestProperty(headerName, headerValue); if (logger.isDebugEnabled()) { logger.debug("Header - " + headerName + ": " + headerValue); } } } if (method.equalsIgnoreCase("post")) { OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), this.streamCharset != null ? this.streamCharset : "UTF-8"); if (logger.isDebugEnabled()) { logger.debug("Opened output stream"); } if (arguments != null) { out.write(arguments); if (logger.isDebugEnabled()) { logger.debug("Wrote arguements (parameters) : " + arguments); } } out.flush(); out.close(); if (logger.isDebugEnabled()) { logger.debug("Flushed and closed buffer"); } } if (logger.isDebugEnabled()) { Map<String, List<String>> headerFields = con.getHeaderFields(); logger.debug("Header Fields : " + headerFields); } in = con.getInputStream(); } catch (IOException ioe) { if ((trustAny && !overrideTrust) && (ioe.getCause() instanceof CertificateException)) { logger.warn("Try again override Trust"); return sendHttpRequestStream(method, true); } throw new HttpClientException("IO Error processing request", ioe); } catch (Exception e) { throw new HttpClientException("Error processing request", e); } return in; }
From source file:com.akop.bach.parser.Parser.java
protected void writeToSd(String filename, String text) { java.io.OutputStreamWriter osw = null; File root = Environment.getExternalStorageDirectory(); try {//from ww w.j a v a 2 s . com java.io.FileOutputStream fOut = new FileOutputStream(root + "/" + filename); osw = new java.io.OutputStreamWriter(fOut); osw.write(text); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (osw != null) { try { osw.flush(); osw.close(); } catch (IOException e) { } } } }
From source file:TargetsAPI.java
/** * Send the POST request to the Wikitude Cloud Targets API. * /*from ww w . j a va 2 s .c om*/ * <b>Remark</b>: We are not using any external libraries for sending HTTP * requests, to be as independent as possible. Libraries like Apache * HttpComponents (included in Android already) make it a lot easier to * interact with HTTP connections. * * @param body * The JSON body that is sent in the request. * @return The response from the server, in JSON format * * @throws IOException * when the server cannot serve the request for any reason, or * anything went wrong during the communication between client * and server. * */ private String sendRequest(String body) throws IOException { BufferedReader reader = null; OutputStreamWriter writer = null; try { // create the URL object from the endpoint URL url = new URL(API_ENDPOINT); // open the connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // use POST and configure the connection connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // set the request headers connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("X-Api-Token", apiToken); connection.setRequestProperty("X-Version", "" + apiVersion); connection.setRequestProperty("Content-Length", String.valueOf(body.length())); // construct the writer and write request writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(body); writer.flush(); // listen on the server response reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // construct the server response and return StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null;) { sb.append(line); } // return the result return sb.toString(); } catch (MalformedURLException e) { // the URL we specified as endpoint was not valid System.err.println("The URL " + API_ENDPOINT + " is not a valid URL"); e.printStackTrace(); return null; } catch (ProtocolException e) { // this should not happen, it means that we specified a wrong // protocol System.err.println("The HTTP method is not valid. Please check if you specified POST."); e.printStackTrace(); return null; } finally { // close the reader and writer try { writer.close(); } catch (Exception e) { // intentionally left blank } try { reader.close(); } catch (Exception e) { // intentionally left blank } } }