List of usage examples for org.apache.commons.httpclient.methods GetMethod setQueryString
public void setQueryString(String queryString)
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Given a list of stations and a date range this function queries the remote serviceUrl for a list of log files * and returns a JSON representation of the response * /*from w w w. j a va2 s .c om*/ * @param dateFrom The (inclusive) start of date range in YYYY-MM-DD format * @param dateTo The (inclusive) end of date range in YYYY-MM-DD format * @param serviceUrl The remote service URL to query * @param stationList a list (comma seperated) of the GPSSITEID to fetch log files for * * Response Format * { * success : (true/false), * urlList : [{ * fileUrl : (Mapped from url or empty string) * fileDate : (Mapped from date or empty string) * stationId : (Mapped from stationId or empty string) * selected : will be always set to true * }] * } */ @RequestMapping(value = "/getStationListUrls.do", params = { "dateFrom", "dateTo", "stationList", "serviceUrl" }) public ModelAndView getStationListUrls(@RequestParam("dateFrom") final String dateFrom, @RequestParam("dateTo") final String dateTo, @RequestParam("serviceUrl") final String serviceUrl, @RequestParam("stationList") final String stationList, HttpServletRequest request) { boolean success = true; ModelAndView jsonResponse = new ModelAndView("jsonView"); JSONArray urlList = new JSONArray(); logger.debug("getStationListUrls : Requesting urls for " + stationList + " in the range " + dateFrom + " -> " + dateTo); try { String gmlResponse = serviceCaller.getMethodResponseAsString(new ICSWMethodMaker() { public HttpMethodBase makeMethod() { GetMethod method = new GetMethod(serviceUrl); //Generate our filter string based on date and station list String cqlFilter = "(date>='" + dateFrom + "')AND(date<='" + dateTo + "')"; if (stationList != null && stationList.length() > 0) { String[] stations = stationList.split(","); cqlFilter += "AND("; for (int i = 0; i < stations.length; i++) { if (i > 0) cqlFilter += "OR"; cqlFilter += "(id='" + stations[i] + "')"; } cqlFilter += ")"; } //attach them to the method method.setQueryString(new NameValuePair[] { new NameValuePair("request", "GetFeature"), new NameValuePair("outputFormat", "GML2"), new NameValuePair("typeName", "geodesy:station_observations"), new NameValuePair("PropertyName", "geodesy:date,geodesy:url,geodesy:id"), new NameValuePair("CQL_FILTER", cqlFilter) }); return method; } }.makeMethod(), serviceCaller.getHttpClient()); //Parse our XML string into a list of input files List<GeodesyGridInputFile> ggifList = GeodesyGridInputFile.fromGmlString(gmlResponse); for (GeodesyGridInputFile ggif : ggifList) { urlList.add(ggif); } } catch (Exception ex) { logger.warn("selectStationList.do : Error " + ex.getMessage()); urlList.clear(); success = false; } //save the date range for later processing request.getSession().setAttribute("dateFrom", dateFrom); request.getSession().setAttribute("dateTo", dateTo); jsonResponse.addObject("success", success); jsonResponse.addObject("urlList", urlList); return jsonResponse; }
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Returns every Geodesy station (and some extra descriptive info) in a JSON format. * //from w ww . ja v a 2s . co m * Response Format * { * success : (true/false), * records : [{ * stationNumber : (Mapped from STATIONNO or empty string) * stationName : (Mapped from STATIONNAME or empty string) * gpsSiteId : (Mapped from GPSSITEID or empty string) * countryId : (Mapped from COUNTRYID or empty string) * stateId : (Mapped from STATEID or empty string) * }] * } */ @RequestMapping("/getStationList.do") public ModelAndView getStationList() { final String stationTypeName = "ngcp:GnssStation"; ModelAndView jsonResponse = new ModelAndView("jsonView"); JSONArray stationList = new JSONArray(); boolean success = true; try { XPath xPath = XPathFactory.newInstance().newXPath(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //Query every geodesy station provider for the raw GML CSWRecord[] geodesyRecords = cswService.getWFSRecordsForTypename(stationTypeName); if (geodesyRecords == null || geodesyRecords.length == 0) throw new Exception("No " + stationTypeName + " records available"); //This makes the assumption of only a single geodesy WFS CSWRecord record = geodesyRecords[0]; final String serviceUrl = record.getServiceUrl(); jsonResponse.addObject("serviceUrl", serviceUrl); logger.debug("getStationListXML.do : Requesting " + stationTypeName + " for " + serviceUrl); String gmlResponse = serviceCaller.getMethodResponseAsString(new ICSWMethodMaker() { public HttpMethodBase makeMethod() { GetMethod method = new GetMethod(serviceUrl); //set all of the parameters NameValuePair request = new NameValuePair("request", "GetFeature"); NameValuePair elementSet = new NameValuePair("typeName", stationTypeName); //attach them to the method method.setQueryString(new NameValuePair[] { request, elementSet }); return method; } }.makeMethod(), serviceCaller.getHttpClient()); //Parse the raw GML and generate some useful JSON objects Document doc = builder.parse(new InputSource(new StringReader(gmlResponse))); String serviceTitleExpression = "/FeatureCollection/featureMembers/GnssStation"; NodeList nodes = (NodeList) xPath.evaluate(serviceTitleExpression, doc, XPathConstants.NODESET); //Lets pull some useful info out for (int i = 0; nodes != null && i < nodes.getLength(); i++) { Node node = nodes.item(i); ModelMap stationMap = new ModelMap(); Node tempNode = (Node) xPath.evaluate("STATIONNO", node, XPathConstants.NODE); stationMap.addAttribute("stationNumber", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("GPSSITEID", node, XPathConstants.NODE); stationMap.addAttribute("gpsSiteId", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("STATIONNAME", node, XPathConstants.NODE); stationMap.addAttribute("stationName", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("COUNTRYID", node, XPathConstants.NODE); stationMap.addAttribute("countryId", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("STATEID", node, XPathConstants.NODE); stationMap.addAttribute("stateId", tempNode == null ? "" : tempNode.getTextContent()); stationList.add(stationMap); } } catch (Exception ex) { logger.warn("getStationListXML.do : Error " + ex.getMessage()); success = false; stationList.clear(); } //Form our response object jsonResponse.addObject("stations", stationList); jsonResponse.addObject("success", success); return jsonResponse; }
From source file:org.carrot2.util.httpclient.HttpUtils.java
/** * Opens a HTTP/1.1 connection to the given URL using the GET method, decompresses * compressed response streams, if supported by the server. * //w ww. j ava 2 s.c om * @param url The URL to open. The URL must be properly escaped, this method will * <b>not</b> perform any escaping. * @param params Query string parameters to be attached to the url. * @param headers Any extra HTTP headers to add to the request. * @param user if not <code>null</code>, the user name to send during Basic * Authentication * @param password if not <code>null</code>, the password name to send during Basic * Authentication * @return The {@link HttpUtils.Response} object. Note that entire payload is read and * buffered so that the HTTP connection can be closed when leaving this * method. */ public static Response doGET(String url, Collection<NameValuePair> params, Collection<Header> headers, String user, String password, int timeout) throws HttpException, IOException { final HttpClient client = HttpClientFactory.getTimeoutingClient(timeout); client.getParams().setVersion(HttpVersion.HTTP_1_1); final GetMethod request = new GetMethod(); if (user != null && password != null) { client.getState().setCredentials(new AuthScope(null, 80, null), new UsernamePasswordCredentials(user, password)); request.setDoAuthentication(true); } final Response response = new Response(); try { request.setURI(new URI(url, true)); if (params != null) { request.setQueryString(params.toArray(new NameValuePair[params.size()])); } request.setRequestHeader(HttpHeaders.URL_ENCODED); request.setRequestHeader(HttpHeaders.GZIP_ENCODING); if (headers != null) { for (Header header : headers) request.setRequestHeader(header); } org.slf4j.LoggerFactory.getLogger(HttpUtils.class).debug("GET: " + request.getURI()); final int statusCode = client.executeMethod(request); response.status = statusCode; InputStream stream = request.getResponseBodyAsStream(); final Header encoded = request.getResponseHeader("Content-Encoding"); if (encoded != null && "gzip".equalsIgnoreCase(encoded.getValue())) { stream = new GZIPInputStream(stream); response.compression = COMPRESSION_GZIP; } else { response.compression = COMPRESSION_NONE; } final Header[] respHeaders = request.getResponseHeaders(); response.headers = new String[respHeaders.length][]; for (int i = 0; i < respHeaders.length; i++) { response.headers[i] = new String[] { respHeaders[i].getName(), respHeaders[i].getValue() }; } response.payload = StreamUtils.readFullyAndClose(stream); return response; } finally { request.releaseConnection(); } }
From source file:org.cauldron.tasks.HttpCall.java
/** * Running an HttpTask retrieves the path contents according to the task * attributes. POST body comes from the input. *//*from ww w . j av a 2 s. c o m*/ public Object run(Context context, Object input) throws TaskException { // For POST, body must be available as input. String body = null; if (!isGet) { body = (String) context.convert(input, String.class); if (body == null) throw new TaskException("HTTP POST input must be convertible to String"); } // Prepare request parameters. NameValuePair[] nvp = null; if (params != null && params.size() > 0) { nvp = new NameValuePair[params.size()]; int count = 0; for (Iterator entries = params.entrySet().iterator(); entries.hasNext();) { Map.Entry entry = (Map.Entry) entries.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); nvp[count++] = new NameValuePair(key, value); } } // Create the retrieval method and set parameters. // HttpMethod method; if (isGet) { GetMethod get = new GetMethod(); if (nvp != null) get.setQueryString(nvp); method = get; } else { PostMethod post = new PostMethod(); post.setRequestBody(body); if (nvp != null) post.addParameters(nvp); method = post; } // Make the call. method.setPath(path); HttpConnection connection = connectionManager.getConnection(config); try { connection.open(); method.execute(new HttpState(), connection); return method.getResponseBodyAsString(); } catch (HttpException e) { throw new TaskException(e); } catch (IOException e) { throw new TaskException(e); } finally { connection.close(); } }
From source file:org.codehaus.mojo.delicious.DeliciousService.java
private void doServiceImpl(String category, String command, HashMap formFields) throws InterruptedException, IOException, HttpException { Thread.sleep(Messages.getCourtesyTime().longValue()); HttpClient client = new HttpClient(); client.getState().setCredentials(new AuthScope(Messages.getDeliciousHost(), 80), new UsernamePasswordCredentials(userName, password)); GetMethod httpMethod = new GetMethod(getServiceUrl(category, command)); if (formFields != null && formFields.size() > 0) { httpMethod.setQueryString(getQuery(formFields)); }/* www. j a va 2 s . com*/ code = connection.executeMethod(client, httpMethod); notifyListener(httpMethod, code); httpMethod.releaseConnection(); if (code != HttpStatus.SC_OK) { throw new RuntimeException(serviceUnavailableMessage); } }
From source file:org.craftercms.cstudio.impl.service.deployment.PublishingManagerImpl.java
@Override public long getTargetVersion(PublishingTargetItem target, String site) { long version = -1; if (target.getVersionUrl() != null && !target.getVersionUrl().isEmpty()) { LOGGER.debug(String.format("Get deployment agent version for target ", target.getName())); URL versionUrl = null;// ww w .j a va 2 s. c om try { versionUrl = new URL(target.getVersionUrl()); } catch (MalformedURLException e) { LOGGER.error(String.format("Invalid get version URL for target [%s]", target.getName()), e); } GetMethod getMethod = null; HttpClient client = null; try { getMethod = new GetMethod(target.getVersionUrl()); String siteId = target.getSiteId(); if (StringUtils.isEmpty(siteId)) { siteId = site; } getMethod.setQueryString( new NameValuePair[] { new NameValuePair(TARGET_REQUEST_PARAMETER, target.getTarget()), new NameValuePair(SITE_REQUEST_PARAMETER, siteId) }); client = new HttpClient(); int status = client.executeMethod(getMethod); if (status == HttpStatus.SC_OK) { String responseText = getMethod.getResponseBodyAsString(); if (responseText != null && !responseText.isEmpty()) { version = Long.parseLong(responseText.trim()); } else { version = 0; } } } catch (Exception e) { //LOGGER.error(String.format("Target (%s) responded with error while checking target version. Get version failed for url %s", target.getName(), target.getVersionUrl())); } finally { if (client != null) { HttpConnectionManager mgr = client.getHttpConnectionManager(); if (mgr instanceof SimpleHttpConnectionManager) { ((SimpleHttpConnectionManager) mgr).shutdown(); } } if (getMethod != null) { getMethod.releaseConnection(); } getMethod = null; client = null; } } return version; }
From source file:org.craftercms.studio.impl.v1.service.deployment.PublishingManagerImpl.java
@Override public long getTargetVersion(DeploymentEndpointConfigTO target, String site) { long version = -1; if (target.getVersionUrl() != null && !target.getVersionUrl().isEmpty()) { LOGGER.debug(String.format("Get deployment agent version for target ", target.getName())); URL versionUrl = null;/*from w w w .j av a2 s . c o m*/ try { versionUrl = new URL(target.getVersionUrl()); } catch (MalformedURLException e) { LOGGER.error(String.format("Invalid get version URL for target [%s]", target.getName()), e); } GetMethod getMethod = null; HttpClient client = null; try { getMethod = new GetMethod(target.getVersionUrl()); String siteId = target.getSiteId(); if (StringUtils.isEmpty(siteId)) { siteId = site; } getMethod.setQueryString( new NameValuePair[] { new NameValuePair(TARGET_REQUEST_PARAMETER, target.getTarget()), new NameValuePair(SITE_REQUEST_PARAMETER, siteId) }); client = new HttpClient(); int status = client.executeMethod(getMethod); if (status == HttpStatus.SC_OK) { InputStream responseStream = getMethod.getResponseBodyAsStream(); String responseText = IOUtils.toString(responseStream); if (responseText != null && !responseText.isEmpty()) { version = Long.parseLong(responseText.trim()); } else { version = 0; } } } catch (Exception e) { //LOGGER.error(String.format("Target (%s) responded with error while checking target version. Get version failed for url %s", target.getName(), target.getVersionUrl())); } finally { if (client != null) { HttpConnectionManager mgr = client.getHttpConnectionManager(); if (mgr instanceof SimpleHttpConnectionManager) { ((SimpleHttpConnectionManager) mgr).shutdown(); } } if (getMethod != null) { getMethod.releaseConnection(); } getMethod = null; client = null; } } return version; }
From source file:org.dspace.discovery.SolrServiceImpl.java
/** Simple means to return the search result as an InputStream */ public java.io.InputStream searchAsInputStream(DiscoverQuery query) throws SearchServiceException, java.io.IOException { try {//from w w w. ja va2 s . c o m org.apache.commons.httpclient.methods.GetMethod method = new org.apache.commons.httpclient.methods.GetMethod( getSolr().getHttpClient().getHostConfiguration().getHostURL() + ""); method.setQueryString(query.toString()); getSolr().getHttpClient().executeMethod(method); return method.getResponseBodyAsStream(); } catch (org.apache.solr.client.solrj.SolrServerException e) { throw new SearchServiceException(e.getMessage(), e); } }
From source file:org.eclipse.mylyn.internal.monitor.usage.UsageUploadManager.java
public int getExistingUid(StudyParameters studyParameters, String firstName, String lastName, String emailAddress, boolean anonymous, IProgressMonitor monitor) throws UsageDataException { // TODO extract url for servlet String url = studyParameters.getUserIdServletUrl(); final GetMethod getUidMethod = new GetMethod(url); try {//from w w w. j av a 2 s . c o m NameValuePair first = new NameValuePair("firstName", firstName); //$NON-NLS-1$ NameValuePair last = new NameValuePair("lastName", lastName); //$NON-NLS-1$ NameValuePair email = new NameValuePair("email", emailAddress); //$NON-NLS-1$ NameValuePair job = new NameValuePair("jobFunction", ""); //$NON-NLS-1$ //$NON-NLS-2$ NameValuePair size = new NameValuePair("companySize", ""); //$NON-NLS-1$ //$NON-NLS-2$ NameValuePair buisness = new NameValuePair("companyBuisness", ""); //$NON-NLS-1$ //$NON-NLS-2$ NameValuePair contact = new NameValuePair("contact", ""); //$NON-NLS-1$ //$NON-NLS-2$ NameValuePair anon = null; if (anonymous) { anon = new NameValuePair("anonymous", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } else { anon = new NameValuePair("anonymous", "false"); //$NON-NLS-1$ //$NON-NLS-2$ } if (studyParameters.usingContactField()) { getUidMethod.setQueryString( new NameValuePair[] { first, last, email, job, size, buisness, anon, contact }); } else { getUidMethod.setQueryString(new NameValuePair[] { first, last, email, job, size, buisness, anon }); } // create a new client and upload the file AbstractWebLocation location = new WebLocation(url); HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); final int status = WebUtil.execute(httpClient, hostConfiguration, getUidMethod, monitor); if (status == HttpStatus.SC_OK) { InputStream inputStream = WebUtil.getResponseBodyAsStream(getUidMethod, monitor); try { String response = getStringFromStream(inputStream); response = response.substring(response.indexOf(":") + 1).trim(); //$NON-NLS-1$ int uid = Integer.parseInt(response); return uid; } finally { inputStream.close(); } } else { throw new UsageDataException( NLS.bind(Messages.UsageUploadManager_Error_Getting_Uid_Http_Response, status)); } } catch (UsageDataException e) { throw e; } catch (final IOException e) { throw new UsageDataException(NLS.bind(Messages.UsageUploadManager_Error_Getting_UidX_Y, e.getClass().getCanonicalName(), e.getMessage()), e); } catch (final Exception e) { if (e instanceof NoRouteToHostException || e instanceof UnknownHostException) { throw new UsageDataException(Messages.UsageUploadManager_Error_Getting_Uid_No_Network, e); } else { throw new UsageDataException(NLS.bind(Messages.UsageUploadManager_Error_Getting_Uid_X_Y, e.getClass().getCanonicalName(), e.getMessage()), e); } } finally { getUidMethod.releaseConnection(); } }
From source file:org.eclipse.orion.server.cf.commands.BindServicesCommand.java
@Override protected ServerStatus _doIt() { /* multi server status */ MultiServerStatus status = new MultiServerStatus(); try {//from w w w . j av a2s . co m /* bind services */ URI targetURI = URIUtil.toURI(target.getUrl()); ManifestParseTree manifest = getApplication().getManifest(); ManifestParseTree app = manifest.get("applications").get(0); //$NON-NLS-1$ if (app.has(CFProtocolConstants.V2_KEY_SERVICES)) { /* fetch all services */ URI servicesURI = targetURI.resolve("/v2/services"); //$NON-NLS-1$ GetMethod getServicesMethod = new GetMethod(servicesURI.toString()); HttpUtil.configureHttpMethod(getServicesMethod, target); getServicesMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$ /* send request */ ServerStatus jobStatus = HttpUtil.executeMethod(getServicesMethod); status.add(jobStatus); if (!jobStatus.isOK()) return status; JSONObject resp = jobStatus.getJsonData(); JSONArray servicesJSON = resp.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES); /* check for manifest version */ ManifestParseTree services = app.getOpt(CFProtocolConstants.V2_KEY_SERVICES); if (services == null) /* nothing to do */ return status; int version = services.isList() ? 6 : 2; if (version == 2) { String spaceGuid = target.getSpace().getGuid(); URI serviceInstancesURI2 = targetURI.resolve("/v2/spaces/" + spaceGuid + "/service_instances"); //$NON-NLS-1$//$NON-NLS-2$ for (ManifestParseTree service : services.getChildren()) { String serviceName = service.getLabel(); String nameService = "name:" + serviceName; //$NON-NLS-1$ NameValuePair[] pa = new NameValuePair[] { new NameValuePair("return_user_provided_service_instance", "false"), // //$NON-NLS-1$//$NON-NLS-2$ new NameValuePair("q", nameService), //$NON-NLS-1$ new NameValuePair("inline-relations-depth", "2") // //$NON-NLS-1$ //$NON-NLS-2$ }; GetMethod getServiceMethod = new GetMethod(serviceInstancesURI2.toString()); getServiceMethod.setQueryString(pa); HttpUtil.configureHttpMethod(getServiceMethod, target); /* send request */ jobStatus = HttpUtil.executeMethod(getServiceMethod); status.add(jobStatus); if (!jobStatus.isOK()) return status; resp = jobStatus.getJsonData(); String serviceInstanceGUID = null; JSONArray respArray = resp.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES); for (int i = 0; i < respArray.length(); ++i) { JSONObject o = respArray.optJSONObject(i); if (o != null) { JSONObject str = o.optJSONObject(CFProtocolConstants.V2_KEY_METADATA); if (str != null) { serviceInstanceGUID = str.getString(CFProtocolConstants.V2_KEY_GUID); break; } } } if (serviceInstanceGUID == null) { /* no service instance bound to the application, create one if possible */ /* support both 'type' and 'label' fields as service type */ ManifestParseTree serviceType = service.getOpt(CFProtocolConstants.V2_KEY_TYPE); if (serviceType == null) serviceType = service.get(CFProtocolConstants.V2_KEY_LABEL); ManifestParseTree provider = service.get(CFProtocolConstants.V2_KEY_PROVIDER); ManifestParseTree plan = service.get(CFProtocolConstants.V2_KEY_PLAN); String servicePlanGUID = findServicePlanGUID(serviceType.getValue(), provider.getValue(), plan.getValue(), servicesJSON); if (servicePlanGUID == null) { String[] bindings = { serviceName, serviceType.getValue(), plan.getValue() }; String msg = NLS.bind( "Could not find service instance {0} nor service {1} with plan {2} in target.", bindings); status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); return status; } /* create service instance */ URI serviceInstancesURI = targetURI.resolve("/v2/service_instances"); //$NON-NLS-1$ PostMethod createServiceMethod = new PostMethod(serviceInstancesURI.toString()); HttpUtil.configureHttpMethod(createServiceMethod, target); /* set request body */ JSONObject createServiceRequest = new JSONObject(); createServiceRequest.put(CFProtocolConstants.V2_KEY_SPACE_GUID, target.getSpace().getCFJSON().getJSONObject(CFProtocolConstants.V2_KEY_METADATA) .getString(CFProtocolConstants.V2_KEY_GUID)); createServiceRequest.put(CFProtocolConstants.V2_KEY_NAME, serviceName); createServiceRequest.put(CFProtocolConstants.V2_KEY_SERVICE_PLAN_GUID, servicePlanGUID); createServiceMethod.setRequestEntity(new StringRequestEntity( createServiceRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ /* send request */ jobStatus = HttpUtil.executeMethod(createServiceMethod); status.add(jobStatus); if (!jobStatus.isOK()) return status; resp = jobStatus.getJsonData(); serviceInstanceGUID = resp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA) .getString(CFProtocolConstants.V2_KEY_GUID); } /* bind service to the application */ URI serviceBindingsURI = targetURI.resolve("/v2/service_bindings"); //$NON-NLS-1$ PostMethod bindServiceMethod = new PostMethod(serviceBindingsURI.toString()); HttpUtil.configureHttpMethod(bindServiceMethod, target); /* set request body */ JSONObject bindServiceRequest = new JSONObject(); bindServiceRequest.put(CFProtocolConstants.V2_KEY_APP_GUID, getApplication().getGuid()); bindServiceRequest.put(CFProtocolConstants.V2_KEY_SERVICE_INSTANCE_GUID, serviceInstanceGUID); bindServiceMethod.setRequestEntity(new StringRequestEntity(bindServiceRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ /* send request */ jobStatus = HttpUtil.executeMethod(bindServiceMethod); status.add(jobStatus); if (!jobStatus.isOK()) return status; } } if (version == 6) { String spaceGuid = target.getSpace().getGuid(); URI serviceInstancesURI = targetURI.resolve("/v2/spaces/" + spaceGuid + "/service_instances"); //$NON-NLS-1$//$NON-NLS-2$ for (ManifestParseTree service : services.getChildren()) { String nameService = service.getValue(); NameValuePair[] pa = new NameValuePair[] { new NameValuePair("return_user_provided_service_instance", "true"), // //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("q", "name:" + nameService), //$NON-NLS-1$//$NON-NLS-2$ new NameValuePair("inline-relations-depth", "2") }; //$NON-NLS-1$ //$NON-NLS-2$ GetMethod getServiceMethod = new GetMethod(serviceInstancesURI.toString()); getServiceMethod.setQueryString(pa); HttpUtil.configureHttpMethod(getServiceMethod, target); /* send request */ jobStatus = HttpUtil.executeMethod(getServiceMethod); status.add(jobStatus); if (!jobStatus.isOK()) return status; resp = jobStatus.getJsonData(); String serviceInstanceGUID = null; JSONArray respArray = resp.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES); for (int i = 0; i < respArray.length(); i++) { JSONObject o = respArray.optJSONObject(i); if (o != null) { JSONObject str = o.optJSONObject(CFProtocolConstants.V2_KEY_METADATA); if (str != null) { serviceInstanceGUID = str.getString(CFProtocolConstants.V2_KEY_GUID); } } } if (serviceInstanceGUID == null) { status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Service instance " + nameService + " can not be found in target space", null)); return status; } /* bind service to the application */ URI serviceBindingsURI = targetURI.resolve("/v2/service_bindings"); //$NON-NLS-1$ PostMethod bindServiceMethod = new PostMethod(serviceBindingsURI.toString()); HttpUtil.configureHttpMethod(bindServiceMethod, target); /* set request body */ JSONObject bindServiceRequest = new JSONObject(); bindServiceRequest.put(CFProtocolConstants.V2_KEY_APP_GUID, getApplication().getGuid()); bindServiceRequest.put(CFProtocolConstants.V2_KEY_SERVICE_INSTANCE_GUID, serviceInstanceGUID); bindServiceMethod.setRequestEntity(new StringRequestEntity(bindServiceRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ /* send request */ jobStatus = HttpUtil.executeMethod(bindServiceMethod); status.add(jobStatus); if (!jobStatus.isOK()) return status; } } } return status; } catch (InvalidAccessException e) { status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null)); return status; } catch (Exception e) { String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$ logger.error(msg, e); status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); return status; } }