List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsString
public abstract String getResponseBodyAsString() throws IOException;
From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxyTest.java
@Test public void testRetrieveWSDLList() throws Exception { Map<String, String> props = new HashMap<String, String>(); props.put("property1", "value1"); props.put("property2", "value2"); props.put("property3", "value3"); ClientRequest request = RegistryProxyFactory.getInstance().createRequest(); request.setURI(new URI(DESCRIPTION_URL)); request.setMethod(Method.GET); request.setEntityType(WSDLList.class); request.setProperties(props);//from w w w . j a va 2 s . c o m HttpMethod httpMethodMock = createNiceMock(HttpMethod.class); HttpClientProxyStub proxyStub = new HttpClientProxyStub(); proxyStub.setClient(new HttpClientStub()); proxyStub.setMethod(httpMethodMock); httpMethodMock.setURI(uriMatches(DESCRIPTION_URL, convertToQuery(props))); expectLastCall().atLeastOnce(); httpMethodMock.getResponseBodyAsString(); expectLastCall().andReturn(RESPONSE_WSDL_LIST).once(); replay(httpMethodMock); ClientResponse response = proxyStub.get(request); assertNotNull("ClientResponse must not be null.", response); assertNotNull("Response status must be set.", response.getStatus()); assertEquals(Status.SUCCESS, response.getStatus()); assertNotNull("Response object must be set.", response.getEntity()); assertEquals(WSDLList.class, response.getEntity().getClass()); List<String> wsdls = WSDLList.class.cast(response.getEntity()).getUrl(); assertNotNull(wsdls); assertEquals(2, wsdls.size()); verify(httpMethodMock); }
From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxyTest.java
@Test public void testRetrieveWsdl() throws Exception { ClientRequest request = RegistryProxyFactory.getInstance().createRequest(); request.setURI(new URI(DESCRIPTION_URL)); HttpMethod httpMethodMock = createNiceMock(HttpMethod.class); HttpClientProxyStub proxyStub = new HttpClientProxyStub(); proxyStub.setClient(new HttpClientStub()); proxyStub.setMethod(httpMethodMock); httpMethodMock.getResponseBodyAsString(); expectLastCall().andReturn("wsdl contents").once(); replay(httpMethodMock);// w w w. j a va 2 s .c o m ClientResponse response = proxyStub.get(request); assertNotNull("ClientResponse must not be null.", response); assertNotNull("Response status must be set.", response.getStatus()); assertEquals(Status.SUCCESS, response.getStatus()); assertNotNull("Response object must be set.", response.getEntity()); assertEquals("wsdl contents", response.getEntity()); verify(httpMethodMock); }
From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxyTest.java
@Test public void testRetrievalFailsProxyThrewException() throws Exception { ClientRequest request = RegistryProxyFactory.getInstance().createRequest(); request.setURI(new URI(DESCRIPTION_URL)); HttpMethod httpMethodMock = createNiceMock(HttpMethod.class); HttpClientProxyStub proxyStub = new HttpClientProxyStub(); proxyStub.setClient(new HttpClientStub()); proxyStub.setMethod(httpMethodMock); httpMethodMock.getResponseBodyAsString(); expectLastCall().andReturn("registry contents").once(); replay(httpMethodMock);/*from w ww. jav a 2 s . c o m*/ try { // setting any type other than WSDLList will lead to // unmarshalling failure and exception will be thrown request.setEntityType(String.class); proxyStub.get(request); } catch (SwordfishException e) { // expected } verify(httpMethodMock); }
From source file:org.eclipse.winery.highlevelrestapi.LowLevelRestApi.java
/** * Extracts the response information from an executed HttpMethod * //from w w w . j a v a 2 s .c om * @param method Executed Method * @return Packaged response information */ private static HttpResponseMessage extractResponseInformation(HttpMethod method) { // Create and return HttpResponseMethod HttpResponseMessage responseMessage = new HttpResponseMessage(); responseMessage.setStatusCode(method.getStatusCode()); try { responseMessage.setResponseBody(method.getResponseBodyAsString()); } catch (Exception e) { e.printStackTrace(); } return responseMessage; }
From source file:org.eclipsetrader.directa.internal.core.WebConnector.java
public synchronized void login() { final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final ISecurePreferences securePreferences; if (preferenceStore.getBoolean(Activator.PREFS_USE_SECURE_PREFERENCE_STORE)) { securePreferences = SecurePreferencesFactory.getDefault().node(Activator.PLUGIN_ID); try {//from w w w .j a va 2s . c o m if (userName == null) { userName = securePreferences.get(Activator.PREFS_USERNAME, ""); //$NON-NLS-1$ } if (password == null) { password = securePreferences.get(Activator.PREFS_PASSWORD, ""); //$NON-NLS-1$ } } catch (Exception e) { final Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error accessing secure storage", e); //$NON-NLS-1$ Display.getDefault().syncExec(new Runnable() { @Override public void run() { Activator.log(status); ErrorDialog.openError(null, null, null, status); } }); } } else { securePreferences = null; if (userName == null) { userName = preferenceStore.getString(Activator.PREFS_USERNAME); } if (password == null) { password = preferenceStore.getString(Activator.PREFS_PASSWORD); } } prt = ""; //$NON-NLS-1$ urt = ""; //$NON-NLS-1$ user = ""; //$NON-NLS-1$ do { if (userName == null || password == null || "".equals(userName) || "".equals(password)) { //$NON-NLS-1$ //$NON-NLS-2$ Display.getDefault().syncExec(new Runnable() { @Override public void run() { LoginDialog dlg = new LoginDialog(null, userName, password); if (dlg.open() == Window.OK) { userName = dlg.getUserName(); password = dlg.getPassword(); if (dlg.isSavePassword()) { if (preferenceStore.getBoolean(Activator.PREFS_USE_SECURE_PREFERENCE_STORE)) { try { securePreferences.put(Activator.PREFS_USERNAME, userName, true); securePreferences.put(Activator.PREFS_PASSWORD, dlg.isSavePassword() ? password : "", true); //$NON-NLS-1$ } catch (Exception e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error accessing secure storage", e); //$NON-NLS-1$ Activator.log(status); ErrorDialog.openError(null, null, null, status); } } else { preferenceStore.putValue(Activator.PREFS_USERNAME, userName); preferenceStore.putValue(Activator.PREFS_PASSWORD, dlg.isSavePassword() ? password : ""); //$NON-NLS-1$ } } } else { userName = null; password = null; } } }); if (userName == null || password == null) { return; } } if (client == null) { client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); try { setupProxy(client, HOST); } catch (URISyntaxException e) { final Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error setting proxy", e); //$NON-NLS-1$ Display.getDefault().syncExec(new Runnable() { @Override public void run() { Activator.log(status); ErrorDialog.openError(null, null, null, status); } }); } } try { HttpMethod method = new GetMethod("https://" + HOST + "/trading/collegc_3"); //$NON-NLS-1$ //$NON-NLS-2$ method.setFollowRedirects(true); method.setQueryString(new NameValuePair[] { new NameValuePair("USER", userName), //$NON-NLS-1$ new NameValuePair("PASSW", password), //$NON-NLS-1$ new NameValuePair("PAG", "VT4.4.0.6"), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("TAPPO", "X"), //$NON-NLS-1$ //$NON-NLS-2$ }); logger.debug(method.getURI().toString()); client.executeMethod(method); Parser parser = Parser.createParser(method.getResponseBodyAsString(), ""); //$NON-NLS-1$ NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter(RemarkNode.class)); for (SimpleNodeIterator iter = list.elements(); iter.hasMoreNodes();) { RemarkNode node = (RemarkNode) iter.nextNode(); String text = node.getText(); if (text.startsWith("USER")) { //$NON-NLS-1$ user = text.substring(4); } if (text.startsWith("URT")) { //$NON-NLS-1$ urt = text.substring(3); } else if (text.startsWith("PRT")) { //$NON-NLS-1$ prt = text.substring(3); } } } catch (Exception e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to login server", e); //$NON-NLS-1$ Activator.log(status); return; } if (user.equals("") || prt.equals("") || urt.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ password = ""; //$NON-NLS-1$ } } while (user.equals("") || prt.equals("") || urt.equals("")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ account.setId(userName); }
From source file:org.eclipsetrader.directa.internal.core.WebConnector.java
protected void getWatchlist(String id, String title) { try {//from w w w . j a v a2 s.c o m HttpMethod method = new GetMethod("https://" + HOST + "/trading/tabelc_4"); //$NON-NLS-1$ //$NON-NLS-2$ method.setFollowRedirects(true); method.setQueryString(new NameValuePair[] { new NameValuePair("USER", user), //$NON-NLS-1$ new NameValuePair("DEVAR", id), //$NON-NLS-1$ }); logger.debug(method.getURI().toString()); client.executeMethod(method); Parser parser = Parser.createParser(method.getResponseBodyAsString(), ""); //$NON-NLS-1$ NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter(TableRow.class)); for (SimpleNodeIterator iter = list.elements(); iter.hasMoreNodes();) { TableRow row = (TableRow) iter.nextNode(); if (row.getChildCount() == 23) { if (row.getChild(1) instanceof TableHeader) { continue; } String symbol = ""; //$NON-NLS-1$ String isin = ""; //$NON-NLS-1$ String description = ""; //$NON-NLS-1$ LinkTag link = (LinkTag) ((TableColumn) row.getChild(1)).getChild(1); int s = link.getText().indexOf("TITO="); //$NON-NLS-1$ if (s != -1) { s += 5; int e = link.getText().indexOf("&", s); //$NON-NLS-1$ if (e == -1) { e = link.getText().length(); } symbol = link.getText().substring(s, e); } description = link.getFirstChild().getText(); description = description.replaceAll("[\r\n]", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$ link = (LinkTag) ((TableColumn) row.getChild(5)).getChild(0); s = link.getText().indexOf("tlv="); //$NON-NLS-1$ if (s != -1) { s += 4; int e = link.getText().indexOf("&", s); //$NON-NLS-1$ if (e == -1) { e = link.getText().length(); } isin = link.getText().substring(s, e); } System.out.println(symbol + " " + isin + " (" + description + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } } catch (Exception e) { logger.error(e.toString(), e); } }
From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java
@Override public Response execute(Request request) throws IOException { HttpMethod http = null; switch (request.method()) { case DELETE://from ww w . j ava2 s .co m http = new DeleteMethodWithBody(); break; case HEAD: http = new HeadMethod(); break; case GET: http = (request.body() == null ? new GetMethod() : new GetMethodWithBody()); break; case POST: http = new PostMethod(); break; case PUT: http = new PutMethod(); break; default: throw new EsHadoopTransportException("Unknown request method " + request.method()); } CharSequence uri = request.uri(); if (StringUtils.hasText(uri)) { http.setURI(new URI(escapeUri(uri.toString(), settings.getNetworkSSLEnabled()), false)); } // NB: initialize the path _after_ the URI otherwise the path gets reset to / http.setPath(prefixPath(request.path().toString())); try { // validate new URI uri = http.getURI().toString(); } catch (URIException uriex) { throw new EsHadoopTransportException("Invalid target URI " + request, uriex); } CharSequence params = request.params(); if (StringUtils.hasText(params)) { http.setQueryString(params.toString()); } ByteSequence ba = request.body(); if (ba != null && ba.length() > 0) { if (!(http instanceof EntityEnclosingMethod)) { throw new IllegalStateException(String.format("Method %s cannot contain body - implementation bug", request.method().name())); } EntityEnclosingMethod entityMethod = (EntityEnclosingMethod) http; entityMethod.setRequestEntity(new BytesArrayRequestEntity(ba)); entityMethod.setContentChunked(false); } // when tracing, log everything if (log.isTraceEnabled()) { log.trace(String.format("Tx %s[%s]@[%s][%s] w/ payload [%s]", proxyInfo, request.method().name(), httpInfo, request.path(), request.body())); } long start = System.currentTimeMillis(); try { client.executeMethod(http); } finally { stats.netTotalTime += (System.currentTimeMillis() - start); } if (log.isTraceEnabled()) { Socket sk = ReflectionUtils.invoke(GET_SOCKET, conn, (Object[]) null); String addr = sk.getLocalAddress().getHostAddress(); log.trace(String.format("Rx %s@[%s] [%s-%s] [%s]", proxyInfo, addr, http.getStatusCode(), HttpStatus.getStatusText(http.getStatusCode()), http.getResponseBodyAsString())); } // the request URI is not set (since it is retried across hosts), so use the http info instead for source return new SimpleResponse(http.getStatusCode(), new ResponseInputStream(http), httpInfo); }
From source file:org.encuestame.core.util.SocialUtils.java
/** * Get Google Stats from google short url. * @param googleShortUrl/* w ww. ja v a2 s . com*/ * @return * @throws IOException */ public static String getGoGlStats(final String googleShortUrl) throws IOException { HttpClient httpclient = new HttpClient(); String completeUrl = StringUtils.replace(SocialUtils.GOOGLE_SHORT_URL_STATS, "$1", googleShortUrl); HttpMethod method = new GetMethod(completeUrl); httpclient.executeMethod(method); String tinyUrl = method.getResponseBodyAsString(); method.releaseConnection(); return tinyUrl; }
From source file:org.encuestame.core.util.SocialUtils.java
/** * Get TinyUrl./*from ww w . j a v a2 s . c o m*/ * @param url * @return * @throws HttpException * @throws IOException */ public static String getYourls(final String url) { String yourlsShortUrl = url; HttpClientParams params = new HttpClientParams(); params.setConnectionManagerTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); params.setSoTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); HttpClient httpclient = new HttpClient(params); //TODO: time out?? HttpMethod method = new GetMethod(EnMePlaceHolderConfigurer.getProperty("short.yourls.path")); method.setQueryString(new NameValuePair[] { new NameValuePair("url", url), new NameValuePair("action", "shorturl"), new NameValuePair("format", "json"), new NameValuePair("signature", EnMePlaceHolderConfigurer.getProperty("short.yourls.key")) }); System.out.println("method--->" + method.getPath()); System.out.println("method--->" + method.getQueryString()); try { httpclient.executeMethod(method); final Object jsonObject = JSONValue.parse(method.getResponseBodyAsString()); final JSONObject o = (JSONObject) jsonObject; //{"message":"Please log in","errorCode":403}" Long errorCode = (Long) o.get("errorCode"); if (errorCode != null) { throw new EnMeException("Yourls error: " + errorCode); } yourlsShortUrl = (String) o.get("shorturl"); } catch (HttpException e) { log.error("HttpException " + e); yourlsShortUrl = url; } catch (IOException e) { log.error("IOException" + e); yourlsShortUrl = url; } catch (Exception e) { //e.printStackTrace(); log.error("IOException" + e); yourlsShortUrl = url; } finally { RequestSessionMap.setErrorMessage("short url is not well configured"); method.releaseConnection(); } return yourlsShortUrl; }
From source file:org.encuestame.core.util.SocialUtils.java
/** * Get TinyUrl.// w w w.j a v a 2 s.co m * * @param string * @return * @throws HttpException * @throws IOException */ public static String getTinyUrl(String string) { String tinyUrl = string; HttpClientParams params = new HttpClientParams(); params.setConnectionManagerTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); params.setSoTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); HttpClient httpclient = new HttpClient(params); //TODO: time out?? //httpclient.setConnectionTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); log.debug("tiny url timeout " + EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); //httpclient.setParams(params); HttpMethod method = new GetMethod(SocialUtils.TINY_URL); method.setQueryString(new NameValuePair[] { new NameValuePair("url", string) }); try { log.debug("tiny url execute: " + string); httpclient.executeMethod(method); tinyUrl = method.getResponseBodyAsString(); } catch (HttpException e) { log.error("HttpException " + e); tinyUrl = string; } catch (IOException e) { log.error("IOException" + e); tinyUrl = string; } finally { method.releaseConnection(); } return tinyUrl; }