List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:org.apache.flink.streaming.api.functions.source.SocketTextStreamFunctionTest.java
@Test public void testSocketSourceOutputInfiniteRetries() throws Exception { ServerSocket server = new ServerSocket(0); Socket channel = null;/*from w w w .jav a 2 s.co m*/ try { SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), "\n", -1, 100); SocketSourceThread runner = new SocketSourceThread(source, "test1", "check"); runner.start(); // first connection: nothing channel = server.accept(); channel.close(); // second connection: first string channel = server.accept(); OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream()); writer.write("test1\n"); writer.close(); channel.close(); // third connection: nothing channel = server.accept(); channel.close(); // forth connection: second string channel = server.accept(); writer = new OutputStreamWriter(channel.getOutputStream()); writer.write("check\n"); writer.flush(); runner.waitForNumElements(2); runner.cancel(); runner.waitUntilDone(); } finally { if (channel != null) { IOUtils.closeQuietly(channel); } IOUtils.closeQuietly(server); } }
From source file:com.mycompany.twitterapp.TwitterApp.java
public void saveToFile(long id, String tweet, String user, Orientation orientation) { OutputStreamWriter fileWriter = null; CSVPrinter csvFilePrinter = null;/*www. j a va 2 s. co m*/ CSVFormat csvFileFormat = CSVFormat.DEFAULT; if (tweet != null) { try { fileWriter = new OutputStreamWriter(new FileOutputStream(tweetFileName, true), "UTF-8"); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(id, orientation.name().toLowerCase(), tweet); } catch (IOException ex) { Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!"); e.printStackTrace(); } } } else { try { fileWriter = new OutputStreamWriter(new FileOutputStream(userFileName, true), "UTF-8"); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(id, user, orientation.name().toLowerCase()); } catch (IOException ex) { Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!"); e.printStackTrace(); } } } }
From source file:com.moviejukebox.plugin.AnimatorPlugin.java
/** * Retrieve Animator matching the specified movie name and year. * * This routine is base on a Google request. *//*from ww w . j ava2 s . co m*/ private String getAnimatorId(String movieName, String year) { try { String animatorId = Movie.UNKNOWN; String allmultsId = Movie.UNKNOWN; String sb = movieName; // Unaccenting letters sb = Normalizer.normalize(sb, Normalizer.Form.NFD); // Return simple letters '' & '' sb = sb.replaceAll("" + (char) 774, ""); sb = sb.replaceAll("" + (char) 774, ""); sb = sb.replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); sb = "text=" + URLEncoder.encode(sb, "Cp1251").replace(" ", "+"); // Get ID from animator.ru if (animatorDiscovery) { String uri = "http://www.animator.ru/db/?p=search&SearchMask=1&" + sb; if (StringTools.isValidString(year)) { uri = uri + "&year0=" + year; uri = uri + "&year1=" + year; } String xml = httpClient.request(uri); // Checking for zero results if (xml.contains("[?? ]")) { // It's search results page, searching a link to the movie page int beginIndex; if (-1 != xml.indexOf("? ")) { for (String tmp : HTMLTools.extractTags(xml, "? ", HTML_TD, HTML_HREF, "<br><br>")) { if (0 < tmp.indexOf("[?? ]")) { beginIndex = tmp.indexOf(" .)"); if (beginIndex >= 0) { String year2 = tmp.substring(beginIndex - 4, beginIndex); if (year2.equals(year)) { beginIndex = tmp.indexOf("http://www.animator.ru/db/?p=show_film&fid=", beginIndex); if (beginIndex >= 0) { StringTokenizer st = new StringTokenizer(tmp.substring(beginIndex + 43), " "); animatorId = st.nextToken(); break; } } } } } } } } // Get ID from allmults.org if (multsDiscovery) { URL url = new URL("http://allmults.org/search.php"); URLConnection conn = url.openConnection(YamjHttpClientBuilder.getProxy()); conn.setDoOutput(true); OutputStreamWriter osWriter = null; StringBuilder xmlLines = new StringBuilder(); try { osWriter = new OutputStreamWriter(conn.getOutputStream()); osWriter.write(sb); osWriter.flush(); try (InputStreamReader inReader = new InputStreamReader(conn.getInputStream(), "cp1251"); BufferedReader bReader = new BufferedReader(inReader)) { String line; while ((line = bReader.readLine()) != null) { xmlLines.append(line); } } osWriter.flush(); } finally { if (osWriter != null) { osWriter.close(); } } if (xmlLines.indexOf("<div class=\"post\"") != -1) { for (String tmp : HTMLTools.extractTags(xmlLines.toString(), " ? ", "<ul><li>", "<div class=\"entry\"", "</div>")) { int pos = tmp.indexOf("<img "); if (pos != -1) { int temp = tmp.indexOf(" alt=\""); if (temp != -1) { String year2 = tmp.substring(temp + 6, tmp.indexOf("\"", temp + 6) - 1); year2 = year2.substring(year2.length() - 4); if (year2.equals(year)) { temp = tmp.indexOf(" src=\"/images/multiki/"); if (temp != -1) { allmultsId = tmp.substring(temp + 22, tmp.indexOf(".jpg", temp + 22)); break; } } } } } } } return (animatorId.equals(Movie.UNKNOWN) && allmultsId.equals(Movie.UNKNOWN)) ? Movie.UNKNOWN : animatorId + ":" + allmultsId; } catch (IOException error) { LOG.error("Failed retreiving Animator Id for movie : {}", movieName); LOG.error("Error : {}", error.getMessage()); return Movie.UNKNOWN; } }
From source file:com.norconex.jefmon.ws.JobSuiteProgressJsonPage.java
@Override public void renderPage() { JEFMonConfig monitorConfig = ((JEFMonSession) getSession()).getConfig(); if (monitorConfig == null) { return;/*from w w w . ja v a 2 s .c o m*/ } try { Response response = getRequestCycle().getResponse(); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream()); InstanceSummary instance = InstancesManager.createThisJefMonInstance(); JSONWriter writer = new JSONWriter(out).object().key("name").value(instance.getName()).key("total") .value(instance.getTotalRoots()).key("statuses").object(); for (JobState status : instance.getStatuses().keySet()) { MutableInt value = instance.getStatuses().get(status); if (status == null) { writer.key("").value(value); } else { writer.key(status.toString()).value(value); } } writer.endObject(); writer.endObject(); out.flush(); } catch (IOException e) { throw new WicketRuntimeException("Cannot flush JSON response.", e); } catch (JSONException e) { throw new WicketRuntimeException("Cannot create JSON response.", e); } }
From source file:org.aludratest.cloud.web.report.SqlBean.java
public void download() { FacesContext context = FacesContext.getCurrentInstance(); // export as CSV - directly send to response to save memory, but use gzip encoding if supported HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); String acceptHeader = request.getHeader("Accept-Encoding"); boolean gzipSupported = acceptHeader != null && acceptHeader.contains("gzip"); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("text/csv"); response.setCharacterEncoding("UTF-8"); DateFormat dfFileMarker = new SimpleDateFormat("yyyy-MM-dd_HH-mm"); response.setHeader("Content-Disposition", "attachment; filename=acm-data-" + dfFileMarker.format(new Date()) + ".csv"); if (gzipSupported) { response.setHeader("Content-Encoding", "gzip"); }/*from ww w .j av a 2s. com*/ OutputStream out = null; try { out = response.getOutputStream(); if (gzipSupported) { out = new GZIPOutputStream(out, 2048); } OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); // write header for (String colName : resultColumns) { writer.append(colName).append(";"); } writer.write("\n"); // write data for (Map<String, String> row : resultRows) { for (String key : resultColumns) { String value = row.get(key); if (value != null) { writer.write(value); } writer.write(";"); } writer.write("\n"); } writer.flush(); writer.close(); } catch (IOException e) { // ignore for now } finally { IOUtils.closeQuietly(out); } context.responseComplete(); }
From source file:com.createtank.payments.coinbase.CoinbaseApi.java
private boolean doTokenRequest(Map<String, String> params) throws IOException { Map<String, String> paramsBody = new HashMap<String, String>(); paramsBody.put("client_id", clientId); paramsBody.put("client_secret", clientSecret); paramsBody.putAll(params);// w w w .j a va 2s. c om String bodyStr = RequestClient.createRequestParams(paramsBody); System.out.println(bodyStr); HttpURLConnection conn = (HttpsURLConnection) new URL(OAUTH_BASE_URL + "/token").openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(bodyStr); writer.flush(); writer.close(); int code = conn.getResponseCode(); if (code == 401) { return false; } else if (code != 200) { throw new IOException("Got HTTP response code " + code); } String response = RequestClient.getResponseBody(conn.getInputStream()); JsonParser parser = new JsonParser(); JsonObject content = (JsonObject) parser.parse(response); System.out.print("content: " + content.toString()); accessToken = content.get("access_token").getAsString(); refreshToken = content.get("refresh_token").getAsString(); return true; }
From source file:com.thoughtworks.go.server.dashboard.GoDashboardPipelineGroup.java
public String etag() { try {/* w w w .j av a2 s . c om*/ MessageDigest digest = DigestUtils.getSha256Digest(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter( new DigestOutputStream(new NullOutputStream(), digest)); outputStreamWriter.write(name); outputStreamWriter.write("/"); outputStreamWriter.write(Integer.toString(permissions.hashCode())); outputStreamWriter.write("["); for (Map.Entry<String, GoDashboardPipeline> entry : pipelines.entrySet()) { long lastUpdatedTimeStamp = entry.getValue().getLastUpdatedTimeStamp(); outputStreamWriter.write(entry.getKey()); outputStreamWriter.write(":"); outputStreamWriter.write(Long.toString(lastUpdatedTimeStamp)); } outputStreamWriter.write("]"); outputStreamWriter.flush(); return Hex.encodeHexString(digest.digest()); } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;/*from w w w. j a va2 s.c o m*/ BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:org.apache.sling.tracer.internal.JSONRecording.java
private byte[] toJSON() throws JSONException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = baos;// w ww .j av a 2 s . c o m if (compress) { os = new GZIPOutputStream(os); } OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); JSONWriter jw = new JSONWriter(osw); jw.setTidy(true); jw.object(); jw.key("method").value(method); timeTaken = System.currentTimeMillis() - start; jw.key("time").value(timeTaken); jw.key("timestamp").value(start); addRequestProgressLogs(jw); queryCollector.done(); addJson(jw, "queries", queries); addJson(jw, "logs", logs); jw.endObject(); osw.flush(); os.close(); return baos.toByteArray(); }
From source file:org.intermine.api.mines.HttpRequester.java
@Override public BufferedReader requestURL(final String urlString, final ContentType contentType) { BufferedReader reader = null; OutputStreamWriter writer = null; // TODO: when all friendly mines support mimetype formats then we can remove this. String suffix = "?format=" + contentType.getFormat(); try {// ww w .j ava2 s.c o m URL url = new URL(StringUtils.substringBefore(urlString, "?") + suffix); URLConnection conn = url.openConnection(); conn.addRequestProperty("Accept", contentType.getMimeType()); conn.setConnectTimeout(timeout * 1000); // conn accepts millisecond timeout. if (urlString.contains("?")) { // POST String queryString = StringUtils.substringAfter(urlString, "?"); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(queryString); writer.flush(); LOG.info("FriendlyMine URL (POST) " + urlString); } reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (Exception e) { throw new RuntimeException("Unable to access " + urlString + " exception: " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { LOG.error("Error sending POST request", e); } } } return reader; }