List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:fr.Axeldu18.PterodactylAPI.Methods.POSTMethods.java
public String call(String methodURL, String data) { try {//from w w w. j a v a 2 s.c om 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.openxdata.server.servlet.WMDownloadServlet.java
private void downloadForms(HttpServletResponse response, int studyId) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); formDownloadService.downloadForms(studyId, dos, "", ""); baos.flush();/*from ww w . jav a2s .c o m*/ dos.flush(); byte[] data = baos.toByteArray(); baos.close(); dos.close(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); PrintWriter out = response.getWriter(); out.println("<study>"); try { dis.readByte(); //reads the size of the studies while (true) { String value = dis.readUTF(); out.println("<form>" + value + "</form>"); } } catch (EOFException exe) { //exe.printStackTrace(); } out.println("</study>"); out.flush(); dis.close(); }
From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java
public boolean performRequest() { jsonResponseArray = null;//from www . j ava 2 s. com jsonResponseObject = null; HttpURLConnection connection = null; try { // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP. mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject()); byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8"); URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET connection.setDoInput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(mRequestMethod); connection.setUseCaches(false); // For all methods except GET we need to include data in the body. if (mRequestMethod != "GET") { connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length)); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(postDataBytes); wr.flush(); wr.close(); } if (connection.getResponseCode() == 200) { InputStreamReader in = new InputStreamReader((InputStream) connection.getContent()); BufferedReader buff = new BufferedReader(in); String line = buff.readLine().toString(); buff.close(); Object json = new JSONTokener(line).nextValue(); if (json.getClass() == JSONObject.class) { jsonResponseObject = (JSONObject) json; } else if (json.getClass() == JSONArray.class) { jsonResponseArray = (JSONArray) json; } // else members will be left to null indicating no valid response. return true; } } catch (MalformedURLException e) { Log.e(TAG, e.getMessage()); } catch (IOException e) { Log.e(TAG, e.getMessage()); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } return false; }
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;/*w w w . j a v a 2 s . c o 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:edu.uci.ics.pregelix.example.util.TestCluster.java
private void startHDFS() throws IOException { conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/core-site.xml")); conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/mapred-site.xml")); conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/hdfs-site.xml")); FileSystem lfs = FileSystem.getLocal(new Configuration()); lfs.delete(new Path("build"), true); System.setProperty("hadoop.log.dir", "logs"); dfsCluster = new MiniDFSCluster(conf, numberOfNC, true, null); FileSystem dfs = FileSystem.get(conf); Path src = new Path(DATA_PATH); Path dest = new Path(HDFS_PATH); dfs.mkdirs(dest);//from w ww . ja v a 2s. co m dfs.copyFromLocalFile(src, dest); src = new Path(DATA_PATH2); dest = new Path(HDFS_PATH2); dfs.mkdirs(dest); dfs.copyFromLocalFile(src, dest); src = new Path(DATA_PATH3); dest = new Path(HDFS_PATH3); dfs.mkdirs(dest); dfs.copyFromLocalFile(src, dest); src = new Path(DATA_PATH4); dest = new Path(HDFS_PATH4); dfs.mkdirs(dest); dfs.copyFromLocalFile(src, dest); src = new Path(DATA_PATH5); dest = new Path(HDFS_PATH5); dfs.mkdirs(dest); dfs.copyFromLocalFile(src, dest); DataOutputStream confOutput = new DataOutputStream(new FileOutputStream(new File(HADOOP_CONF_PATH))); conf.writeXml(confOutput); confOutput.flush(); confOutput.close(); }
From source file:TaxSvc.TaxSvc.java
public CancelTaxResult CancelTax(CancelTaxRequest req) { //Create URL/* w ww.j a v a2s. c om*/ String taxget = svcURL + "/1.0/tax/cancel"; URL url; HttpURLConnection conn; try { //Connect to URL with authorization header, request content. url = new URL(taxget); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content conn.setRequestProperty("Authorization", encoded); //Add authorization header conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null String content = mapper.writeValueAsString(req); //System.out.println(content); //Uncomment to see the content of the request object conn.setRequestProperty("Content-Length", Integer.toString(content.length())); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(content); wr.flush(); wr.close(); conn.disconnect(); if (conn.getResponseCode() != 200) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode. { //If we got a more serious error, print out the error message. CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response return res; } else { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response return res.CancelTaxResult; } } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.phearom.um.model.RemoteJSONSource.java
private JSONObject sendPost(String urlString) throws Exception { URL url = new URL(urlString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); Map<String, String> params = new HashMap<>(); params.put("limit", "25"); params.put("offset", "0"); String parameter = params.toString().replace(",", "&"); // Send post request con.setDoOutput(true);//w w w . j a va 2 s .co m DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(parameter); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return new JSONObject(response.toString()); }
From source file:com.QuarkLabs.BTCeClientJavaFX.networking.AuthRequest.java
public JSONObject makeRequest(String method, Map<String, String> arguments) throws UnsupportedEncodingException { if (method == null) { return null; }// w ww. java 2 s . c om if (arguments == null) { arguments = new HashMap<>(); } arguments.put("method", method); arguments.put("nonce", "" + ++nonce); String postData = ""; for (Iterator it = arguments.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> ent = (Map.Entry<String, String>) it.next(); if (postData.length() > 0) { postData += "&"; } postData += ent.getKey() + "=" + ent.getValue(); } try { _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512"); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } try { mac = Mac.getInstance("HmacSHA512"); } catch (NoSuchAlgorithmException nsae) { System.err.println("No such algorithm exception: " + nsae.toString()); return null; } try { mac.init(_key); } catch (InvalidKeyException ike) { System.err.println("Invalid key exception: " + ike.toString()); return null; } StringBuilder out = new StringBuilder(); try { HttpURLConnection urlConnection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty("Key", key); String sign = byteArrayToHexString(mac.doFinal(postData.getBytes("UTF-8"))); urlConnection.setRequestProperty("Sign", sign); urlConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); if (urlConnection.getResponseCode() == 200) { BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = rd.readLine()) != null) { out.append(line); } rd.close(); } } catch (IOException e) { e.printStackTrace(); } return new JSONObject(out.toString()); }
From source file:TaxSvc.TaxSvc.java
public GetTaxResult GetTax(GetTaxRequest req) { //Create URL/* ww w .ja va2s .c om*/ String taxget = svcURL + "/1.0/tax/get"; URL url; HttpURLConnection conn; try { //Connect to URL with authorization header, request content. url = new URL(taxget); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content conn.setRequestProperty("Authorization", encoded); //Add authorization header conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null String content = mapper.writeValueAsString(req); //System.out.println(content); //Uncomment to see the content of the request object conn.setRequestProperty("Content-Length", Integer.toString(content.length())); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(content); wr.flush(); wr.close(); conn.disconnect(); if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error. { GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response return res; } else //Otherwise, print out the total tax calculated { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response return res; } } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:org.jongo.mocks.JongoClient.java
private JongoResponse doRequest(final String url, final List<NameValuePair> parameters) { final String urlParameters = URLEncodedUtils.format(parameters, "UTF-8"); JongoResponse response = null;/*from w w w .j a v a 2 s . c o m*/ try { HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", MediaType.APPLICATION_XML); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader r = null; if (con.getResponseCode() != Response.Status.CREATED.getStatusCode()) { r = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { r = new BufferedReader(new InputStreamReader(con.getInputStream())); } StringBuilder rawresponse = new StringBuilder(); String strLine = null; while ((strLine = r.readLine()) != null) { rawresponse.append(strLine); rawresponse.append("\n"); } try { response = XmlXstreamTest.successFromXML(rawresponse.toString()); } catch (Exception e) { response = XmlXstreamTest.errorFromXML(rawresponse.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return response; }