List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java
public String getAuthToken(String apiEndPoint, String encodedCliAndSecret) { //receives : apiEndPoint (https://api.test.sabre.com) //encodedCliAndSecret : base64Encode( base64Encode(V1:[user]:[group]:[domain]) + ":" + base64Encode([secret]) ) String strRet = null;/*from w w w . j a v a 2 s . co m*/ try { URL urlConn = new URL(apiEndPoint + "/v1/auth/token"); URLConnection conn = urlConn.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Authorization", "Basic " + encodedCliAndSecret); conn.setRequestProperty("Accept", "application/json"); //send request DataOutputStream dataOut = new DataOutputStream(conn.getOutputStream()); dataOut.writeBytes("grant_type=client_credentials"); dataOut.flush(); dataOut.close(); //get response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strChunk = ""; StringBuilder sb = new StringBuilder(); while (null != ((strChunk = rd.readLine()))) sb.append(strChunk); //parse the token JSONObject respParser = new JSONObject(sb.toString()); strRet = respParser.getString("access_token"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return strRet; }
From source file:com.base2.kagura.core.authentication.RestAuthentication.java
public InputStream httpPost(String suffix, HashMap<String, String> values) { try {/* w ww . j av a 2 s .com*/ URL obj = new URL(url + "/" + suffix); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); String data = new ObjectMapper().writeValueAsString(values); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode != 200) throw new Exception("Got error code: " + responseCode); return con.getInputStream(); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:identify.SendMessage.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w. java 2s. c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException { String sender = request.getParameter("sender"); String receiver = request.getParameter("receiver"); String message = request.getParameter("body"); int index = SaveToken.storage.findUsername(receiver); System.out.println(index); String tokenTo = SaveToken.storage.getData().get(index).getToken(); JSONObject obj = new JSONObject(); obj.put("sender", sender); obj.put("receiver", receiver); obj.put("body", message); JSONObject arrayObj = new JSONObject(); arrayObj.put("to", tokenTo); arrayObj.put("data", obj); System.out.println(arrayObj.toString()); String USER_AGENT = "Mozilla/5.0"; String authKey = "key=AIzaSyBPldzkpB5YtLm3N8cYbdoweqtn5Dk3IfQ"; String contentType = "application/json"; String url = "https://fcm.googleapis.com/fcm/send"; URL connection = new URL(url); HttpURLConnection con = (HttpURLConnection) connection.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("Content-Type", contentType); con.setRequestProperty("Authorization", authKey); String urlParameters = arrayObj.toString(); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder resp = new StringBuilder(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine); } in.close(); String acrHeaders = request.getHeader("Access-Control-Request-Headers"); String acrMethod = request.getHeader("Access-Control-Request-Method"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", acrHeaders); response.setHeader("Access-Control-Allow-Methods", acrMethod); response.setContentType("application/json:charset=UTF-8"); response.getWriter().write(resp.toString()); }
From source file:org.apache.hadoop.hdfs.TestDFSRename.java
@Test public void testRename() throws Exception { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); try {/* ww w. java 2s .c o m*/ FileSystem fs = cluster.getFileSystem(); assertTrue(fs.mkdirs(dir)); { //test lease Path a = new Path(dir, "a"); Path aa = new Path(dir, "aa"); Path b = new Path(dir, "b"); createFile(fs, a); //should not have any lease assertEquals(0, countLease(cluster)); DataOutputStream aa_out = fs.create(aa); aa_out.writeBytes("something"); //should have 1 lease assertEquals(1, countLease(cluster)); list(fs, "rename0"); fs.rename(a, b); list(fs, "rename1"); aa_out.writeBytes(" more"); aa_out.close(); list(fs, "rename2"); //should not have any lease assertEquals(0, countLease(cluster)); } { // test non-existent destination Path dstPath = new Path("/c/d"); assertFalse(fs.exists(dstPath)); assertFalse(fs.rename(dir, dstPath)); } { // dst cannot be a file or directory under src // test rename /a/b/foo to /a/b/c Path src = new Path("/a/b"); Path dst = new Path("/a/b/c"); createFile(fs, new Path(src, "foo")); // dst cannot be a file under src assertFalse(fs.rename(src, dst)); // dst cannot be a directory under src assertFalse(fs.rename(src.getParent(), dst.getParent())); } { // dst can start with src, if it is not a directory or file under src // test rename /test /testfile Path src = new Path("/testPrefix"); Path dst = new Path("/testPrefixfile"); createFile(fs, src); assertTrue(fs.rename(src, dst)); } { // dst should not be same as src test rename /a/b/c to /a/b/c Path src = new Path("/a/b/c"); createFile(fs, src); assertTrue(fs.rename(src, src)); assertFalse(fs.rename(new Path("/a/b"), new Path("/a/b/"))); assertTrue(fs.rename(src, new Path("/a/b/c/"))); } fs.delete(dir, true); } finally { if (cluster != null) { cluster.shutdown(); } } }
From source file:org.perfcake.reporting.destination.Client.java
public long createTestExecution(TestExec te) throws Exception { Long id = null;//www.ja v a 2 s.co m HttpURLConnection conn = (HttpURLConnection) urlCreate.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Basic " + authorizationHeader); conn.setRequestProperty("Content-Type", "text/xml"); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(te.toXml()); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); if (responseCode == 201) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = in.readLine(); id = Long.parseLong(response); te.setId(id); in.close(); } else { //TODO ERROR } conn.disconnect(); return id; }
From source file:logout2_servlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w w w . ja v a 2s . co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String access_token = ""; Cookie cookie = null; Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie cookie1 = cookies[i]; if (cookies[i].getName().equals("access_token")) { access_token = cookie1.getValue(); cookie = cookie1; } } System.out.println("TOKEN = " + access_token); String USER_AGENT = "Mozilla/5.0"; String url = "http://localhost:8082/Identity_Service/logout_servlet"; URL connection = new URL(url); HttpURLConnection con = (HttpURLConnection) connection.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "access_token=" + access_token; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder resp = new StringBuilder(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine); } in.close(); JSONParser parser = new JSONParser(); JSONObject obj = null; try { obj = (JSONObject) parser.parse(resp.toString()); } catch (ParseException ex) { Logger.getLogger(logout2_servlet.class.getName()).log(Level.SEVERE, null, ex); } String status = (String) obj.get("status"); System.out.println(status); if (status.equals("ok")) { cookie.setMaxAge(0); response.sendRedirect("login.jsp"); } else { } }
From source file:org.kuali.rice.rest.test.RestTest.java
public String request(String requestMethod, String location, String queryContent, String token, String contentType) throws Exception { String responseJSON = null;//from ww w. j a va2 s. com URL url; HttpURLConnection connection = null; //Create connection if (requestMethod.equalsIgnoreCase("post") || requestMethod.equalsIgnoreCase("put")) { url = new URL(location); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(requestMethod.toUpperCase()); connection.setRequestProperty("Content-Type", contentType); if (StringUtils.isNotBlank(token)) { connection.setRequestProperty("Authorization", "bearer " + token); } connection.setRequestProperty("Content-Length", "" + Integer.toString(queryContent.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(queryContent); wr.flush(); wr.close(); } else { url = new URL(location + "?" + queryContent); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(requestMethod.toUpperCase()); connection.setRequestProperty("Accept-Language", "en-US"); connection.setRequestProperty("Accept", "*/*"); if (StringUtils.isNotBlank(token)) { connection.setRequestProperty("Authorization", "bearer " + token); } } //Successful responses start with 2 if (!Integer.toString(connection.getResponseCode()).startsWith("2")) { return "" + connection.getResponseCode(); } //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); responseJSON = response.toString(); return responseJSON; }
From source file:fr.Axeldu18.PterodactylAPI.Methods.POSTMethods.java
public String call(String methodURL, String data) { try {//from w w w.java 2 s . c o m URL url = new URL(methodURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); String hmac = main.getPublicKey() + "." + main.hmac(methodURL + data); System.out.println("DEBUG CALL: " + methodURL); System.out.println("DEBUG CALL2: " + methodURL + data); System.out.println("DEBUG CALL3: " + hmac); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Pterodactyl Java-API"); connection.setRequestProperty("Authorization", "Bearer " + hmac.replaceAll("\n", "")); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return main.readResponse(connection.getInputStream()).toString(); } else { return main.readResponse(connection.getErrorStream()).toString(); } } catch (Exception e) { main.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); return null; } }
From source file:org.openhim.mediator.engine.connectors.MLLPConnector.java
private void sendRequest(final MediatorSocketRequest req) { try {// w w w . j a v a 2 s. c o m final Socket socket = getSocket(req); ExecutionContext ec = getContext().dispatcher(); Future<String> f = future(new Callable<String>() { public String call() throws IOException { DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeBytes(wrapMLLP(req.getBody())); String result = readMLLPStream(socket.getInputStream()); if (isMLLPWrapped(result)) { result = result.substring(1).substring(0, result.length() - 3); } else { log.warning("Response from server is not valid MLLP"); } return result; } }, ec); f.onComplete(new OnComplete<String>() { @Override public void onComplete(Throwable throwable, String result) throws Throwable { try { if (throwable != null) { throw throwable; } MediatorSocketResponse response = new MediatorSocketResponse(req, result); req.getRespondTo().tell(response, getSelf()); //enrich engine response CoreResponse.Orchestration orch = buildOrchestration(req, response); req.getRequestHandler().tell(new AddOrchestrationToCoreResponse(orch), getSelf()); } catch (Exception ex) { req.getRequestHandler().tell(new ExceptError(ex), getSelf()); } finally { IOUtils.closeQuietly(socket); } } }, ec); } catch (IOException | UnsupportedOperationException ex) { req.getRequestHandler().tell(new ExceptError(ex), getSelf()); } }
From source file:jackwu.com.gasprice.GCMService.RegistrationIntentService.java
/** * Persist registration to third-party servers. * * Modify this method to associate the user's GCM registration token with any server-side account * maintained by your application.// w ww . java 2s .c o m * * @param token The new token. */ private void sendRegistrationToServer(String token, String device_id) throws Exception { // Add custom implementation, as needed. HttpURLConnection urlConnection = null; URL url = null; String parameter = "device_id=" + device_id; String parameter2 = "gcm_regid=" + token; try { url = new URL(getString(R.string.server_address_register)); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/x-www.form-urlencoded"); urlConnection.setRequestProperty("Content-Language", "en-US"); urlConnection.setUseCaches(false); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream()); dos.writeBytes(parameter); dos.writeBytes(parameter2); dos.flush(); dos.close(); int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (!response.toString().equals("success")) { throw new Exception("not success"); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }