// function to do the join use case public static void share() throws Exception { HttpPost method = new HttpPost(url + "/share"); String ipAddress = null; Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) en.nextElement(); if (ni.getName().equals("eth0")) { Enumeration<InetAddress> en2 = ni.getInetAddresses(); while (en2.hasMoreElements()) { InetAddress ip = (InetAddress) en2.nextElement(); if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } break; } } method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } // get present time date = new Date(); long start = date.getTime(); // Execute the vishwa share process Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp); String ch = "alive"; System.out.println("Type kill to unjoin from the grid"); while (!ch.equals("kill")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ch = in.readLine(); } p.destroy(); date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/shareAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
// function to do the compute use case public static void compute() throws Exception { HttpPost method = new HttpPost(url + "/compute"); method.setEntity(new StringEntity(username, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } System.out.println("Give the file name which has to be put in the grid for computation"); // input of the file name to be computed BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = in.readLine(); // get the absolute path of the current working directory File directory = new File("."); String pwd = directory.getAbsolutePath(); // get present time date = new Date(); long start = date.getTime(); String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp; System.out.println(cmd); // Execute the vishwa compute process Process p = Runtime.getRuntime().exec(cmd); // wait till the compute process is completed // check for the status code (0 for successful termination) int status = p.waitFor(); if (status == 0) { System.out.println("Compute operation successful. Check the directory for results"); } date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/computeAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
public String getData(String url) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); String response = ""; try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(get, responseHandler); } catch (Exception e) { debug(e.toString()); } return response; }
private String getJsonResponse(String jsonUrl) throws PhrescoException { if (debugEnabled) { S_LOGGER.debug("Entering Method CIManagerImpl.getJsonResponse(String jsonUrl)"); S_LOGGER.debug("getJsonResponse() JSonUrl = " + jsonUrl); } try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(jsonUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); return httpClient.execute(httpget, responseHandler); } catch (IOException e) { throw new PhrescoException(e); } }
/** * Запрос с указанием параметров. * * @see MoneyDownloader#login * @see MoneyDownloader#password * @see MoneyDownloader#dateStart * @see MoneyDownloader#dateEnd */ public final void run() { File file = new File(directory + "/Results.tsv"); // File test = new File(directory + "/tmp/result.tsv"); try { if (!file.exists()) { file.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } String request = "https://rt.miran.ru?user="******"&pass="******"http://rt.miran.ru/rt/Search/Results.tsv?user="******"&pass="******"&Format=%27__Created__%2FTITLE%3A%D0%94%D0%B0%D1%82%D0%B0%27%2C%0A%27%20%20%20%3Cb%3E%3Ca%20href%3D%22%2Frt%2FTicket%2FDisplay.html%3Fid%3D__id__%22%3E__id__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3A%23%27%2C%0A%27__Subject__%2FTITLE%3A%D0%A2%D0%B5%D0%BC%D0%B0%27%2C%0A%27__QueueName__%2FTITLE%3A%D0%9E%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%27%2C%0A%27__CustomField.%7Binteraction%20type%7D__%2FTITLE%3A%D0%A2%D0%B8%D0%BF%27%2C%0A%27__CustomField.%7Bbussines%7D__%2FTITLE%3A%D0%91%D0%B8%D0%B7%D0%BD%D0%B5%D1%81%27%2C%0A%27__CustomField.%7Bdirection%7D__%2FTITLE%3A%D0%9D%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%27%2C%0A%27__CustomField.%7Bservice%7D__%2FTITLE%3A%D0%A3%D1%81%D0%BB%D1%83%D0%B3%D0%B0%27%2C%0A%27__CustomField.%7BSD%20Type%7D__%2FTITLE%3A%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F%27%2C%0A%27__CustomField.%7BSD%20Detail%7D__%2FTITLE%3A%D0%91%D0%BE%D0%BD%D1%83%D1%81%27%2C%0A%27__CustomField.%7BQA%7D__%2FTITLE%3A%D0%92%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D0%BB%27&Order=DESC%7CASC%7CASC%7CASC&OrderBy=Created%7C%7C%7C&Page=1&Query=Created%20%3E%20%27" + dateStart + "%27%20AND%20Created%20%3C%20%27" + dateEnd + "%27%20AND%20Status%20%3D%20%27closed%27%20AND%20Queue%20!%3D%20%27manager%27%20AND%20Queue%20!%3D%20%27sales%27%20AND%20%27CF.%7BQA%7D%27%20%3D%20%27__CurrentUser__%27&RowsPerPage=0&SavedChartSearchId=new&SavedSearchId="; System.out.println(tickets); ListCookieHandler cookieHandler = new ListCookieHandler(); CookieHandler.setDefault(cookieHandler); try { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getResponseCode(); GetMethod method = new GetMethod(tickets); method.addRequestHeader("Cookie", cookieHandler.getCookiez()); method.addRequestHeader("Referer", "http://rt.miran.ru/"); HttpClient httpClient = new HttpClient(); httpClient.executeMethod(method); InputStream in = method.getResponseBodyAsStream(); System.out.println(in.available()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Tests method setRequestContent of HttpClient. * * @throws IOException I/O Exception */ @Test public void writeMultipartMessage() throws IOException { final HttpRequest req = new HttpRequest(); req.isMultipart = true; req.payloadAttrs.put("media-type", "multipart/alternative"); req.payloadAttrs.put("boundary", "boundary42"); final Part p1 = new Part(); p1.headers.put("Content-Type", "text/plain; charset=us-ascii"); p1.bodyAttrs.put("media-type", "text/plain"); final String plain = "...plain text...."; p1.bodyContent.add(Str.get(plain + '\n')); final Part p2 = new Part(); p2.headers.put("Content-Type", "text/richtext"); p2.bodyAttrs.put("media-type", "text/richtext"); final String rich = ".... richtext version..."; p2.bodyContent.add(Str.get(rich)); final Part p3 = new Part(); p3.headers.put("Content-Type", "text/x-whatever"); p3.bodyAttrs.put("media-type", "text/x-whatever"); final String fancy = ".... fanciest formatted version..."; p3.bodyContent.add(Str.get(fancy)); req.parts.add(p1); req.parts.add(p2); req.parts.add(p3); final FakeHttpConnection fakeConn = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn.getOutputStream(), req); final String expResult = "--boundary42" + CRLF + "Content-Type: text/plain; charset=us-ascii" + CRLF + CRLF + plain + Prop.NL + CRLF + "--boundary42" + CRLF + "Content-Type: text/richtext" + CRLF + CRLF + rich + CRLF + "--boundary42" + CRLF + "Content-Type: text/x-whatever" + CRLF + CRLF + fancy + CRLF + "--boundary42--" + CRLF; // Compare results assertEquals(expResult, fakeConn.getOutputStream().toString()); }
/** * Tests writing of body content when @method is raw and output is xs:hexBinary. * * @throws IOException I/O Exception */ @Test public void writeHex() throws IOException { // Case 1: content is xs:hexBinary final HttpRequest req1 = new HttpRequest(); req1.payloadAttrs.put("method", SerialMethod.BASEX.toString()); req1.bodyContent.add(new Hex(token("test"))); final FakeHttpConnection fakeConn1 = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn1.getOutputStream(), req1); assertEquals(fakeConn1.out.toString(Strings.UTF8), "test"); // Case 2: content is a node final HttpRequest req2 = new HttpRequest(); req2.payloadAttrs.put("method", SerialMethod.BASEX.toString()); final FElem e3 = new FElem("a").add("test"); req2.bodyContent.add(e3); final FakeHttpConnection fakeConn2 = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn2.getOutputStream(), req2); assertEquals(fakeConn2.out.toString(), "<a>test</a>"); }
/** * Tests writing of request content with different combinations of the body attributes media-type * and method. * * @throws IOException IO exception */ @Test public void writeMessage() throws IOException { // Case 1: No method, media-type='text/xml' final HttpRequest req1 = new HttpRequest(); final FakeHttpConnection fakeConn1 = new FakeHttpConnection(new URL("http://www.test.com")); req1.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/xml"); // Node child final FElem e1 = new FElem("a").add("a"); req1.bodyContent.add(e1); // String item child req1.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn1.getOutputStream(), req1); assertEquals("<a>a</a><b>b</b>", fakeConn1.out.toString(Strings.UTF8)); // Case 2: No method, media-type='text/plain' final HttpRequest req2 = new HttpRequest(); final FakeHttpConnection fakeConn2 = new FakeHttpConnection(new URL("http://www.test.com")); req2.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/plain"); // Node child final FElem e2 = new FElem("a").add("a"); req2.bodyContent.add(e2); // String item child req2.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn2.getOutputStream(), req2); assertEquals("a<b>b</b>", fakeConn2.out.toString()); // Case 3: method='text', media-type='text/xml' final HttpRequest req3 = new HttpRequest(); final FakeHttpConnection fakeConn3 = new FakeHttpConnection(new URL("http://www.test.com")); req3.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/xml"); req3.payloadAttrs.put("method", "text"); // Node child final FElem e3 = new FElem("a").add("a"); req3.bodyContent.add(e3); // String item child req3.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn3.getOutputStream(), req3); assertEquals("a<b>b</b>", fakeConn3.out.toString()); }
// function to check login public static boolean login(String pass) throws Exception { HttpPost method = new HttpPost(url + "/login"); method.setEntity(new StringEntity(username + ';' + pass, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } return connIp.equals("true"); }
/** * Tests writing of request content when @src is set. * * @throws IOException I/O Exception */ @Test public void writeFromResource() throws IOException { // Create a file form which will be read final IOFile file = new IOFile(Prop.TMP, Util.className(FnHttpTest.class)); file.write(token("test")); // Request final HttpRequest req = new HttpRequest(); req.payloadAttrs.put("src", file.url()); req.payloadAttrs.put("method", "binary"); // HTTP connection final FakeHttpConnection fakeConn = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn.getOutputStream(), req); // Delete file file.delete(); assertEquals(fakeConn.out.toString(Strings.UTF8), "test"); }
public String getRequest(String url, String queryString) { String responseText = ""; try { httpGet.setURI(new URI(url + "?" + queryString)); httpGet.addHeader("Accept", "application/json"); HttpResponse response = httpClient.execute(httpGet); responseText = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (URISyntaxException e1) { } return responseText; }
public String postRequest(String url, List<NameValuePair> entity) { String responseText = ""; try { httpPost.setURI(new URI(url)); httpPost.addHeader("Accept", "application/json"); httpPost.setEntity(new UrlEncodedFormEntity(entity)); HttpResponse response = httpClient.execute(httpPost); responseText = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (URISyntaxException e1) { } return responseText; }
/** * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the * form /userService/users. If CS throws an exception it handled and transalated to a Openfire * exception if possible. This is done using the check fault method that tries to throw the best * maching exception. * * @param type Must be GET or DELETE * @param urlSuffix The url suffix of the rest request * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only * @return The response as a xml doc. * @throws ConnectionException Thrown if there are issues perfoming the request. * @throws Exception Thrown if the response from Clearspace contains an exception. */ public Element executeRequest(HttpType type, String urlSuffix, String xmlParams) throws ConnectionException, Exception { if (Log.isDebugEnabled()) { Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams); } String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix; String secret = getSharedSecret(); HttpClient client = new HttpClient(); HttpMethod method; // Configures the authentication client.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret); AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM); client.getState().setCredentials(scope, credentials); // Creates the method switch (type) { case GET: method = new GetMethod(wsUrl); break; case POST: PostMethod pm = new PostMethod(wsUrl); StringRequestEntity requestEntity = new StringRequestEntity(xmlParams); pm.setRequestEntity(requestEntity); method = pm; break; case PUT: PutMethod pm1 = new PutMethod(wsUrl); StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams); pm1.setRequestEntity(requestEntity1); method = pm1; break; case DELETE: method = new DeleteMethod(wsUrl); break; default: throw new IllegalArgumentException(); } method.setRequestHeader("Accept", "text/xml"); method.setDoAuthentication(true); try { // Executes the request client.executeMethod(method); // Parses the result String body = method.getResponseBodyAsString(); if (Log.isDebugEnabled()) { Log.debug("Outgoing REST call results: " + body); } // Checks the http status if (method.getStatusCode() != 200) { if (method.getStatusCode() == 401) { throw new ConnectionException( "Invalid password to connect to Clearspace.", ConnectionException.ErrorType.AUTHENTICATION); } else if (method.getStatusCode() == 404) { throw new ConnectionException( "Web service not found in Clearspace.", ConnectionException.ErrorType.PAGE_NOT_FOUND); } else if (method.getStatusCode() == 503) { throw new ConnectionException( "Web service not avaible in Clearspace.", ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE); } else { throw new ConnectionException( "Error connecting to Clearspace, http status code: " + method.getStatusCode(), new HTTPConnectionException(method.getStatusCode()), ConnectionException.ErrorType.OTHER); } } else if (body.contains("Clearspace Upgrade Console")) { // TODO Change CS to send a more standard error message throw new ConnectionException( "Clearspace is in an update state.", ConnectionException.ErrorType.UPDATE_STATE); } Element response = localParser.get().parseDocument(body).getRootElement(); // Check for exceptions checkFault(response); // Since there is no exception, returns the response return response; } catch (DocumentException e) { throw new ConnectionException( "Error parsing the response of Clearspace.", e, ConnectionException.ErrorType.OTHER); } catch (HttpException e) { throw new ConnectionException( "Error performing http request to Clearspace", e, ConnectionException.ErrorType.OTHER); } catch (UnknownHostException e) { throw new ConnectionException( "Unknown Host " + getConnectionURI() + " trying to connect to Clearspace", e, ConnectionException.ErrorType.UNKNOWN_HOST); } catch (IOException e) { throw new ConnectionException( "Error peforming http request to Clearspace.", e, ConnectionException.ErrorType.OTHER); } finally { method.releaseConnection(); } }