List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:fi.hip.sicx.store.HIPStoreClient.java
@Override public boolean checkFile(String cloudFile, StorageClientObserver sco) { boolean ok = false; HttpURLConnection conn = null; try {// w w w . ja va2s . com String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8"); conn = getConnection("/store/list"); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); String inp = readInput(conn); JSONObject json = new JSONObject(inp); if (inp.length() > 10) ok = true; JSONArray arr = json.getJSONArray("elements"); for (int i = 0; !ok && i < arr.length(); i++) { JSONObject o = arr.getJSONObject(i); if (o.getString("path").equals(cloudFile)) ok = true; } } catch (Exception e) { e.printStackTrace(); failed = true; } closeConnection(conn); return ok; }
From source file:org.geotools.data.sfs.SFSDataStore.java
/** * This method requests the response from the URL either through GET/POST * and returns the response as a stream//www . j av a2 s .c o m * The request is going to be a POST one if postData is not null, a GET otherwise * @param is * @return String * @throws IOException */ InputStream resourceToStream(String resource, String postData) throws MalformedURLException, IOException, ProtocolException { boolean doPost = false; URL url; if (postData != null && (baseURL.length() + resource.length() + postData.length() < 2048)) { url = new URL(baseURL + resource + "?" + postData); } else { url = new URL(baseURL + resource); } // TODO: use commons http client + persistent connections instead HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Accept-Encoding", "gzip"); // if we have username/password use them to setup basic auth if (user != null && password != null) { String combined = nullToEmpty(user) + ":" + nullToEmpty(password); byte[] authBytes = combined.getBytes("US-ASCII"); String encoded = new String(Base64.encodeBase64(authBytes)); urlConnection.setRequestProperty("Authorization", "Basic " + encoded); } // enforce the timeout if we have one if (timeout > 0) { urlConnection.setConnectTimeout(timeout); urlConnection.setReadTimeout(timeout); } urlConnection.setDoInput(true); if (doPost && postData != null && !"".equals(postData.trim())) { urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setDoOutput(true); /*write the data to server*/ OutputStreamWriter wr = null; try { wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(postData); wr.flush(); } finally { if (wr != null) { wr.close(); } } } else { urlConnection.setRequestMethod("GET"); } /* Get the response from the server*/ if (urlConnection.getResponseCode() != 200) { throw new IOException("Server reported and error with code " + urlConnection.getResponseCode() + ": " + urlConnection.getResponseMessage() + " accessing resource " + url.toExternalForm()); } else { InputStream is = urlConnection.getInputStream(); String encoding = urlConnection.getContentEncoding(); if ("gzip".equalsIgnoreCase(encoding)) { is = new GZIPInputStream(is); } return is; } }
From source file:be.solidx.hot.test.TestScriptExecutors.java
@Test public void testScriptEncodingGroovy() throws Exception { Script<CompiledScript> script = new Script<CompiledScript>( IOUtils.toByteArray(getClass().getResourceAsStream("/frenchScript.groovy")), "french"); FileOutputStream fileOutputStream = new FileOutputStream(new File("testiso.txt")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bos, "ISO8859-1"); groovyScriptExecutor.execute(script, outputStreamWriter); outputStreamWriter.flush(); bos.flush();//from w ww. j a v a 2 s . c om ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(outputStream, "ISO8859-1"); writer.append(new String(bos.toByteArray(), "iso8859-1")); writer.flush(); writer.close(); fileOutputStream.write(outputStream.toByteArray()); fileOutputStream.close(); new File("testiso.txt").delete(); }
From source file:AIR.Common.Web.HttpWebHelper.java
public String getResponse(String urlString, String postRequestParams, String contentMimeType) throws Exception { try {/* w ww . j a v a 2s . c o m*/ URL url = new URL(urlString); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Content-Type", String.format("application/%s; charset=UTF-8", contentMimeType)); urlConn.setUseCaches(false); // the request will return a response urlConn.setDoInput(true); // set request method to POST urlConn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream()); writer.write(postRequestParams); writer.flush(); // reads response, store line by line in an array of Strings BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuffer bfr = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { bfr.append(line + "\n"); } reader.close(); writer.close(); urlConn.disconnect(); return bfr.toString(); } catch (Exception exp) { StringWriter strn = new StringWriter(); exp.printStackTrace(new PrintWriter(strn)); _logger.error(strn.toString()); exp.printStackTrace(); throw new Exception(exp); } }
From source file:fi.hip.sicx.store.HIPStoreClient.java
/** * Gets a file stored in the cloud and saves to a local disk. * // w w w.j a va 2 s.c o m * @param cloudFile The file in the cloud that is to be saved. * @param localOutFile The saved file name. * @return true if file saved successfully, otherwise false */ @Override public boolean getFile(String cloudFile, String localOutFile, StorageClientObserver sco) { boolean ok = false; HttpURLConnection conn = null; try { String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8"); conn = getConnection("/store/fetch"); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); long total = conn.getContentLength(); long sent = 0; System.out.println("content len is " + total); FileOutputStream out = new FileOutputStream(localOutFile); byte[] buf = new byte[1024 * 64]; int r = 0; while ((r = in.read(buf)) > -1) { out.write(buf, 0, r); sent += r; sco.progressMade((int) ((sent * 100) / total)); } out.close(); ok = true; } } catch (Exception e) { e.printStackTrace(); failed = true; } closeConnection(conn); return ok; }
From source file:minikbextractor.SparqlProxy.java
public boolean storeData(StringBuilder query, boolean makeQuery) { boolean ret = true; if (makeQuery) query = SparqlProxy.makeQuery(query); HttpURLConnection connection = null; try {/*from ww w . j a v a 2 s.co m*/ String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8"); URL url = new URL(this.urlServer + "update"); //Create connection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String rep = ""; while ((line = reader.readLine()) != null) { rep += line; } writer.close(); reader.close(); } catch (Exception e) { System.err.println("ERROR UPDATE : " + e); SparqlProxy.saveQueryOnFile("Query.sparql", query.toString()); ret = false; } finally { if (connection != null) { connection.disconnect(); } } return ret; }
From source file:org.modeshape.web.jcr.rest.AbstractRestTest.java
protected Response doPost(JSONObject object, String url) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(byteArrayOutputStream); object.write(writer);/*from w ww . jav a 2s . co m*/ writer.flush(); writer.close(); HttpPost post = newDefaultRequest(HttpPost.class, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), MediaType.APPLICATION_JSON, url); return new Response(post); }
From source file:org.modeshape.web.jcr.rest.AbstractRestTest.java
protected Response doPut(JSONObject request, String url) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(byteArrayOutputStream); request.write(writer);// w ww. j a v a 2s . c o m writer.flush(); writer.close(); HttpPut put = newDefaultRequest(HttpPut.class, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), MediaType.APPLICATION_JSON, url); return new Response(put); }
From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;//from w w w . ja va2s. c o m final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
From source file:de.fahrgemeinschaft.FahrgemeinschaftConnector.java
@Override public String publish(Ride offer) throws Exception { HttpURLConnection post;//from www .j a va 2s . co m if (offer.getRef() == null) { post = (HttpURLConnection) new URL(endpoint + TRIP).openConnection(); post.setRequestMethod(POST); } else { post = (HttpURLConnection) new URL( new StringBuffer().append(endpoint).append(TRIP).append(ID).append(offer.getRef()).toString()) .openConnection(); post.setRequestMethod(PUT); } post.setRequestProperty("User-Agent", USER_AGENT); post.setRequestProperty(APIKEY, Secret.APIKEY); if (getAuth() != null) post.setRequestProperty(AUTHKEY, getAuth()); post.setDoOutput(true); JSONObject json = new JSONObject(); // json.put("Smoker", "no"); json.put(TRIPTYPE, OFFER); json.put(TRIP_ID, offer.getRef()); json.put(ID_USER, get(USER)); if (offer.getMode() != null && offer.getMode().equals(Mode.TRAIN)) { json.put(PLATE, BAHN); } else { json.put(PLATE, offer.get(PLATE)); } if (offer.isActive()) { json.put(RELEVANCE, 10); } else { json.put(RELEVANCE, 0); } json.put(PLACES, offer.getSeats()); json.put(PRICE, offer.getPrice() / 100); json.put(CONTACTMAIL, offer.get(EMAIL)); json.put(CONTACTMOBILE, offer.get(MOBILE)); json.put(CONTACTLANDLINE, offer.get(LANDLINE)); String dep = fulldf.format(offer.getDep()); json.put(STARTDATE, dep.subSequence(0, 8)); json.put(STARTTIME, dep.subSequence(8, 12)); json.put(DESCRIPTION, offer.get(COMMENT)); if (!offer.getDetails().isNull(PRIVACY)) json.put(PRIVACY, offer.getDetails().getJSONObject(PRIVACY)); if (!offer.getDetails().isNull(REOCCUR)) json.put(REOCCUR, offer.getDetails().getJSONObject(REOCCUR)); ArrayList<JSONObject> routings = new ArrayList<JSONObject>(); List<Place> stops = offer.getPlaces(); int max = stops.size() - 1; for (int dest = max; dest >= 0; dest--) { for (int orig = 0; orig < dest; orig++) { int idx = (orig == 0 ? (dest == max ? 0 : dest) : -dest); JSONObject route = new JSONObject(); route.put(ROUTING_INDEX, idx); route.put(ORIGIN, place(stops.get(orig))); route.put(DESTINATION, place(stops.get(dest))); routings.add(route); } } json.put(ROUTINGS, new JSONArray(routings)); OutputStreamWriter out = new OutputStreamWriter(post.getOutputStream()); out.write(json.toString()); out.flush(); out.close(); JSONObject response = loadJson(post); if (!response.isNull(TRIP_ID_WITH_SMALL_t)) { offer.ref(response.getString(TRIP_ID_WITH_SMALL_t)); } return offer.getRef(); }