List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:dbf.parser.pkg2.handler.java
private void sendPost(String json) throws Exception { System.out.println("Adding url .."); String url = "http://shorewindowcleaning:withwindows@ironside.ddns.net:5984/shorewindowcleaning/_bulk_docs"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); //con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Type", "application/json"); String basicAuth = "Basic " + new String(new Base64().encode(obj.getUserInfo().getBytes())); con.setRequestProperty("Authorization", basicAuth); //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; System.out.println("Adding output .."); // Send post request con.setDoOutput(true);/*www . ja va2 s . c o m*/ OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(json); wr.flush(); wr.close(); System.out.println("geting content .."); // System.out.println(con.getResponseMessage()); int responseCode = con.getResponseCode(); System.out.println("Adding checking response .."); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + json); System.out.println("Response Code : " + responseCode); System.out.println(con.getResponseMessage()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); }
From source file:com.google.firebase.auth.migration.AuthMigrator.java
private Task<String> exchangeToken(final String legacyToken) { if (legacyToken == null) { return Tasks.forResult(null); }//from w w w . j av a2 s . com return Tasks.call(Executors.newCachedThreadPool(), new Callable<String>() { @Override public String call() throws Exception { JSONObject postBody = new JSONObject(); postBody.put("token", legacyToken); HttpURLConnection connection = (HttpURLConnection) exchangeEndpoint.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("POST"); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); try { osw.write(postBody.toString()); osw.flush(); } finally { osw.close(); } int responseCode = connection.getResponseCode(); InputStream is; if (responseCode >= 400) { is = connection.getErrorStream(); } else { is = connection.getInputStream(); } try { byte[] buffer = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int numRead = 0; while ((numRead = is.read(buffer)) >= 0) { baos.write(buffer, 0, numRead); } JSONObject resultObject = new JSONObject(new String(baos.toByteArray())); if (responseCode != 200) { throw new FirebaseWebRequestException( resultObject.getJSONObject("error").getString("message"), responseCode); } return resultObject.getString("token"); } finally { is.close(); } } }); }
From source file:org.apache.uima.ruta.resource.TreeWordList.java
private void writeUncompressedMTWLFile(TextNode root, String path, String encoding) throws IOException { FileOutputStream output = new FileOutputStream(path); OutputStreamWriter writer = new OutputStreamWriter(output, encoding); writeTWLFile(root, writer);//w w w . j av a 2s. com writer.close(); }
From source file:at.lame.hellonzb.parser.NzbParser.java
/** * This method is called to save the currently loaded parser data * to a file (to be loaded later on).//from ww w . ja v a2 s.com * * @param logger The central logger object * @param counter File(name) counter * @param filename File name to use * @param dlFiles The vector of DownloadFile to write * @return Success status (true or false) */ public synchronized static boolean saveParserData(MyLogger logger, int counter, String filename, Vector<DownloadFile> dlFiles) { String newline = System.getProperty("line.separator"); if (dlFiles.size() < 1) return true; try { String datadirPath = System.getProperty("user.home") + "/.HelloNzb/"; // create home directory File datadir = new File(datadirPath); if (datadir.exists()) { if (datadir.isFile()) { logger.msg("Can't create data directory: " + datadirPath, MyLogger.SEV_ERROR); return false; } } else datadir.mkdirs(); File file = new File(datadirPath, counter + "-" + filename + ".nzb"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); // XML header writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); writer.write(newline); // XML doctype writer.write("<!DOCTYPE nzb PUBLIC \"-//newzBin//DTD NZB 1.0//EN\" " + "\"http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd\">"); writer.write(newline); // HelloNzb signature line writer.write("<!-- NZB generated by HelloNzb, the Binary Usenet tool -->"); writer.write(newline); // XML namespace writer.write("<nzb xmlns=\"http://www.newzbin.com/DTD/2003/nzb\">"); writer.write(newline); writer.write(newline); // now write all files passed to this method for (DownloadFile dlFile : dlFiles) writeDlFileToXml(writer, dlFile); // end <nzb> element writer.write(newline); writer.write("</nzb>"); // flush and close file writer.flush(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
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();/*w w w. jav a2s. c om*/ bos.flush(); 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:com.google.ytd.picasa.PicasaApiHelper.java
public String getResumableUploadUrl(com.google.ytd.model.PhotoEntry photoEntry, String title, String description, String albumId, Double latitude, Double longitude) throws IllegalArgumentException { LOG.info(String.format("Resumable upload request.\nTitle: %s\nDescription: %s\nAlbum: %s", title, description, albumId));// w ww .j av a 2 s. co m // Picasa API resumable uploads are not currently documented publicly, but they're essentially // the same as what YouTube API offers: // http://code.google.com/apis/youtube/2.0/developers_guide_protocol_resumable_uploads.html // The Java client library does offer support for resumable uploads, but its use of threads // and some other assumptions makes it unsuitable for our purposes. try { URL url = new URL(String.format(RESUMABLE_UPLOADS_URL_FORMAT, albumId)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("POST"); // Set all the GData request headers. These strings should probably be moved to CONSTANTS. connection.setRequestProperty("Content-Type", "application/atom+xml;charset=UTF-8"); connection.setRequestProperty("Authorization", String.format("AuthSub token=\"%s\"", adminConfigDao.getAdminConfig().getPicasaAuthSubToken())); connection.setRequestProperty("GData-Version", "2.0"); connection.setRequestProperty("Slug", photoEntry.getOriginalFileName()); connection.setRequestProperty("X-Upload-Content-Type", photoEntry.getFormat()); connection.setRequestProperty("X-Upload-Content-Length", String.valueOf(photoEntry.getOriginalFileSize())); // If we're given lat/long then create the element to geotag the picture; otherwise, pass in // and empty string for no geotag. String geoRss = ""; if (latitude != null && longitude != null) { geoRss = String.format(GEO_RSS_XML_FORMAT, latitude, longitude); LOG.info("Geo RSS XML: " + geoRss); } String atomXml = String.format(UPLOAD_ENTRY_XML_FORMAT, StringEscapeUtils.escapeXml(title), StringEscapeUtils.escapeXml(description), geoRss); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(atomXml); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { String uploadUrl = connection.getHeaderField("Location"); if (util.isNullOrEmpty(uploadUrl)) { throw new IllegalArgumentException("No Location header found in HTTP response."); } else { LOG.info("Resumable upload URL is " + uploadUrl); return uploadUrl; } } else { LOG.warning(String.format("HTTP POST to %s returned status %d (%s).", url.toString(), connection.getResponseCode(), connection.getResponseMessage())); } } catch (MalformedURLException e) { LOG.log(Level.WARNING, "", e); throw new IllegalArgumentException(e); } catch (IOException e) { LOG.log(Level.WARNING, "", e); } return null; }
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 ww w .jav a 2 s . c o 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);//from w ww . ja v a 2 s . c om 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.sun.identity.console.user.model.UMChangeUserPasswordModelImpl.java
private byte[] getBytes(char[] charArr) { try {/*from w ww .j a v a 2 s .co m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = null; try { outputStreamWriter = new OutputStreamWriter(baos); outputStreamWriter.write(charArr, 0, charArr.length); } finally { if (outputStreamWriter != null) { outputStreamWriter.close(); } } return baos.toByteArray(); } catch (IOException ex) { throw new RuntimeException("Could not convert char[] to byte[]", ex); } }
From source file:de.fahrgemeinschaft.FahrgemeinschaftConnector.java
@Override public String publish(Ride offer) throws Exception { HttpURLConnection post;//www . j ava2 s . c om 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(); }