List of usage examples for org.apache.commons.httpclient HttpMethod setQueryString
public abstract void setQueryString(NameValuePair[] paramArrayOfNameValuePair);
From source file:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java
private HttpMethod createMethod(RequestMethod method, String uri, InputStream data) throws ConnectionException { uri = prepend_base(uri);//from w ww. j a v a 2 s .c o m if (uri == null) throw new ConnectionException("URI must not be null"); // Extract QP's int qp_start = uri.indexOf('?'); String qps = null; if (qp_start != -1) { qps = uri.substring(qp_start + 1); uri = uri.substring(0, qp_start); } HttpMethod out = null; switch (method) { case POST: { out = new PostMethod(uri); if (data != null) ((PostMethod) out).setRequestEntity(new InputStreamRequestEntity(data)); break; } case PUT: { out = new PutMethod(uri); if (data != null) ((PutMethod) out).setRequestEntity(new InputStreamRequestEntity(data)); break; } case GET: out = new GetMethod(uri); break; case DELETE: out = new DeleteMethod(uri); break; default: throw new ConnectionException("Unsupported method " + method, 0, uri); } if (qps != null) out.setQueryString(qps); out.setDoAuthentication(true); return out; }
From source file:org.deegree.ogcwebservices.wass.wss.operation.DoServiceHandler.java
/** * This method does the actual request to the secured service. It returns the response of the * secured service as an inputstream. It also replace the GetCapabilities request - responses * with the facadeurl given by the client. * * @param request/* www . j a v a2 s . c o m*/ * send by the client a DoService Request. * @param securedService * the service for which this wss is proxying, must be put in the deegreeparams of * the configuration file. * @param requestedCharset * this wss uses, also read from the deegreeparams in the configuration file. * @param timeout * how long to wait for a response. Service dependable therefor also read from the * deegreeparams in the config file. * @param securedServiceName * the name of the service for which we are proxying -> config. * @return the http response of the secured service as an inputstream. * @throws DoServiceException * if an error occurs wile sending the request or treating the response. see * org.deegree.ogcwebservices.csw.manager.CatalogueHarvester#getNextMetadataRecord */ public DoServiceResponse sendRequest(DoService request, URL securedService, String requestedCharset, int timeout, String securedServiceName) throws DoServiceException { if (requestAllowed) { Header[] headers = null; InputStream body = null; Header[] footers = null; String proxyRequest = null; try { proxyRequest = URLDecoder.decode(request.getPayload(), CharsetUtils.getSystemCharset()); } catch (UnsupportedEncodingException e) { LOG.logError(e.getMessage(), e); throw new DoServiceException(Messages.getMessage("WASS_ERROR_INTERNAL", "WSS")); } LOG.logDebug("encoded proxyrequest: " + request.getPayload() + "\ndecoded proxy: " + proxyRequest); String dcp = request.getDcp(); HttpClient client = new HttpClient(); client = WebUtils.enableProxyUsage(client, securedService); StringRequestEntity requestEntity = null; HttpClientParams params = client.getParams(); params.setSoTimeout(timeout); HttpMethod requestMethod = null; try { String contentType = null; for (RequestParameter param : request.getRequestParameters()) { if (param.getId().toLowerCase().trim().contains("mime-type")) contentType = param.getParameter(); } requestEntity = new StringRequestEntity(proxyRequest, contentType, requestedCharset); } catch (UnsupportedEncodingException e1) { throw new DoServiceException(Messages.getMessage("WASS_ERROR_ENCODING_NOT_SUPPORTED", "WSS")); } if (dcp.equalsIgnoreCase("http_post")) { // the url to the service must be written in the deegreeparams in the configuration // xml requestMethod = new PostMethod(securedService.toExternalForm()); ((PostMethod) requestMethod).setRequestEntity(requestEntity); } else if (dcp.equalsIgnoreCase("http_get")) { requestMethod = new GetMethod(securedService.toExternalForm()); requestMethod.setQueryString(proxyRequest); } else { throw new DoServiceException(Messages.getMessage("WASS_ERROR_NOT_POST_OR_GET", "WSS")); } // getDataRequest try { // make header parameters of the requestParameters. for (RequestParameter param : request.getRequestParameters()) { if (!param.getId().toLowerCase().trim().contains("mime-type"))// Contenttype requestMethod.addRequestHeader(param.getId(), param.getParameter()); } // Call the secured service client.executeMethod(requestMethod); headers = requestMethod.getResponseHeaders(); footers = requestMethod.getResponseFooters(); body = requestMethod.getResponseBodyAsStream(); if (body == null) throw new DoServiceException(Messages.getMessage("WASS_ERROR_GOT_NO_RESPONSE", "WSS")); } catch (HttpException e) { LOG.logError(e.getMessage(), e); throw new DoServiceException(Messages.getMessage("WASS_ERROR_EXCEPTION_IN_RESPONSE", "WSS")); } catch (IOException e) { LOG.logError(e.getMessage(), e); throw new DoServiceException(Messages.getMessage("WASS_ERROR_IN_TRANSPORT", "WSS")); } try { // Replace the given urls with the facadeurls if it is a GetCapabilities request if (proxyRequest.trim().contains("GetCapabilities")) { Operation[] operations = null; OGCCapabilitiesDocument doc = null; /* * For now just check these service, others may be "secured" in the future. */ if ("WFS".equals(securedServiceName)) { doc = new WFSCapabilitiesDocument(); doc.load(body, securedService.toExternalForm()); WFSCapabilities cap = (WFSCapabilities) doc.parseCapabilities(); operations = cap.getOperationsMetadata().getOperations(); replaceFacadeURL(operations, request.getFacadeURL()); doc = org.deegree.ogcwebservices.wfs.XMLFactory.export(cap); } else if (("WMS").equals(securedServiceName)) { doc = new WMSCapabilitiesDocument(); doc.load(body, securedService.toExternalForm()); doc = WMSCapabilitiesDocumentFactory.getWMSCapabilitiesDocument(doc.getRootElement()); WMSCapabilities cap = (WMSCapabilities) doc.parseCapabilities(); org.deegree.owscommon_new.Operation[] ops = cap.getOperationMetadata().getOperations() .toArray(new org.deegree.owscommon_new.Operation[0]); replaceFacadeURL(ops, request.getFacadeURL()); doc = org.deegree.ogcwebservices.wms.XMLFactory.export(cap); } else if (("WCS").equals(securedServiceName)) { doc = new WCSCapabilitiesDocument(); doc.load(body, securedService.toExternalForm()); WCSCapabilities cap = (WCSCapabilities) doc.parseCapabilities(); operations = cap.getCapabilitiy().getOperations().getOperations(); replaceFacadeURL(operations, request.getFacadeURL()); doc = org.deegree.ogcwebservices.wcs.XMLFactory.export(cap); } else if (("CSW").equals(securedServiceName)) { doc = new CatalogueCapabilitiesDocument(); doc.load(body, securedService.toExternalForm()); CatalogueCapabilities cap = (CatalogueCapabilities) doc.parseCapabilities(); operations = cap.getOperationsMetadata().getOperations(); replaceFacadeURL(operations, request.getFacadeURL()); doc = org.deegree.ogcwebservices.csw.XMLFactory_2_0_0.export(cap, null); } body = new ByteArrayInputStream(doc.getAsString().getBytes()); } } catch (IOException e) { LOG.logError(e.getMessage(), e); throw new DoServiceException(Messages.getMessage("WASS_ERROR_READING_BODY", "WSS")); } catch (InvalidCapabilitiesException e) { LOG.logError(e.getMessage(), e); throw new DoServiceException(Messages.getMessage("WASS_ERROR_CAPABILITIES_RESPONSE", "WSS")); } catch (SAXException e) { LOG.logError(e.getMessage(), e); throw new DoServiceException(Messages.getMessage("WASS_ERROR_FACADE_URL", "WSS")); } catch (XMLParsingException e) { LOG.logError(e.getMessage(), e); throw new DoServiceException(Messages.getMessage("WASS_ERROR_READING_BODY", "WSS")); } return new DoServiceResponse(headers, body, footers); } return null; }
From source file:org.dspace.rest.providers.DiscoverProvider.java
public List<?> getEntities(EntityReference ref, Search search) { log.info("DiscoverProvider - get_entities"); List<Object> entities = new ArrayList<Object>(); try {/*from w w w.j ava 2s.c om*/ HttpClient client = new HttpClient(); HttpMethod method = new GetMethod( ConfigurationManager.getProperty("discovery", "search.server") + "/select"); log.info("DiscoverProvider method - " + ConfigurationManager.getProperty("discovery", "search.server")); log.info("DiscoverProvider search.getRestrictions().length - " + search.getRestrictions().length); log.info("DiscoverProvider format - " + format); List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>(); if (search.getRestrictions().length > 0) { for (int i = 0; i < search.getRestrictions().length; i++) { log.info("DiscoverProvider search.getRestrictions()[i].getProperty() - " + search.getRestrictions()[i].getProperty()); log.info("DiscoverProvider search.getRestrictions()[i].getStringValue() - " + search.getRestrictions()[i].getStringValue()); if (!"org.apache.catalina.ASYNC_SUPPORTED".equals(search.getRestrictions()[i].getProperty())) { nameValuePairsList.add(new NameValuePair(search.getRestrictions()[i].getProperty(), search.getRestrictions()[i].getStringValue())); } } if ("json".equals(format)) { nameValuePairsList.add(new NameValuePair("wt", "json")); } } if (search.getOrders().length > 0) { for (int i = 0; i < search.getOrders().length; i++) { log.info("DiscoverProvider search.getOrders()[i].getProperty() - " + search.getOrders()[i].getProperty()); nameValuePairsList.add(new NameValuePair("sort", search.getOrders()[i].getProperty())); } } NameValuePair[] nameValuePairs = new NameValuePair[nameValuePairsList.size()]; nameValuePairsList.toArray(nameValuePairs); method.setQueryString(nameValuePairs); client.executeMethod(method); String s = method.getResponseBodyAsString(); // log.info("DiscoverProvider result string - " + s); entities.add(new EntityData(s)); method.releaseConnection(); } catch (IOException e) { throw new EntityException("Internal server error", "IO error, cannot call solr server", 500); } return entities; }
From source file:org.dspace.rest.providers.StatisticsProvider.java
public List<?> getEntities(EntityReference ref, Search search) { log.info("StatisticsProvider - get_entities"); List<Object> entities = new ArrayList<Object>(); try {//from ww w.j av a 2 s . co m HttpClient client = new HttpClient(); HttpMethod method = new GetMethod( ConfigurationManager.getProperty("solr-statistics", "server") + "/select"); log.info( "StatisticsProvider method - " + ConfigurationManager.getProperty("solr-statistics", "server")); log.info("StatisticsProvider search.getRestrictions().length - " + search.getRestrictions().length); log.info("StatisticsProvider format - " + format); List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>(); if (search.getRestrictions().length > 0) { for (int i = 0; i < search.getRestrictions().length; i++) { log.info("StatisticsProvider search.getRestrictions()[i].getProperty() - " + search.getRestrictions()[i].getProperty()); log.info("StatisticsProvider search.getRestrictions()[i].getStringValue() - " + search.getRestrictions()[i].getStringValue()); if (!"org.apache.catalina.ASYNC_SUPPORTED".equals(search.getRestrictions()[i].getProperty())) { nameValuePairsList.add(new NameValuePair(search.getRestrictions()[i].getProperty(), search.getRestrictions()[i].getStringValue())); } } if ("json".equals(format)) { nameValuePairsList.add(new NameValuePair("wt", "json")); } } if (search.getOrders().length > 0) { for (int i = 0; i < search.getOrders().length; i++) { log.info("StatisticsProvider search.getOrders()[i].getProperty() - " + search.getOrders()[i].getProperty()); nameValuePairsList.add(new NameValuePair("sort", search.getOrders()[i].getProperty())); } } NameValuePair[] nameValuePairs = new NameValuePair[nameValuePairsList.size()]; nameValuePairsList.toArray(nameValuePairs); method.setQueryString(nameValuePairs); client.executeMethod(method); String s = method.getResponseBodyAsString(); // log.info("StatisticsProvider result string - " + s); entities.add(new EntityData(s)); method.releaseConnection(); } catch (IOException e) { throw new EntityException("Internal server error", "IO error, cannot call solr server", 500); } return entities; }
From source file:org.eclipse.ecf.remoteservice.rest.client.RestClientService.java
/** * @throws ECFException //from w w w . ja va2 s . com */ protected HttpMethod prepareGetMethod(String uri, IRemoteCall call, IRemoteCallable callable) throws NotSerializableException { HttpMethod result = new GetMethod(uri); NameValuePair[] params = toNameValuePairs(uri, call, callable); if (params != null) result.setQueryString(params); return result; }
From source file:org.eclipse.om2m.comm.http.RestHttpClient.java
/** * Converts a protocol-independent {@link RequestIndication} object into a standard HTTP request and sends a standard HTTP request. * Converts the received standard HTTP request into {@link ResponseConfirm} object and returns it back. * @param requestIndication - protocol independent request. * @return protocol independent response. *//*from w w w. j a va2s. c o m*/ public ResponseConfirm sendRequest(RequestIndication requestIndication) { logServiceTracker = new ServiceTracker(FrameworkUtil.getBundle(RestHttpClient.class).getBundleContext(), org.osgi.service.log.LogService.class.getName(), null); logServiceTracker.open(); logservice = (LogService) logServiceTracker.getService(); LOGGER.debug("Http Client > " + requestIndication); logservice.log(LogService.LOG_ERROR, "Http Client > " + requestIndication); HttpClient httpclient = new HttpClient(); ResponseConfirm responseConfirm = new ResponseConfirm(); HttpMethod httpMethod = null; String url = requestIndication.getUrl(); if (!url.startsWith(protocol + "://")) { url = protocol + "://" + url; } try { switch (requestIndication.getMethod()) { case "RETRIEVE": httpMethod = new GetMethod(url); break; case "CREATE": httpMethod = new PostMethod(url); ((PostMethod) httpMethod).setRequestEntity( new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8")); break; case "UPDATE": httpMethod = new PutMethod(url); ((PutMethod) httpMethod).setRequestEntity( new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8")); break; case "DELETE": httpMethod = new DeleteMethod(url); break; case "EXECUTE": httpMethod = new PostMethod(url); break; default: return new ResponseConfirm(); } httpMethod.addRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(requestIndication.getRequestingEntity().getBytes()))); httpMethod.setQueryString(getQueryFromParams(requestIndication.getParameters())); int statusCode = httpclient.executeMethod(httpMethod); responseConfirm.setStatusCode(getRestStatusCode(statusCode)); if (statusCode != 204) { if (httpMethod.getResponseBody() != null) { responseConfirm.setRepresentation(new String(httpMethod.getResponseBody())); } } if (statusCode == 201) { if (httpMethod.getResponseHeader("Location").getValue() != null) { responseConfirm.setResourceURI(httpMethod.getResponseHeader("Location").getValue()); } } //LOGGER.debug("Http Client > "+responseConfirm); LOGGER.debug("Http Client > " + responseConfirm); logservice.log(LogService.LOG_ERROR, "Http Client > " + responseConfirm); } catch (IOException e) { LOGGER.error(url + " Not Found" + responseConfirm, e); logservice.log(LogService.LOG_ERROR, url + " Not Found" + responseConfirm); } finally { httpMethod.releaseConnection(); } return responseConfirm; }
From source file:org.eclipsetrader.borsaitalia.internal.core.BackfillConnector.java
@Override public IOHLC[] backfillHistory(IFeedIdentifier identifier, Date from, Date to, TimeSpan timeSpan) { String code = identifier.getSymbol(); String isin = null;//from w w w. j av a 2 s. co m IFeedProperties properties = (IFeedProperties) identifier.getAdapter(IFeedProperties.class); if (properties != null) { if (properties.getProperty(Activator.PROP_ISIN) != null) { isin = properties.getProperty(Activator.PROP_ISIN); } if (properties.getProperty(Activator.PROP_CODE) != null) { code = properties.getProperty(Activator.PROP_CODE); } } if (code == null || isin == null) { return null; } String period = String.valueOf(timeSpan.getLength()) + (timeSpan.getUnits() == Units.Minutes ? "MIN" : "DAY"); //$NON-NLS-1$ //$NON-NLS-2$ List<OHLC> list = new ArrayList<OHLC>(); try { HttpMethod method = new GetMethod("http://" + host + "/scripts/cligipsw.dll"); //$NON-NLS-1$ //$NON-NLS-2$ method.setQueryString(new NameValuePair[] { new NameValuePair("app", "tic_d"), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("action", "dwnld4push"), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("cod", code), //$NON-NLS-1$ new NameValuePair("codneb", isin), //$NON-NLS-1$ new NameValuePair("req_type", "GRAF_DS"), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("ascii", "1"), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("form_id", ""), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("period", period), //$NON-NLS-1$ new NameValuePair("From", new SimpleDateFormat("yyyyMMdd000000").format(from)), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("To", new SimpleDateFormat("yyyyMMdd000000").format(to)), //$NON-NLS-1$ //$NON-NLS-2$ }); method.setFollowRedirects(true); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); client.executeMethod(method); BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); String inputLine = in.readLine(); if (inputLine.startsWith("@")) { //$NON-NLS-1$ while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("@") || inputLine.length() == 0) { //$NON-NLS-1$ continue; } try { String[] item = inputLine.split("\\|"); //$NON-NLS-1$ OHLC bar = new OHLC(df.parse(item[0]), nf.parse(item[1]).doubleValue(), nf.parse(item[2]).doubleValue(), nf.parse(item[3]).doubleValue(), nf.parse(item[4]).doubleValue(), nf.parse(item[5]).longValue()); list.add(bar); } catch (Exception e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error parsing data: " + inputLine, e); //$NON-NLS-1$ Activator.getDefault().getLog().log(status); } } } else { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, NLS.bind("Unexpected response from {0}: {1}", new Object[] { //$NON-NLS-1$ method.getURI().toString(), inputLine }), null); Activator.getDefault().getLog().log(status); } in.close(); } catch (Exception e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error reading data", e); //$NON-NLS-1$ Activator.getDefault().getLog().log(status); } return list.toArray(new IOHLC[list.size()]); }
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 {/* w w w . j a v a 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 va2 s. co 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 .ja v a 2s .c o 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); }