List of usage examples for java.io OutputStreamWriter write
public void write(int c) throws IOException
From source file:graphene.rest.ws.impl.ExportGraphRSImpl.java
@Override public Response exportGraphAsJSON(@QueryParam("fileName") final String fileName, @QueryParam("fileExt") final String fileExt, @QueryParam("username") final String username, @QueryParam("timeStamp") final String timeStamp, // this is the // client // timestamp in // millisecs as a string final String graphJSONdata) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(outputStream); // DEBUG//from w w w. j a va2 s. c o m logger.debug("exportGraphAsJSON: fileName = " + fileName + ", fileExt = " + fileExt + ", graphJSONdata length = " + graphJSONdata.length()); try { writer.write(graphJSONdata); } catch (final IOException e) { logger.error("exportGraphAsJSON: Exception writing JSON"); logger.error(e.getMessage()); } try { writer.close(); outputStream.flush(); outputStream.close(); } catch (final java.io.IOException ioe) { logger.error("exportGraphAsJSON: I/O Exception when attempting to close output. Details " + ioe.getMessage()); } // Create the file on the Web Server File file = null; ServletContext servletContext = null; try { servletContext = globals.getServletContext(); } catch (final Exception se) { logger.error("exportGraphAsJSON: ServletContext is null."); } String path = null; final String serverfileName = "GraphExport" + "_" + username + "_" + timeStamp + "_" + fileName + fileExt; if (servletContext != null) { path = servletContext.getRealPath("/"); } // TODO - get the path from the servlerContext or the request param // TODO the file should be placed under the webserver's dir if (path == null) { // TODO - handle case if the Server is Linux instead of Windows path = "C:/Windows/Temp"; // Temp hack } // DEBUG logger.debug("exportGraphAsJSON: file path = " + path); try { file = new File(path, serverfileName); // file.mkdirs(); final FileOutputStream fout = new FileOutputStream(file); fout.write(outputStream.toByteArray()); fout.close(); String finalPath = file.toURI().toString(); finalPath = finalPath.replace("file:/", ""); // remove leading // DEBUG // logger.debug("exportGraphAsJSON: file toURI = " + finalPath); final ResponseBuilder response = Response.ok(finalPath); response.type("text/plain"); final Response responseOut = response.build(); return responseOut; } catch (final Exception fe) { logger.error( "exportGraphAsJSON: Failed to create file for export. Details: " + fe.getLocalizedMessage()); } return null; }
From source file:connection.HttpReq.java
@Override protected String doInBackground(HttpReqPkg... params) { URL url;//from ww w .j ava 2 s . 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.roche.iceboar.demo.JnlpServlet.java
/** * This method handle all HTTP requests for *.jnlp files (defined in web.xml). Method check, is name correct * (allowed), read file from disk, replace #{codebase} (it's necessary to be generated based on where application * is deployed), #{host} () and write to the response. * <p>/* www .ja v a 2s . c o m*/ * You can use this class in your code for downloading JNLP files. * Return a content of requested jnlp file in response. * * @throws IOException when can't close some stream */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String contextPath = request.getContextPath(); String requestURI = request.getRequestURI(); String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String codebase = host + contextPath; String filename = StringUtils.removeStart(requestURI, contextPath); response.setContentType("application/x-java-jnlp-file"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "-1"); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream()); InputStream in = JnlpServlet.class.getResourceAsStream(filename); if (in == null) { error(response, "Can't open: " + filename); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { line = line.replace("#{codebase}", codebase); line = line.replace("#{host}", host); out.write(line); out.write("\n"); line = reader.readLine(); } out.flush(); out.close(); reader.close(); }
From source file:com.example.kjpark.smartclass.NoticeTab.java
@Override public void onActivityResult(int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != Activity.RESULT_OK) return;/*from w w w.java2 s. c o m*/ switch (requestCode) { case BOARD_NOTICE: { Log.d(TAG, "BOARD_NOTICE called"); loadBoards(); ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { String title = data.getStringExtra("title"); @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL("http://165.194.104.22:5000/send_gcm"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //implement below code if token is send to server con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); String parameter = URLEncoder.encode("title", "UTF-8") + "=" + URLEncoder.encode(title, "UTF-8"); parameter += "&" + URLEncoder.encode("board_type", "UTF-8") + "=" + URLEncoder.encode("notice", "UTF-8"); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(parameter); wr.flush(); if (con.getResponseCode() == 200) { Log.d(TAG, "---- success ----"); } else { Log.d(TAG, "---- failed ----"); } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Boolean value) { } }); ConnectServer.getInstance().execute(); } } }
From source file:com.intranet.intr.inbox.SupControllerInbox.java
@RequestMapping("Inboxphp.htm") public ModelAndView Inboxphp(ModelAndView mav, Principal principal) { String name = principal.getName(); List<correoNoLeidos> lta = null; int numTodoscorreosNum = 0; Map<String, String> datosEnv = new HashMap<String, String>(); datosEnv.put("nombre", "pepe"); datosEnv.put("apellido", "Gonzalez"); Gson gson = new Gson(); String jsonOutput = gson.toJson(datosEnv); try {//from w ww .j av a 2s . c o m //Usamos URLencode para poder enviar la cadena jsonOutput = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(jsonOutput, "UTF-8"); //Establecemos la conexion y enviamos los datos URL url = new URL("http://localhost/php/index.php"); URLConnection con = (URLConnection) url.openConnection(); con.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonOutput); wr.flush(); //Recibimos los datos BufferedReader recv = new BufferedReader(new InputStreamReader(con.getInputStream())); //Los mostramos por pantalla String s = recv.readLine(); while (s != null) { System.out.println(s); s = recv.readLine(); } } catch (Exception ex) { } //ModelAndView mav=new ModelAndView(); String r = validaInterfacesRoles.valida(); mav.addObject("menu", r); mav.addObject("numCT", numTodoscorreosNum); mav.addObject("lta", lta); mav.setViewName("Inbox"); return mav; }
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. * //www. j a v a2s .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:at.gv.egiz.bku.binding.DataUrlConnectionImpl.java
@Override public void transmit(SLResult slResult) throws IOException { log.trace("Sending data."); if (urlEncoded) { ///*from w w w. jav a 2 s .c o m*/ // application/x-www-form-urlencoded (legacy, SL < 1.2) // OutputStream os = connection.getOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(os, HttpUtil.DEFAULT_CHARSET); // ResponseType streamWriter.write(FORMPARAM_RESPONSETYPE); streamWriter.write("="); streamWriter.write(URLEncoder.encode(DEFAULT_RESPONSETYPE, "UTF-8")); streamWriter.write("&"); // XMLResponse / Binary Response if (slResult.getResultType() == SLResultType.XML) { streamWriter.write(DataUrlConnection.FORMPARAM_XMLRESPONSE); } else { streamWriter.write(DataUrlConnection.FORMPARAM_BINARYRESPONSE); } streamWriter.write("="); streamWriter.flush(); URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter); slResult.writeTo(new StreamResult(urlEnc), false); urlEnc.flush(); // transfer parameters char[] cbuf = new char[512]; int len; for (HTTPFormParameter formParameter : httpFormParameter) { streamWriter.write("&"); streamWriter.write(URLEncoder.encode(formParameter.getName(), "UTF-8")); streamWriter.write("="); InputStreamReader reader = new InputStreamReader(formParameter.getData(), (formParameter.getCharSet() != null) ? formParameter.getCharSet() : "UTF-8"); // assume request was // application/x-www-form-urlencoded, // formParam therefore UTF-8 while ((len = reader.read(cbuf)) != -1) { urlEnc.write(cbuf, 0, len); } urlEnc.flush(); } streamWriter.close(); } else { // // multipart/form-data (conforming to SL 1.2) // ArrayList<Part> parts = new ArrayList<Part>(); // ResponseType StringPart responseType = new StringPart(FORMPARAM_RESPONSETYPE, DEFAULT_RESPONSETYPE, "UTF-8"); responseType.setTransferEncoding(null); parts.add(responseType); // XMLResponse / Binary Response SLResultPart slResultPart = new SLResultPart(slResult, XML_RESPONSE_ENCODING); if (slResult.getResultType() == SLResultType.XML) { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); slResultPart.setCharSet(XML_RESPONSE_ENCODING); } else { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); } parts.add(slResultPart); // transfer parameters for (HTTPFormParameter formParameter : httpFormParameter) { InputStreamPartSource source = new InputStreamPartSource(null, formParameter.getData()); FilePart part = new FilePart(formParameter.getName(), source, formParameter.getContentType(), formParameter.getCharSet()); part.setTransferEncoding(formParameter.getTransferEncoding()); parts.add(part); } OutputStream os = connection.getOutputStream(); Part.sendParts(os, parts.toArray(new Part[parts.size()]), boundary.getBytes()); os.close(); } // MultipartRequestEntity PostMethod InputStream is = null; try { is = connection.getInputStream(); } catch (IOException iox) { log.info("Failed to get InputStream of HTTPUrlConnection.", iox); } log.trace("Reading response."); response = new DataUrlResponse(url.toString(), connection.getResponseCode(), is); Map<String, String> responseHttpHeaders = new HashMap<String, String>(); Map<String, List<String>> httpHeaders = connection.getHeaderFields(); for (Iterator<String> keyIt = httpHeaders.keySet().iterator(); keyIt.hasNext();) { String key = keyIt.next(); StringBuffer value = new StringBuffer(); for (String val : httpHeaders.get(key)) { value.append(val); value.append(HttpUtil.SEPARATOR[0]); } String valString = value.substring(0, value.length() - 1); if ((key != null) && (value.length() > 0)) { responseHttpHeaders.put(key, valString); } } response.setResponseHttpHeaders(responseHttpHeaders); }
From source file:MegaHandler.java
private String api_request(String data) { HttpURLConnection connection = null; try {/* w ww . ja v a 2 s . c o m*/ String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number; if (sid != null) urlString += "&sid=" + sid; URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); //use post method connection.setDoOutput(true); //we will send stuff connection.setDoInput(true); //we want feedback connection.setUseCaches(false); //no caches connection.setAllowUserInteraction(false); connection.setRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); try { OutputStreamWriter wr = new OutputStreamWriter(out); wr.write("[" + data + "]"); //data is JSON object containing the api commands wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the output stream if (out != null) out.close(); } InputStream in = connection.getInputStream(); StringBuffer response = new StringBuffer(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); //close the reader } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the input stream if (in != null) in.close(); } return response.toString().substring(1, response.toString().length() - 1); } catch (IOException e) { e.printStackTrace(); } return ""; }
From source file:URLEncoder.java
public String encode(String path) { int maxBytesPerChar = 10; int caseDiff = ('a' - 'A'); StringBuffer rewrittenPath = new StringBuffer(path.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); OutputStreamWriter writer = null; try {//from w w w . j av a2s . c o m 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((char) 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: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 v a2s.com 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; }