List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:io.github.gsteckman.rpi_rest.SubscriptionManager.java
/** * Sends the provided message to the host and port specified in the URL object. * /* www . j a va 2 s .c o m*/ * @param url * Provides the host and port to which the message is sent via TCP. * @param message * The message to send, including all headers and message body. * @throws IOException * If an exception occured writing to the socket. */ private void sendNotify(final URL url, final String message) throws IOException { Socket sock = new Socket(url.getHost(), url.getPort()); OutputStreamWriter out = new OutputStreamWriter(sock.getOutputStream()); out.write(message); out.close(); sock.close(); }
From source file:squash.deployment.lambdas.utils.CloudFormationResponder.java
/** * Sends the custom resource response to the Cloudformation service. * //from w w w .j a v a 2 s .c o m * <p>The response is returned indirectly to Cloudformation via the * presigned Url it provided in its request. * * @param status whether the call succeeded - must be either SUCCESS or FAILED. * @param logger a CloudwatchLogs logger. * @throws IllegalStateException when the responder is uninitialised. */ public void sendResponse(String status, LambdaLogger logger) { if (!initialised) { throw new IllegalStateException("The responder has not been initialised"); } try { rootNode.put("Status", status); rootNode.put("RequestId", requestParameters.get("RequestId")); rootNode.put("StackId", requestParameters.get("StackId")); rootNode.put("LogicalResourceId", requestParameters.get("LogicalResourceId")); rootNode.put("PhysicalResourceId", physicalResourceId); } catch (Exception e) { // Can do nothing more than log the error and return. Must rely on // CloudFormation timing-out since it won't get a response from us. logger.log("Exception caught whilst constructing response: " + e.toString()); return; } // Send the response to CloudFormation via the provided presigned S3 URL logger.log("About to send response to presigned URL: " + requestParameters.get("ResponseURL")); try { URL url = new URL(requestParameters.get("ResponseURL")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); mapper.writeTree(generator, rootNode); String output = cloudFormationJsonResponse.toString(StandardCharsets.UTF_8.name()); logger.log("Response about to be sent: " + output); out.write(output); out.close(); logger.log("Sent response to presigned URL"); int responseCode = connection.getResponseCode(); logger.log("Response Code returned from presigned URL: " + responseCode); } catch (IOException e) { // Can do nothing more than log the error and return. logger.log("Exception caught whilst replying to presigned URL: " + e.toString()); return; } }
From source file:com.amastigote.xdu.query.module.WaterAndElectricity.java
@Override public boolean login(@NotNull String username, @NotNull String password) throws IOException { preLogin();/* w w w . j av a 2 s .co m*/ URL url = new URL(HOST + LOGIN_SUFFIX); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setInstanceFollowRedirects(false); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + ASP_dot_NET_SessionId); httpURLConnection.setRequestProperty("AjaxPro-Method", "getLoginInput"); JSONObject jsonObject = new JSONObject(); jsonObject.put("webName", username); jsonObject.put("webPass", password); httpURLConnection.connect(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); outputStreamWriter.write(jsonObject.toString()); outputStreamWriter.flush(); outputStreamWriter.close(); httpURLConnection.getResponseCode(); httpURLConnection.disconnect(); return checkIsLogin(username); }
From source file:game.Clue.JerseyClient.java
public void requestLogintoServer(String name) { try {// www . jav a 2s . co m for (int i = 0; i < 6; i++) { JSONObject jsonObject = new JSONObject(name); URL url = new URL( "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player" + i); URLConnection connection = url.openConnection(); connection.setDoOutput(true); //setDoOutput(true); connection.setRequestProperty("PUT", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); System.out.println("Sent PUT message for logging into server"); out.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java
/** * Submits data on a HTTP connection/*from w ww. j a v a 2 s . c o m*/ * @param connection a valid, open HTTP connection * @param data the data to submit * @throws IOException when there's some kind of communication problem */ private void sendData(HttpURLConnection connection, String data) throws IOException { OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); out.write(data); out.close(); }
From source file:com.alvexcore.share.ShareExtensionRegistry.java
public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes, String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion, String licenseId) throws Exception { // search for extension DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true);//from w ww . java 2s . c o m xmlBuilder = xmlFact.newDocumentBuilder(); // build query Document queryXML = xmlBuilder.newDocument(); Element rootElement = queryXML.createElement("extension"); queryXML.appendChild(rootElement); Element el = queryXML.createElement("license-id"); el.appendChild(queryXML.createTextNode(licenseId)); rootElement.appendChild(el); el = queryXML.createElement("id"); el.appendChild(queryXML.createTextNode(extensionId)); rootElement.appendChild(el); el = queryXML.createElement("share-version"); el.appendChild(queryXML.createTextNode(shareVersion)); rootElement.appendChild(el); el = queryXML.createElement("repo-version"); el.appendChild(queryXML.createTextNode(repoVersion)); rootElement.appendChild(el); el = queryXML.createElement("share-id"); el.appendChild(queryXML.createTextNode(shareId)); rootElement.appendChild(el); el = queryXML.createElement("repo-id"); el.appendChild(queryXML.createTextNode(repoId)); rootElement.appendChild(el); el = queryXML.createElement("share-files"); rootElement.appendChild(el); for (String fileName : shareHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", shareHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } el = queryXML.createElement("repo-files"); rootElement.appendChild(el); for (String fileName : repoHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", repoHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } // query server try { URL url = new URL( "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // disable host verification conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML), new StreamResult(wr)); wr.close(); // get response Document responseXML = xmlBuilder.parse(conn.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); // get version String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) repoFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) shareFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE)) .getNodeValue(); return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion, shareLatestVersion, repoFiles, shareFiles, motd); } catch (Exception e) { return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "", new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), ""); } }
From source file:com.googlecode.noweco.calendar.test.CalendarClientTest.java
@Test @Ignore/* ww w .j ava2 s. co m*/ public void test() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // if (google || chandlerproject) { // HttpParams params = httpclient.getParams(); // ConnRouteParams.setDefaultProxy(params, new HttpHost("ecprox.bull.fr")); // } HttpEntityEnclosingRequestBase httpRequestBase = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return "PROPFIND"; } }; BasicHttpEntity entity = new BasicHttpEntity(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream); // outputStreamWriter.write( "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:propfind xmlns:D=\"DAV:\"> <D:prop> <D:displayname/> <D:principal-collection-set/> <calendar-home-set xmlns=\"urn:ietf:params:xml:ns:caldav\"/> </D:prop> </D:propfind>"); outputStreamWriter.close(); entity.setContent(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); httpRequestBase.setEntity(entity); httpRequestBase.setURI(new URI("/dav/collection/gael.lalire@bull.com/")); if (google) { httpRequestBase.setURI(new URI("/calendar/dav/gael.lalire@gmail.com/user/")); } if (chandlerproject) { httpRequestBase.setURI(new URI("/dav/collection/8de93530-8796-11e0-82b8-d279848d8f3e")); } if (apple) { httpRequestBase.setURI(new URI("/")); } HttpHost target = new HttpHost("localhost", 8080); if (google) { target = new HttpHost("www.google.com", 443, "https"); } if (chandlerproject) { target = new HttpHost("hub.chandlerproject.org", 443, "https"); } if (apple) { target = new HttpHost("localhost", 8008, "http"); } httpRequestBase.setHeader("Depth", "0"); String userpass = null; if (apple) { userpass = "admin:admin"; } httpRequestBase.setHeader("authorization", "Basic " + Base64.encodeBase64String(userpass.getBytes())); HttpResponse execute = httpclient.execute(target, httpRequestBase); System.out.println(Arrays.deepToString(execute.getAllHeaders())); System.out.println(execute.getStatusLine()); System.out.println(EntityUtils.toString(execute.getEntity())); }
From source file:BRHInit.java
public JSONObject json_rpc(String method, JSONArray params) throws Exception { URLConnection conn = rpc_url.openConnection(); if (cookie != null) conn.addRequestProperty("cookie", cookie); JSONObject request = new JSONObject(); request.put("id", false); request.put("method", method); request.put("params", params); conn.setDoOutput(true);//from w w w . j a v a 2 s . c o m OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); try { wr.write(request.toString()); wr.flush(); } finally { wr.close(); } // Get the response InputStreamReader rd = new InputStreamReader(conn.getInputStream()); try { JSONTokener tokener = new JSONTokener(rd); return (JSONObject) tokener.nextValue(); } finally { rd.close(); } }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchObject() { T object = null;/*from w w w. ja v a2 s . 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.cladonia.xngreditor.URLUtilities.java
public static void save(URL url, InputStream input, String encoding) throws IOException { // System.out.println( "URLUtilities.save( "+url+", "+encoding+")"); String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("ftp")) { FTPClient client = null;/* w ww . j a va2 s . com*/ String host = url.getHost(); client = new FTPClient(); // System.out.println( "Connecting ..."); client.connect(host); // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Disconnecting..."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Writing output ..."); OutputStream output = client.storeFileStream(url.getFile()); // if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) { // output.close(); // client.disconnect(); // throw new IOException( "Could not transfer file \""+url.getFile()+"\"."); // } InputStreamReader reader = new InputStreamReader(input, encoding); OutputStreamWriter writer = new OutputStreamWriter(output, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); output.close(); // Must call completePendingCommand() to finish command. if (!client.completePendingCommand()) { client.disconnect(); throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } else { client.disconnect(); } } else if (protocol.equals("http") || protocol.equals("https")) { WebdavResource webdav = createWebdavResource(toString(url), username, password); if (webdav != null) { webdav.putMethod(url.getPath(), input); webdav.close(); } else { throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } } else if (protocol.equals("file")) { FileOutputStream stream = new FileOutputStream(toFile(url)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding)); InputStreamReader reader = new InputStreamReader(input, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); } else { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } }