List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:org.apache.zeppelin.markdown.PegdownWebSequencelPlugin.java
public static String createWebsequenceUrl(String style, String content) { style = StringUtils.defaultString(style, "default"); OutputStreamWriter writer = null; BufferedReader reader = null; String webSeqUrl = ""; try {/*from ww w. j av a 2 s. co m*/ String query = new StringBuilder().append("style=").append(style).append("&message=") .append(URLEncoder.encode(content, "UTF-8")).append("&apiVersion=1").toString(); URL url = new URL(WEBSEQ_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); writer.write(query); writer.flush(); StringBuilder response = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = reader.readLine()) != null) { response.append(line); } writer.close(); reader.close(); String json = response.toString(); int start = json.indexOf("?png="); int end = json.indexOf("\"", start); if (start != -1 && end != -1) { webSeqUrl = WEBSEQ_URL + "/" + json.substring(start, end); } } catch (IOException e) { throw new RuntimeException("Failed to get proper response from websequencediagrams.com", e); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(reader); } return webSeqUrl; }
From source file:och.util.FileUtil.java
public static String readFile(FileInputStream fis, String charset) throws UnsupportedEncodingException, IOException { InputStreamReader r = null;//from ww w . ja v a 2s .c o m OutputStreamWriter w = null; try { r = new InputStreamReader(fis, charset); ByteArrayOutputStream out = new ByteArrayOutputStream(); w = new OutputStreamWriter(out, charset); char[] buff = new char[1024 * 4]; int i; while ((i = r.read(buff)) > 0) { w.write(buff, 0, i); } w.flush(); return out.toString(charset); } finally { if (r != null) try { r.close(); } catch (Exception e) { e.printStackTrace(); } if (w != null) try { w.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.apache.hadoop.hive.ql.io.orc.FileDump.java
static void printJsonData(Configuration conf, String filename) throws IOException, JSONException { Path path = new Path(filename); Reader reader = OrcFile.createReader(path.getFileSystem(conf), path); PrintStream printStream = System.out; OutputStreamWriter out = new OutputStreamWriter(printStream, "UTF-8"); RecordReader rows = reader.rows(null); Object row = null;//from www.j a v a2s . c om List<OrcProto.Type> types = reader.getTypes(); while (rows.hasNext()) { row = rows.next(row); JSONWriter writer = new JSONWriter(out); printObject(writer, row, types, 0); out.write("\n"); out.flush(); if (printStream.checkError()) { throw new IOException("Error encountered when writing to stdout."); } } }
From source file:objective.taskboard.followup.FollowUpHelper.java
public static void toJsonFile(FollowUpData data, File file) { Gson gson = new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter()) .setPrettyPrinting().create(); try (OutputStream stream = new FileOutputStream(file)) { OutputStreamWriter writer = new OutputStreamWriter(stream); gson.toJson(data, writer);//from w w w. j a v a2 s . c o m writer.flush(); } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java
/** * * @param httpParam//from w w w . ja v a 2 s.c o m * @return */ public static SimpleHttpResult httpRequest(SimpleHttpParam httpParam) { String url = httpParam.getUrl(); Map<String, Object> parameters = httpParam.getParameters(); String sMethod = httpParam.getMethod(); String charSet = httpParam.getCharSet(); boolean sslVerify = httpParam.isSslVerify(); int maxResultSize = httpParam.getMaxResultSize(); Map<String, Object> headers = httpParam.getHeaders(); int readTimeout = httpParam.getReadTimeout(); int connectTimeout = httpParam.getConnectTimeout(); boolean ignoreContentIfUnsuccess = httpParam.isIgnoreContentIfUnsuccess(); boolean hostnameVerify = httpParam.isHostnameVerify(); TrustKeyStore trustKeyStore = httpParam.getTrustKeyStore(); ClientKeyStore clientKeyStore = httpParam.getClientKeyStore(); if (url == null || url.trim().length() == 0) { throw new IllegalArgumentException("invalid url : " + url); } if (maxResultSize <= 0) { throw new IllegalArgumentException("maxResultSize must be positive : " + maxResultSize); } Charset.forName(charSet); HttpURLConnection urlConn = null; URL destURL = null; String baseUrl = url.trim(); if (!baseUrl.toLowerCase().startsWith(HTTPS_PREFIX) && !baseUrl.toLowerCase().startsWith(HTTP_PREFIX)) { baseUrl = HTTP_PREFIX + baseUrl; } String method = null; if (sMethod != null) { method = sMethod.toUpperCase(); } if (method == null || !(method.equals(HTTP_METHOD_POST) || method.equals(HTTP_METHOD_GET))) { throw new IllegalArgumentException("invalid http method : " + method); } int index = baseUrl.indexOf("?"); if (index > 0) { baseUrl = urlEncode(baseUrl, charSet); } else if (index == 0) { throw new IllegalArgumentException("invalid url : " + url); } String queryString = mapToQueryString(parameters, charSet); String targetUrl = ""; if (method.equals(HTTP_METHOD_POST)) { targetUrl = baseUrl; } else { if (index > 0) { targetUrl = baseUrl + "&" + queryString; } else { targetUrl = baseUrl + "?" + queryString; } } try { destURL = new URL(targetUrl); urlConn = (HttpURLConnection) destURL.openConnection(); setSSLSocketFactory(urlConn, sslVerify, hostnameVerify, trustKeyStore, clientKeyStore); boolean hasContentType = false; boolean hasUserAgent = false; for (String key : headers.keySet()) { if ("Content-Type".equalsIgnoreCase(key)) { hasContentType = true; } if ("user-agent".equalsIgnoreCase(key)) { hasUserAgent = true; } } if (!hasContentType) { headers.put("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet); } if (!hasUserAgent) { headers.put("user-agent", "PlatSystem"); } if (headers != null && !headers.isEmpty()) { for (Entry<String, Object> entry : headers.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); List<String> values = makeStringList(value); for (String v : values) { urlConn.addRequestProperty(key, v); } } } urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setAllowUserInteraction(false); urlConn.setUseCaches(false); urlConn.setRequestMethod(method); urlConn.setConnectTimeout(connectTimeout); urlConn.setReadTimeout(readTimeout); if (method.equals(HTTP_METHOD_POST)) { String postData = queryString.length() == 0 ? httpParam.getPostData() : queryString; if (postData != null && postData.trim().length() > 0) { OutputStream os = urlConn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, charSet); osw.write(postData); osw.flush(); osw.close(); } } int responseCode = urlConn.getResponseCode(); Map<String, List<String>> responseHeaders = urlConn.getHeaderFields(); String contentType = urlConn.getContentType(); SimpleHttpResult result = new SimpleHttpResult(responseCode); result.setHeaders(responseHeaders); result.setContentType(contentType); if (responseCode != 200 && ignoreContentIfUnsuccess) { return result; } InputStream is = urlConn.getInputStream(); byte[] temp = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int readBytes = is.read(temp); while (readBytes > 0) { baos.write(temp, 0, readBytes); readBytes = is.read(temp); } String resultString = new String(baos.toByteArray(), charSet); //new String(buffer.array(), charSet); baos.close(); result.setContent(resultString); return result; } catch (Exception e) { logger.warn("connection error : " + e.getMessage()); return new SimpleHttpResult(e); } finally { if (urlConn != null) { urlConn.disconnect(); } } }
From source file:com.themodernway.server.core.io.IO.java
public static final long copy(final Reader input, final OutputStream output) throws IOException { final OutputStreamWriter writer = new OutputStreamWriter(output, UTF_8_CHARSET); final long length = IOUtils.copyLarge(input, writer); writer.flush(); return length; }
From source file:com.themodernway.server.core.io.IO.java
public static final long copy(final Reader input, final OutputStream output, long length) throws IOException { if ((length = Math.max(0L, length)) > 0L) { final OutputStreamWriter writer = new OutputStreamWriter(output, UTF_8_CHARSET); length = IOUtils.copyLarge(input, writer, 0L, length); writer.flush(); }//from w w w .ja v a 2 s . c o m return length; }
From source file:com.denimgroup.threadfix.service.defects.RestUtils.java
public static InputStream postUrl(String urlString, String data, String username, String password) { URL url = null;// w ww. j av a2 s .co m try { url = new URL(urlString); } catch (MalformedURLException e) { log.warn("URL used for POST was bad: '" + urlString + "'"); return null; } HttpURLConnection httpConnection = null; OutputStreamWriter outputWriter = null; try { httpConnection = (HttpURLConnection) url.openConnection(); setupAuthorization(httpConnection, username, password); httpConnection.addRequestProperty("Content-Type", "application/json"); httpConnection.addRequestProperty("Accept", "application/json"); httpConnection.setDoOutput(true); outputWriter = new OutputStreamWriter(httpConnection.getOutputStream()); outputWriter.write(data); outputWriter.flush(); InputStream is = httpConnection.getInputStream(); return is; } catch (IOException e) { log.warn("IOException encountered trying to post to URL with message: " + e.getMessage()); if (httpConnection == null) { log.warn( "HTTP connection was null so we cannot do further debugging of why the HTTP request failed"); } else { try { InputStream errorStream = httpConnection.getErrorStream(); if (errorStream == null) { log.warn("Error stream from HTTP connection was null"); } else { log.warn( "Error stream from HTTP connection was not null. Attempting to get response text."); String postErrorResponse = IOUtils.toString(errorStream); log.warn("Error text in response was '" + postErrorResponse + "'"); } } catch (IOException e2) { log.warn("IOException encountered trying to read the reason for the previous IOException: " + e2.getMessage(), e2); } } } finally { if (outputWriter != null) { try { outputWriter.close(); } catch (IOException e) { log.warn("Failed to close output stream in postUrl.", e); } } } return null; }
From source file:IOUtil.java
/** * Serialize chars from a <code>String</code> to bytes on an <code>OutputStream</code>, and * flush the <code>OutputStream</code>. * @param bufferSize Size of internal buffer to use. *//*from w ww .j av a2 s .com*/ public static void copy(final String input, final OutputStream output, final int bufferSize) throws IOException { final StringReader in = new StringReader(input); final OutputStreamWriter out = new OutputStreamWriter(output); copy(in, out, bufferSize); // NOTE: Unless anyone is planning on rewriting OutputStreamWriter, we have to flush // here. out.flush(); }
From source file:IOUtil.java
/** * Serialize chars from a <code>Reader</code> to bytes on an <code>OutputStream</code>, and * flush the <code>OutputStream</code>. * @param bufferSize Size of internal buffer to use. *///from w w w .ja v a2 s. c o m public static void copy(final Reader input, final OutputStream output, final int bufferSize) throws IOException { final OutputStreamWriter out = new OutputStreamWriter(output); copy(input, out, bufferSize); // NOTE: Unless anyone is planning on rewriting OutputStreamWriter, we have to flush // here. out.flush(); }