List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java
/** * The method is synchronized since the caching seems to have issues upon mult-threaded caching * @param overwrite if true, it would overwrite the values on cache *///from w w w. ja va 2 s. c om public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception { String viewsConnected = Arrays.toString(viewsToAdd); String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", ""); ConcurrentMap<String, byte[]> concurrentMap = (db != null) ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen() : null; String key = DigestUtils.sha1Hex(str + views); if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) { byte[] taByte = concurrentMap.get(key); return SerializationHelper.deserializeTextAnnotationFromBytes(taByte); } else { URL obj = new URL(url + ":" + port + "/annotate"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); con.setDoOutput(true); con.setUseCaches(false); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views); wr.flush(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); BufferedReader in = new BufferedReader(reader); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); reader.close(); wr.close(); con.disconnect(); TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString()); if (concurrentMap != null) { concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta)); this.db.commit(); } return ta; } }
From source file:org.apache.openejb.server.cli.StreamManager.java
private void write(final OutputStreamWriter writer, final String s) { for (final String l : s.split(lineSep)) { try {/*from w ww . j av a 2 s . c o m*/ writer.write(l); writer.write(lineSep); writer.flush(); } catch (IOException e) { // ignored } } }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchObject() { T object = null;//w ww.jav a2s. c om try { final StringBuilder sb = new StringBuilder(); sb.append(urlStr); sb.append("/"); sb.append(action); final Gson gson = new Gson(); final String bodyParamsString = gson.toJson(bodyParams); final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); conn.addRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(bodyParamsString); wr.flush(); final StringWriter writer = new StringWriter(); final InputStream in = conn.getInputStream(); IOUtils.copy(in, writer); in.close(); wr.close(); final String jsonString = writer.toString(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONObject jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d"); object = (T) gson.fromJson(jsonRootArray.toString(), typeOfClass); android.util.Log.d("JSON", jsonRootArray.toString()); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return object; }
From source file:com.oxiane.maven.xqueryMerger.Merger.java
@Override public void execute() throws MojoExecutionException { Path sourceRootPath = inputSources.toPath(); Path destinationRootPath = outputDirectory.toPath(); IOFileFilter filter = buildFilter(); Iterator<File> it = FileUtils.iterateFiles(inputSources, filter, FileFilterUtils.directoryFileFilter()); if (!it.hasNext()) { getLog().warn("No file found matching " + filter.toString() + " in " + inputSources.getAbsolutePath()); }/*from w ww. j a v a 2 s . c o m*/ while (it.hasNext()) { File sourceFile = it.next(); Path fileSourcePath = sourceFile.toPath(); Path relativePath = sourceRootPath.relativize(fileSourcePath); getLog().debug("[Merger] found source: " + fileSourcePath.toString()); getLog().debug("[Merger] relative path is " + relativePath.toString()); StreamSource source = new StreamSource(sourceFile); XQueryMerger merger = new XQueryMerger(source); merger.setMainQuery(); File destinationFile = destinationRootPath.resolve(relativePath).toFile(); getLog().debug("[Merger] destination will be " + destinationFile.getAbsolutePath()); try { String result = merger.merge(); destinationFile.getParentFile().mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destinationFile), merger.getEncoding()); osw.write(result); osw.flush(); osw.close(); getLog().debug("[Merger] " + relativePath.toString() + " merged into " + destinationFile.getAbsolutePath()); } catch (ParsingException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException("Merge of " + sourceFile.getAbsolutePath() + " fails", ex); } catch (FileNotFoundException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException( "Unable to create destination " + destinationFile.getAbsolutePath(), ex); } catch (IOException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException("While writing " + destinationFile.getAbsolutePath(), ex); } } }
From source file:NetUtils.java
/** * Encode a path as required by the URL specificatin (<a href="http://www.ietf.org/rfc/rfc1738.txt"> * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according * to the <code>x-www-form-urlencoded</code> MIME format. * * @param path the path to encode/*from ww w. j ava 2 s. co m*/ * @return the encoded path */ public static String encodePath(String path) { // stolen from org.apache.catalina.servlets.DefaultServlet ;) /** * Note: This code portion is very similar to URLEncoder.encode. * Unfortunately, there is no way to specify to the URLEncoder which * characters should be encoded. Here, ' ' should be encoded as "%20" * and '/' shouldn't be encoded. */ int maxBytesPerChar = 10; StringBuffer rewrittenPath = new StringBuffer(path.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(buf, "UTF8"); } catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); } for (int i = 0; i < path.length(); i++) { int c = (int) path.charAt(i); if (safeCharacters.get(c)) { rewrittenPath.append((char) c); } else { // convert to external encoding before hex conversion try { writer.write(c); writer.flush(); } catch (IOException e) { buf.reset(); continue; } byte[] ba = buf.toByteArray(); for (int j = 0; j < ba.length; j++) { // Converting each byte in the buffer byte toEncode = ba[j]; rewrittenPath.append('%'); int low = (int) (toEncode & 0x0f); int high = (int) ((toEncode & 0xf0) >> 4); rewrittenPath.append(hexadecimal[high]); rewrittenPath.append(hexadecimal[low]); } buf.reset(); } } return rewrittenPath.toString(); }
From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java
/** * Post data/* ww w .j a va 2s. c o m*/ * * @param url * @param data * @return boolean * @throws IOException */ @Override public boolean post(final String url, final String data) throws IOException { httpURL = new URL(url); final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection(); conn.setDoOutput(true); initConnection(conn); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); } finally { if (writer != null) { try { writer.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } } final int status = conn.getResponseCode(); conn.disconnect(); return status == HttpURLConnection.HTTP_OK; }
From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java
private String httpPost(Map<String, String> requestParams) throws Exception { final URL url = new URL(authUrl); final StringBuilder data = new StringBuilder(); for (String key : requestParams.keySet()) data.append(String.format("%s=%s&", key, requestParams.get(key))); final String dataString = data.toString(); final String formData = dataString.substring(0, dataString.length() - 1); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setDoOutput(true);/*from w ww . ja va2 s. c o m*/ final OutputStream outputStream = connection.getOutputStream(); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(formData); outputStreamWriter.flush(); InputStream is = connection.getResponseCode() != 400 ? connection.getInputStream() : connection.getErrorStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) stringBuffer.append(line); outputStreamWriter.close(); rd.close(); if (connection.getResponseCode() == 400) throw new Exception("error: " + stringBuffer.toString()); return stringBuffer.toString(); }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchArray() { ArrayList<E> array = new ArrayList<E>(); try {/*from w w w . j a va 2 s. co m*/ final StringBuilder sb = new StringBuilder(); sb.append(urlStr); sb.append("/"); sb.append(action); final Gson gson = new Gson(); final String bodyParamsString = gson.toJson(bodyParams); final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("charset", "utf-8"); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(bodyParamsString); wr.flush(); final StringWriter writer = new StringWriter(); final InputStream in = conn.getInputStream(); IOUtils.copy(in, writer); in.close(); wr.close(); final String jsonString = writer.toString(); final ArrayList<E> objectList = new ArrayList<E>(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONArray jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d").getJSONArray(liste); android.util.Log.d("JSON", jsonRootArray.toString()); for (int i = 0; i < jsonRootArray.length(); i++) { objectList.add(gson.fromJson(jsonRootArray.getJSONObject(i).toString(), typeOfClass)); } array = objectList; } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return (T) array; }
From source file:de.rub.syssec.saaf.analysis.steps.reporting.STReportGenerator.java
private void writeToFile(File reportFile, String result) throws IOException { reportFile.createNewFile();/*from w ww. j av a2s. c o m*/ FileOutputStream os = new FileOutputStream(reportFile); OutputStreamWriter writer = new OutputStreamWriter(os, Charset.forName("utf-8")); writer.write(result); writer.flush(); writer.close(); }
From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesRetriever.java
private static JSONArray retrieveTimeSeriesPOST(String urlString, long startEpoch, long endEpoch, String metric, HashMap<String, String> tags) throws OpenTSDBException { urlString = urlString + API_METHOD;/*from w w w.ja va 2 s . c o m*/ String result = ""; try { HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString); OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream()); JSONObject mainObject = new JSONObject(); mainObject.put("start", startEpoch); mainObject.put("end", endEpoch); JSONArray queryArray = new JSONArray(); JSONObject queryParams = new JSONObject(); queryParams.put("aggregator", "sum"); queryParams.put("metric", metric); queryArray.put(queryParams); if (tags != null) { JSONObject queryTags = new JSONObject(); Iterator<Entry<String, String>> entries = tags.entrySet().iterator(); while (entries.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) entries.next(); queryTags.put((String) entry.getKey(), (String) entry.getValue()); } queryParams.put("tags", queryTags); } mainObject.put("queries", queryArray); String queryString = mainObject.toString(); wr.write(queryString); wr.flush(); wr.close(); result = TimeSeriesUtility.readHttpResponse(httpConnection); } catch (IOException e) { throw new OpenTSDBException("Unable to connect to server", e); } catch (JSONException e) { throw new OpenTSDBException("Error on request data", e); } return TimeSeriesUtility.makeResponseJSONArray(result); }