List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * {@code connect} is for forming the secure connection between server and * android, sending and receiving of the data. * /*from w w w . j av a 2s .c o m*/ * @param arg0 * data which is to be sent to server. * * @return data in string format, received from the server. */ public String connect(String... arg0) { int nrOfDataToSendToServer = arg0.length; nrOfDataToSendToServer = nrOfDataToSendToServer - 1; boolean valid = false; String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig; try { //Creating the server certificate Certificate serverCertificate = getServerCertificate(); KeyStore keyStore = getKeyStore(serverCertificate); TrustManagerFactory tmf = getTrustManager(keyStore); SSLContext sslContext = getSSLContext(tmf); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier); // Converting the data into JSONObject JSONObject obj = new JSONObject(); for (int i = 0; i <= nrOfDataToSendToServer; i++) { obj.put("param" + i, arg0[i]); } // Converting the JSONObject into string String dataToSend = obj.toString(); KeyPairGenerator keyGen = getKeyPairGenerator(); KeyPair keyPair = keyGen.generateKeyPair(); //Public key for verifying the digital signature PublicKey clientPublicKeySig = keyPair.getPublic(); //Private key for signing the data PrivateKey clientPrivateKeySig = keyPair.getPrivate(); // Get signed data String sigData = getDataSig(clientPrivateKeySig, dataToSend); // Creating URL Format String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8"); urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "=" + URLEncoder.encode(dataToSend, "UTF-8"); urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "=" + URLEncoder.encode(sigData, "UTF-8"); // Sending the data to the server OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(urlData); wr.flush(); wr.close(); // Receiving the data from server BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + "\n"); // sb.append(line); } String text = sb.toString(); reader.close(); // Extracting the data, public key and signature received from // server Vector<String> storeExtractedValues = new Vector<String>(); storeExtractedValues = extractDataFromJson(text, "data"); dataFromServer = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig"); serverPublicKeySigStr = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverDataSig"); serverDataSig = storeExtractedValues.get(0); // Converting the Server Public key format to Java compatible from PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr); // Verify the received data valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig); // Disconnect the url connection urlConnection.disconnect(); if (dataFromServer.equalsIgnoreCase("unverified")) { CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED; return "-1"; } else if (valid == false) { CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED; return "-1"; } else { return dataFromServer; } } catch (Exception e) { CExceptionHandling.ExceptionMsg = e.getMessage(); if (e.toString().equals("java.net.SocketException: Network unreachable")) { CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION; } else if (e.toString().equals( "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) { CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT; } else { CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS; } return "-1"; } }
From source file:connection.HttpReq.java
@Override protected String doInBackground(HttpReqPkg... params) { URL url;/*from ww w . j ava2s . c o m*/ BufferedReader reader = null; String username = params[0].getUsername(); String password = params[0].getPassword(); String authStringEnc = null; if (username != null && password != null) { String authString = username + ":" + password; byte[] authEncBytes; authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT); authStringEnc = new String(authEncBytes); } String uri = params[0].getUri(); if (params[0].getMethod().equals("GET")) { uri += "?" + params[0].getEncodedParams(); } try { StringBuilder sb; // create the HttpURLConnection url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (authStringEnc != null) { connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT") || params[0].getMethod().equals("DELETE")) { // enable writing output to this url connection.setDoOutput(true); } if (params[0].getMethod().equals("POST")) { connection.setRequestMethod("POST"); } else if (params[0].getMethod().equals("GET")) { connection.setRequestMethod("GET"); } else if (params[0].getMethod().equals("PUT")) { connection.setRequestMethod("PUT"); } else if (params[0].getMethod().equals("DELETE")) { connection.setRequestMethod("DELETE"); } // give it x seconds to respond connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.setRequestProperty("Content-Type", contentType); for (int i = 0; i < headerMap.size(); i++) { connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i)); } connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length); connection.connect(); if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) { OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); String httpParams = params[0].getEncodedParams(); if (contentType.equals(OptimusHTTP.CONTENT_TYPE_JSON)) { httpParams = httpParams.replace("=", " "); } writer.write(httpParams); writer.flush(); writer.close(); } // read the output from the server InputStream in; resCode = connection.getResponseCode(); resMsg = connection.getResponseMessage(); if (resCode != HttpURLConnection.HTTP_OK) { in = connection.getErrorStream(); } else { in = connection.getInputStream(); } reader = new BufferedReader(new InputStreamReader(in)); sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } sb.append(resCode).append(" : ").append(resMsg); return sb.toString(); } catch (Exception e) { listener.onFailure(Integer.toString(resCode) + " : " + resMsg); e.printStackTrace(); } finally { // close the reader; this can throw an exception too, so // wrap it in another try/catch block. if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return null; }
From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java
public String SendPost(String httpURL, String data, String _cookie) throws IOException { URL url = new URL(httpURL); //URL url = new URL("http://zoff.cc/xx.cgi"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true);/*from w w w .j a va 2s .c o m*/ connection.setRequestProperty("Connection", "Keep-Alive"); //System.out.println("C=" + _cookie); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10"); connection.setRequestProperty("Cookie", _cookie); connection.connect(); if (data != "") { OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(data); out.flush(); out.close(); } // Save Cookie BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()), HTMLDownloader.default_buffer_size); String headerName = null; //_cookies.clear(); if (_cookie == "") { for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) { if (headerName.equalsIgnoreCase("Set-Cookie")) { String cookie = connection.getHeaderField(i); _cookie += cookie.substring(0, cookie.indexOf(";")) + "; "; } } } // Get HTML from Server String getData = ""; String decodedString; while ((decodedString = in.readLine()) != null) { getData += decodedString + "\n"; } in.close(); return getData; }
From source file:cc.twittertools.download.AsyncEmbeddedJsonStatusBlockCrawler.java
public void fetch() throws IOException { long start = System.currentTimeMillis(); LOG.info("Processing " + file); int cnt = 0;//from w ww . j a v a 2s . c o m BufferedReader data = null; try { data = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line; while ((line = data.readLine()) != null) { try { String[] arr = line.split("\t"); long id = Long.parseLong(arr[0]); String username = (arr.length > 1) ? arr[1] : "a"; String url = getUrl(id, username); connections.incrementAndGet(); crawlURL(url, new TweetFetcherHandler(id, username, url, 0, !this.noFollow, line)); cnt++; if (cnt % TWEET_BLOCK_SIZE == 0) { LOG.info(cnt + " requests submitted"); } } catch (NumberFormatException e) { // parseLong continue; } } } catch (IOException e) { e.printStackTrace(); } finally { data.close(); } // Wait for the last requests to complete. LOG.info("Waiting for remaining requests (" + connections.get() + ") to finish!"); for (int i = 0; i < 10; i++) { if (connections.get() == 0) { break; } try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } asyncHttpClient.close(); long end = System.currentTimeMillis(); long duration = end - start; LOG.info("Total request submitted: " + cnt); LOG.info(crawl.size() + " tweets fetched in " + duration + "ms"); LOG.info("Writing tweets..."); int written = 0; OutputStreamWriter out = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(output)), "UTF-8"); for (Map.Entry<Long, String> entry : crawl.entrySet()) { written++; out.write(entry.getValue() + "\n"); } out.close(); LOG.info(written + " statuses written."); if (this.repair != null) { LOG.info("Writing repair data file..."); written = 0; out = new OutputStreamWriter(new FileOutputStream(repair), "UTF-8"); for (Map.Entry<Long, String> entry : crawl_repair.entrySet()) { written++; out.write(entry.getValue() + "\n"); } out.close(); LOG.info(written + " statuses need repair."); } LOG.info("Done!"); }
From source file:com.doomy.padlock.MainActivity.java
public void androidDebugBridge(String mPort) { Runtime mRuntime = Runtime.getRuntime(); Process mProcess = null;/*from w w w .j a va 2 s .c o m*/ OutputStreamWriter mWrite = null; try { mProcess = mRuntime.exec("su"); mWrite = new OutputStreamWriter(mProcess.getOutputStream()); mWrite.write("setprop service.adb.tcp.port " + mPort + "\n"); mWrite.flush(); mWrite.write("stop adbd\n"); mWrite.flush(); mWrite.write("start adbd\n"); mWrite.flush(); mWrite.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java
@Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { try {/*from ww w .j ava 2 s. c om*/ final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer); String expandedUrl = formatter.format(url); String querystring = ""; if (!params.isEmpty()) { querystring = params.entrySet().stream().map( e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue())) .collect(Collectors.joining("&")); expandedUrl = expandedUrl.concat("?").concat(querystring); } StringBuffer callDump = new StringBuffer(); callDump.append("Performing RestCallOperation " + name).append("\n ").append("URL: ") .append(expandedUrl); URL requestUrl = new URL(expandedUrl); HttpURLConnection httpURLConnection; if (truststorePath != null && expandedUrl.startsWith("https://")) { httpURLConnection = openSecureConnection(requestUrl); } else { httpURLConnection = (HttpURLConnection) requestUrl.openConnection(); } callDump.append("\n ").append("Method: " + method); callDump.append("\n ").append("Connection timeout: " + connectionTimeout); callDump.append("\n ").append("Read timeout: " + readTimeout); httpURLConnection.setRequestMethod(method); httpURLConnection.setConnectTimeout(connectionTimeout); httpURLConnection.setReadTimeout(readTimeout); for (Entry<String, String> header : headers.entrySet()) { String k = formatter.format(header.getKey()); String v = formatter.format(header.getValue()); httpURLConnection.setRequestProperty(k, v); callDump.append("\n ").append("Header: " + k + "=" + v); if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) { body = querystring; } } if (sendGVBufferObject && gvBuffer.getObject() != null) { byte[] requestData; if (gvBuffer.getObject() instanceof byte[]) { requestData = (byte[]) gvBuffer.getObject(); } else { requestData = gvBuffer.getObject().toString().getBytes(); } httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length)); callDump.append("\n ").append("Content-Length: " + requestData.length); callDump.append("\n ").append("Request body: binary"); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(requestData); dataOutputStream.flush(); dataOutputStream.close(); } else if (Objects.nonNull(body) && body.length() > 0) { String expandedBody = formatter.format(body); callDump.append("\n ").append("Request body: " + expandedBody); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); outputStreamWriter.write(expandedBody); outputStreamWriter.flush(); outputStreamWriter.close(); } httpURLConnection.connect(); InputStream responseStream = null; try { httpURLConnection.getResponseCode(); responseStream = httpURLConnection.getInputStream(); } catch (IOException connectionFail) { responseStream = httpURLConnection.getErrorStream(); } for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) { if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) { gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()), header.getValue().stream().collect(Collectors.joining(";"))); } } if (responseStream != null) { byte[] responseData = IOUtils.toByteArray(responseStream); String responseContentType = Optional .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse(""); if (responseContentType.startsWith("application/json") || responseContentType.startsWith("application/javascript")) { gvBuffer.setObject(new String(responseData, "UTF-8")); } else { gvBuffer.setObject(responseData); } } else { // No content gvBuffer.setObject(null); } gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode())); gvBuffer.setProperty(RESPONSE_MESSAGE, Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL")); httpURLConnection.disconnect(); } catch (Exception exc) { throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } return gvBuffer; }
From source file:nl.welteninstituut.tel.la.importers.fitbit.FitbitTask.java
public String postUrl(String url, String data, String authorization) { StringBuilder result = new StringBuilder(); try {//from w w w . j av a 2 s . c o m URLConnection conn = new URL(url).openConnection(); // conn.setConnectTimeout(30); conn.setDoOutput(true); if (authorization != null) conn.setRequestProperty("Authorization", "Basic " + new String(new Base64().encode(authorization.getBytes()))); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } wr.close(); rd.close(); } catch (Exception e) { } return result.toString(); }
From source file:it.flavianopetrocchi.jpdfbookmarks.JPdfBookmarks.java
private void dump() { IBookmarksConverter pdf = fatalGetConverterAndOpenPdf(inputFilePath); resetPasswords();/*from w w w. j a va 2s . c o m*/ Dumper dumper = new Dumper(pdf, indentationString, pageSeparator, attributesSeparator); if (outputFilePath == null) { dumper.printBookmarksIterative(new OutputStreamWriter(System.out)); } else { File f = new File(outputFilePath); if (!f.exists() || getYesOrNo(Res.getString("WARNING_OVERWRITE_CMD"))) { FileOutputStream fos = null; try { fos = new FileOutputStream(outputFilePath); OutputStreamWriter outStream = new OutputStreamWriter(fos, charset); dumper.printBookmarksIterative(outStream); outStream.close(); pdf.close(); } catch (FileNotFoundException ex) { fatalOpenFileError(outputFilePath); } catch (UnsupportedEncodingException ex) { //already checked in command line parsing } catch (IOException ex) { } } } }
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
private byte[] newRequest() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final OutputStreamWriter osw = new OutputStreamWriter(baos, "US-ASCII"); int add = 16; int num = 0;// w w w . j a v a 2 s .c o m for (int i = 0; i < 16384; i += add) { if (++add == 32) { add = 16; } osw.write(getHeader("field" + (num++))); osw.flush(); for (int j = 0; j < i; j++) { baos.write((byte) j); } osw.write("\r\n"); } osw.write(getFooter()); osw.close(); return baos.toByteArray(); }
From source file:fr.irit.sparql.Proxy.SparqlProxy.java
public boolean storeDataString(StringBuilder query) throws SparqlQueryMalFormedException, SparqlEndpointUnreachableException { boolean ret = true; SparqlProxy.cleanString(query);//from w w w . jav a 2 s. c om HttpURLConnection connection = null; try { 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 (UnsupportedEncodingException ex) { throw new SparqlQueryMalFormedException("Encoding unsupported"); } catch (MalformedURLException ex) { throw new SparqlQueryMalFormedException("Query malformed"); } catch (IOException ex) { throw new SparqlEndpointUnreachableException(ex); } finally { if (connection != null) { connection.disconnect(); } } return ret; }