Java Code Examples for org.eclipse.jetty.client.api.ContentResponse#getContentAsString()

The following examples show how to use org.eclipse.jetty.client.api.ContentResponse#getContentAsString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JettyXhrTransport.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method,
		HttpHeaders headers, @Nullable String body) {

	Request httpRequest = this.httpClient.newRequest(url).method(method);
	addHttpHeaders(httpRequest, headers);
	if (body != null) {
		httpRequest.content(new StringContentProvider(body));
	}
	ContentResponse response;
	try {
		response = httpRequest.send();
	}
	catch (Exception ex) {
		throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
	}
	HttpStatus status = HttpStatus.valueOf(response.getStatus());
	HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders());
	return (response.getContent() != null ?
			new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) :
			new ResponseEntity<>(responseHeaders, status));
}
 
Example 2
Source File: RpcClient.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
public String callSynchronous(JsonArray params, OrangeContext orangeContext)
        throws RpcCallException {
    HttpClientWrapper clientWrapper = loadBalancer.getHttpClientWrapper();
    HttpRequestWrapper balancedPost = clientWrapper.createHttpPost(this);

    //set custom headers
    if (orangeContext != null) {
        orangeContext.getProperties().forEach(balancedPost::setHeader);
    }

    balancedPost.setHeader("Content-type", TYPE_JSON);
    //TODO: fix: Temporary workaround below until go services are more http compliant
    balancedPost.setHeader("Connection", "close");
    JsonRpcRequest jsonRequest = new JsonRpcRequest(null, methodName, params);
    String json = jsonRequest.toString();
    balancedPost.setContentProvider(new StringContentProvider(json));

    logger.debug("Sending request of size {}", json.length());
    ContentResponse rpcResponse = clientWrapper.execute(balancedPost,
            new JsonRpcCallExceptionDecoder(), orangeContext);
    String rawResponse = rpcResponse.getContentAsString();
    logger.debug("Json response from the service: {}", rawResponse);

    return JsonRpcResponse.fromString(rawResponse).getResult().getAsString();
}
 
Example 3
Source File: JettyXhrTransport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, String body) {
	Request httpRequest = this.httpClient.newRequest(url).method(method);
	addHttpHeaders(httpRequest, headers);
	if (body != null) {
		httpRequest.content(new StringContentProvider(body));
	}
	ContentResponse response;
	try {
		response = httpRequest.send();
	}
	catch (Exception ex) {
		throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
	}
	HttpStatus status = HttpStatus.valueOf(response.getStatus());
	HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders());
	return (response.getContent() != null ?
		new ResponseEntity<String>(response.getContentAsString(), responseHeaders, status) :
		new ResponseEntity<String>(responseHeaders, status));
}
 
Example 4
Source File: SystemTest.java    From app-runner with MIT License 6 votes vote down vote up
@Test
public void theRestAPILives() throws Exception {
    JSONObject all = getAllApps();
    System.out.println("all = " + all.toString(4));
    assertThat(all.getInt("appCount"), is(1));
    JSONAssert.assertEquals("{apps:[" +
        "{ name: \"maven\", url: \"" + appRunnerUrl + "/maven/\" }" +
        "]}", all, JSONCompareMode.LENIENT);

    assertThat(restClient.deploy("invalid-app-name"),
        is(equalTo(404, is("No app found with name 'invalid-app-name'. Valid names: maven"))));

    ContentResponse resp = client.GET(appRunnerUrl + "/api/v1/apps/maven");
    assertThat(resp.getStatus(), is(200));
    JSONObject single = new JSONObject(resp.getContentAsString());
    JSONAssert.assertEquals(all.getJSONArray("apps").getJSONObject(0), single, JSONCompareMode.STRICT_ORDER);

    assertThat(single.has("lastBuild"), is(true));
    assertThat(single.has("lastSuccessfulBuild"), is(true));
}
 
Example 5
Source File: JettyXhrTransport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method,
		HttpHeaders headers, @Nullable String body) {

	Request httpRequest = this.httpClient.newRequest(url).method(method);
	addHttpHeaders(httpRequest, headers);
	if (body != null) {
		httpRequest.content(new StringContentProvider(body));
	}
	ContentResponse response;
	try {
		response = httpRequest.send();
	}
	catch (Exception ex) {
		throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
	}
	HttpStatus status = HttpStatus.valueOf(response.getStatus());
	HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders());
	return (response.getContent() != null ?
			new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) :
			new ResponseEntity<>(responseHeaders, status));
}
 
Example 6
Source File: CloudStore.java    From athenz with Apache License 2.0 6 votes vote down vote up
String getMetaData(String path) {

        final String baseUri = "http://169.254.169.254/latest";
        ContentResponse response;
        try {
            response = httpClient.GET(baseUri + path);
        } catch (InterruptedException | ExecutionException | TimeoutException ex) {
            LOGGER.error("CloudStore: unable to fetch requested uri '{}':{}",
                    path, ex.getMessage());
            return null;
        }
        if (response.getStatus() != 200) {
            LOGGER.error("CloudStore: unable to fetch requested uri '{}' status:{}",
                    path, response.getStatus());
            return null;
        }

        String data = response.getContentAsString();
        if (data == null || data.isEmpty()) {
            LOGGER.error("CloudStore: received empty response from uri '{}' status:{}",
                    path, response.getStatus());
            return null;
        }

        return data;
    }
 
Example 7
Source File: JettyReactiveHttpClientService.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse executeRequest(String url) throws Exception {
    httpClient.start();

    ContentResponse contentResponse = httpClient.newRequest(url)
            .method(HttpMethod.GET)
            .header(HEADER_KEY_CLIENT_TYPE, getClientType().getValue())
            .send();

    httpClient.stop();

    return new ClientResponse(contentResponse.getContentAsString(), contentResponse.getStatus());
}
 
Example 8
Source File: HttpCommandProxy.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
protected String sendRequest(String path, String data, HttpMethod method) throws Exception {
    String url = getServiceUrl(path);
    Request request = httpClient.newRequest(url).method(method).
            header(HttpHeader.CONTENT_TYPE, "application/json");
    if (data != null) {
        request.content(new StringContentProvider(data));
    }
    ContentResponse response = request.send();
    return response.getContentAsString();
}
 
Example 9
Source File: SystemTest.java    From app-runner with MIT License 5 votes vote down vote up
@Test
public void appsCanGetAuthors() throws Exception {
    ContentResponse resp = client.GET(appRunnerUrl + "/api/v1/apps/maven");
    JSONObject respJson = new JSONObject(resp.getContentAsString());
    assertThat(
        respJson.getString("contributors"),
        is("Author Test"));
}
 
Example 10
Source File: HttpCertSigner.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
public String generateX509Certificate(String csr, String keyUsage, int expireMins) {
    
    // Key Usage value used in Go - https://golang.org/src/crypto/x509/x509.go?s=18153:18173#L558
    // we're only interested in ExtKeyUsageClientAuth - with value of 2
    
    List<Integer> extKeyUsage = null;
    if (InstanceProvider.ZTS_CERT_USAGE_CLIENT.equals(keyUsage)) {
        extKeyUsage = new ArrayList<>();
        extKeyUsage.add(2);
    }

    ContentResponse response = null;
    for (int i = 0; i < requestRetryCount; i++) {
        response = processX509CertRequest(csr, extKeyUsage, expireMins, i + 1);
        if (response != null) {
            break;
        }
    }
    if (response == null) {
        return null;
    }
    
    if (response.getStatus() != HttpStatus.CREATED_201) {
        LOGGER.error("unable to fetch requested uri '" + x509CertUri +
                "' status: " + response.getStatus());
        return null;
    }

    String data = response.getContentAsString();
    if (data == null || data.isEmpty()) {
        LOGGER.error("received empty response from uri '" + x509CertUri +
                "' status: " + response.getStatus());
        return null;
    }

    X509CertSignObject pemCert = JSON.fromString(data, X509CertSignObject.class);
    return (pemCert != null) ? pemCert.getPem() : null;
}
 
Example 11
Source File: HTracedProcess.java    From incubator-retired-htrace with Apache License 2.0 5 votes vote down vote up
public String getServerVersionJson() throws Exception {
  ContentResponse response = httpClient.GET(
      new URI(String.format("http://%s/server/version", httpAddr)));
  Assert.assertEquals("application/json", response.getMediaType());
  Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
  return response.getContentAsString();
}
 
Example 12
Source File: WaveAnalyticsTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void runDataflow(String dataflowId) throws StageException {
  try {
    ContentResponse response = httpClient.newRequest(restEndpoint + String.format(startDataflow, dataflowId))
        .method(HttpMethod.PUT)
        .header("Authorization", "OAuth " + connection.getConfig().getSessionId())
        .send();
    int statusCode = response.getStatus();
    String content = response.getContentAsString();

    LOG.info("PUT dataflow with result {} content {}", statusCode, content);
  } catch (InterruptedException | TimeoutException | ExecutionException e) {
    LOG.error("PUT dataflow with result {}", e.getMessage());
    throw new StageException(Errors.WAVE_03, e.getMessage(), e);
  }
}
 
Example 13
Source File: FrontierSiliconRadioConnection.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Performs a request to the radio with addition parameters.
 *
 * Typically used for changing parameters.
 *
 * @param REST
 *            API requestString, e.g. "SET/netRemote.sys.power"
 * @param params
 *            , e.g. "value=1"
 * @return request result
 * @throws IOException if the request failed.
 */
public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException {
    // 3 retries upon failure
    for (int i = 0; i < 3; i++) {
        if (!isLoggedIn && !doLogin()) {
            continue; // not logged in and login was not successful - try again!
        }

        final String url = "http://" + hostname + ":" + port + FrontierSiliconRadioConstants.CONNECTION_PATH + "/"
                + requestString + "?pin=" + pin + "&sid=" + sessionId
                + (params == null || params.trim().length() == 0 ? "" : "&" + params);

        logger.trace("calling url: '{}'", url);

        Request request = httpClient.newRequest(url).method(HttpMethod.GET).timeout(SOCKET_TIMEOUT,
                TimeUnit.MILLISECONDS);

        try {
            ContentResponse response = request.send();
            final int statusCode = response.getStatus();
            if (statusCode != HttpStatus.OK_200) {
                /*-
                 * Issue: https://github.com/eclipse/smarthome/issues/2548
                 * If the session expired, we might get a 404 here. That's ok, remember that we are not logged-in
                 * and try again. Print warning only if this happens in the last iteration.
                 */
                if (i >= 2) {
                    String reason = response.getReason();
                    logger.warn("Method failed: {}  {}", statusCode, reason);
                }
                isLoggedIn = false;
                continue;
            }

            final String responseBody = response.getContentAsString();
            if (!responseBody.isEmpty()) {
                logger.trace("got result: {}", responseBody);
            } else {
                logger.debug("got empty result");
                isLoggedIn = false;
                continue;
            }

            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                return result;
            }

            isLoggedIn = false;
            continue; // try again
        } catch (Exception e) {
            logger.error("Fatal transport error: {}", e.toString());
            throw new IOException(e);
        }
    }
    isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?)
    return null;
}
 
Example 14
Source File: FrontierSiliconRadioConnection.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
 * future requests.
 *
 * @return <code>true</code> if login was successful; <code>false</code> otherwise.
 * @throws IOException if communication with the radio failed, e.g. because the device is not reachable.
 */
public boolean doLogin() throws IOException {
    isLoggedIn = false; // reset login flag

    final String url = "http://" + hostname + ":" + port + FrontierSiliconRadioConstants.CONNECTION_PATH
            + "/CREATE_SESSION?pin=" + pin;

    logger.trace("opening URL: {}", url);

    Request request = httpClient.newRequest(url).method(HttpMethod.GET).timeout(SOCKET_TIMEOUT,
            TimeUnit.MILLISECONDS);

    try {
        ContentResponse response = request.send();
        int statusCode = response.getStatus();
        if (statusCode != HttpStatus.OK_200) {
            String reason = response.getReason();
            logger.debug("Communication with radio failed: {} {}", statusCode, reason);
            if (statusCode == HttpStatus.FORBIDDEN_403) {
                throw new IllegalStateException("Radio does not allow connection, maybe wrong pin?");
            }
            throw new IOException("Communication with radio failed, return code: " + statusCode);
        }

        final String responseBody = response.getContentAsString();
        if (!responseBody.isEmpty()) {
            logger.trace("login response: {}", responseBody);
        }

        final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
        if (result.isStatusOk()) {
            logger.trace("login successful");
            sessionId = result.getSessionId();
            isLoggedIn = true;
            return true; // login successful :-)
        }

    } catch (Exception e) {
        logger.debug("Fatal transport error: {}", e.toString());
        throw new IOException(e);
    }

    return false; // login not successful
}
 
Example 15
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request,
        Fields fields) throws OAuthResponseException, OAuthException, IOException {

    int statusCode = 0;
    String content = "";
    try {
        final FormContentProvider entity = new FormContentProvider(fields);
        final ContentResponse response = AccessController
                .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
                    Request requestWithContent = request.content(entity);
                    return requestWithContent.send();
                });

        statusCode = response.getStatus();
        content = response.getContentAsString();

        if (statusCode == HttpStatus.OK_200) {
            AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class);
            jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response
            logger.info("grant type {} to URL {} success", grantType, request.getURI());
            return jsonResponse;
        } else if (statusCode == HttpStatus.BAD_REQUEST_400) {
            OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class);
            logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType,
                    request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription());

            throw errorResponse;
        } else {
            logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(),
                    statusCode);
            throw new OAuthException("Bad http response, http code " + statusCode);
        }
    } catch (PrivilegedActionException pae) {
        Exception underlyingException = pae.getException();
        if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException
                || underlyingException instanceof ExecutionException) {
            throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
        }
        // Dont know what exception it is, wrap it up and throw it out
        throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
    } catch (JsonSyntaxException e) {
        throw new OAuthException(String.format(
                "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s",
                statusCode, content), e);
    }
}
 
Example 16
Source File: SolrFulltextSearchImpl.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private FulltextSearchHit[] queryIndex(
      FulltextSearchQuery query, HttpClient httpClient)
      throws Exception {

   if (httpClient.isStopped()) {
      throw new FulltextSearchException("The client has been stopped");
   }
   
   
   Request request = httpClient.newRequest(query.getEndpoint());
   
   // Limit response content buffer to 512 KiB
   FutureResponseListener listener =
      new FutureResponseListener(request, 10 * 1024 * 1024); // 100 MB size
   
   request.param("q", query.getQuery());
   request.param("wt", "json");

   final String searchParams = query.getParams();
   if (searchParams!=null && !searchParams.isEmpty()) {
      final String[] params = searchParams.split("&");
      for (int i=0; i<params.length; i++) {
         if (params[i]!=null) {
            String kv[] = params[i].split("=");
            if (kv.length==2 && kv[0]!=null && !(kv[0].isEmpty())) {
               if (!(kv[0].equals("wt"))) {
                  try {
                     final String val = kv[1]==null ? "" : 
                        URLDecoder.decode(kv[1], "UTF-8");
                     request.param(kv[0], val);
                  } catch (Exception e) {
                     if (log.isInfoEnabled()) {
                        log.info("Solr search param: '" + params[i] + "'" +
                              "' can't be URL decoded. Will be ignored...");
                     }
                  }
               }
            } else {
               if (log.isInfoEnabled()) {
                  log.info("Invalid Solr search param: '" + params[i] + "'");
                  log.info("Will be ignored...");
               }
            }
         }
      }
   }
   
   final Integer queryTimeoutSpecified = query.getSearchTimeout();
   final Integer queryTimeoutUsed = 
         queryTimeoutSpecified==null ?
         FTS.Options.DEFAULT_TIMEOUT : queryTimeoutSpecified;
   
   request.send(listener);
   ContentResponse resp = listener.get(queryTimeoutUsed, TimeUnit.MILLISECONDS);

   final int statusCode = resp.getStatus();
   if (statusCode != 200) {

      throw new FulltextSearchException("Status code != 200 received from "
            + "external fulltext service: " + statusCode);

   }

   final String jsonStr = resp.getContentAsString();
   final JSONObject json = new JSONObject(jsonStr);

   return constructFulltextSearchList(json, query);

}
 
Example 17
Source File: HttpCallOperatorFactory.java    From digdag with Apache License 2.0 4 votes vote down vote up
@Override
public TaskResult runTask()
{
    UserSecretTemplate uriTemplate = UserSecretTemplate.of(params.get("_command", String.class));
    boolean uriIsSecret = uriTemplate.containsSecrets();
    URI uri = URI.create(uriTemplate.format(context.getSecrets()));
    String mediaTypeOverride = params.getOptional("content_type_override", String.class).orNull();

    ContentResponse response;

    HttpClient httpClient = client();
    try {
        response = runHttp(httpClient, uri, uriIsSecret);
    }
    finally {
        stop(httpClient);
    }

    String content;
    if (Strings.isNullOrEmpty(mediaTypeOverride)) {
        // This ContentResponse::getContentAsString considers ;charset= parameter
        // of Content-Type. If not set, it uses UTF-8.
        content = response.getContentAsString();
    }
    else {
        // This logic mimics how org.eclipse.jetty.client.HttpContentResponse::getContentAsString handles Content-Type
        int index = mediaTypeOverride.toLowerCase(ENGLISH).indexOf("charset=");
        if (index > 0) {
            String encoding = mediaTypeOverride.substring(index + "charset=".length());
            try {
                content = new String(response.getContent(), encoding);
            }
            catch (UnsupportedEncodingException e) {
                throw new UnsupportedCharsetException(encoding);
            }
        }
        else {
            content = new String(response.getContent(), UTF_8);
        }
    }

    // validate response length
    if (content.length() > maxResponseContentSize) {
        throw new TaskExecutionException("Response content too large: " + content.length() + " > " + maxResponseContentSize);
    }

    // parse content based on response media type
    String digFileSource = reformatDigFile(content, response.getMediaType(), mediaTypeOverride);
    // write to http_call.dig file
    Path workflowPath = writeDigFile(digFileSource);

    // following code is almost same with CallOperatorFactory.CallOperator.runTask
    Config config = request.getConfig();

    WorkflowFile workflowFile;
    try {
        workflowFile = projectLoader.loadWorkflowFileFromPath(
                workspace.getProjectPath(), workflowPath, config.getFactory().create());
    }
    catch (IOException ex) {
        throw propagateIoException(ex, WORKFLOW_FILE_NAME, ConfigException::new);
    }

    Config def = workflowFile.toWorkflowDefinition().getConfig();

    return TaskResult.defaultBuilder(request)
        .subtaskConfig(def)
        .build();
}
 
Example 18
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request,
        Fields fields) throws OAuthResponseException, OAuthException, IOException {
    int statusCode = 0;
    String content = "";
    try {
        final FormContentProvider entity = new FormContentProvider(fields);
        final ContentResponse response = AccessController
                .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
                    Request requestWithContent = request.content(entity);
                    return requestWithContent.send();
                });

        statusCode = response.getStatus();
        content = response.getContentAsString();

        if (statusCode == HttpStatus.OK_200) {
            AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class);
            jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response
            logger.debug("grant type {} to URL {} success", grantType, request.getURI());
            return jsonResponse;
        } else if (statusCode == HttpStatus.BAD_REQUEST_400) {
            OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class);
            logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType,
                    request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription());

            throw errorResponse;
        } else {
            logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(),
                    statusCode);
            throw new OAuthException("Bad http response, http code " + statusCode);
        }
    } catch (PrivilegedActionException pae) {
        Exception underlyingException = pae.getException();
        if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException
                || underlyingException instanceof ExecutionException) {
            throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
        }
        // Dont know what exception it is, wrap it up and throw it out
        throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
    } catch (JsonSyntaxException e) {
        throw new OAuthException(String.format(
                "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s",
                statusCode, content), e);
    }
}
 
Example 19
Source File: HTTPAction.java    From nadia with Apache License 2.0 4 votes vote down vote up
@Override
public HashMap<String, String> execute(Frame frame) {
	
	 	/*
	 	 * WikiAPI: http://www.mediawiki.org/wiki/Extension:MobileFrontend
	 	 * e.g.,
	 	 * url="http://en.wikipedia.org/w/api.php?format=xml&action=query&prop=extracts&explaintext&exsentences=3&titles=Edinburgh";
	 	 * xpath="//extract";
	 	 * 
	 	 * or
	 	 * 
	 	 * curl --data "state=on" http://mmt.et.hs-wismar.de:8080/Lightbulb/Lightbulb
	 	 * 
	 	 */
	
		String replaced_url=replaceSlotMarkers(url, frame);
		String replaced_params=replaceSlotMarkers(params, frame);
		String[] params_arr = replaced_params.split("&");
		
		String result="Sorry, that did not work. ";
        try{
        		        	 
        	ContentResponse response;
        	Request request;
       		
        	request = client.newRequest(replaced_url);

        	//choose method
        	if(method.toLowerCase().equals("get")){
        		request.method(HttpMethod.GET);
        	}
        	else{
        		request.method(HttpMethod.POST);
        	}
        	
        	//process parameters
        	String[] key_value;
        	for(String paramPair : params_arr){
        		key_value=paramPair.split("=");
        		if(key_value.length>1) request.param(key_value[0],key_value[1]);
        		else request.param(key_value[0], "");
        	}       	
        	
        	logger.info("requesting: "+request.getURI()+", "+request.getParams().toString());
        	response = request.send();
        	logger.info("HTTP status: "+response.getStatus());
        	
        	String xml = response.getContentAsString();
        	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
        	Document doc = builder.parse(new InputSource(new StringReader(xml)));
        	 
	        XPathFactory xPathfactory = XPathFactory.newInstance();
	        XPath xPath = xPathfactory.newXPath();
	        XPathExpression expr = xPath.compile(xpath);
	        result = (String) expr.evaluate(doc, XPathConstants.STRING);
	        
	        //Postprocessing
	        result = result.replaceAll("\\s\\(.*?\\)", ""); //remove content in brackets
	        result = result.replaceAll("\\s\\[.*?\\]", "");
        }
        catch(Exception ex){
        	ex.printStackTrace();
        }
        executionResults.put("result", result);
		return executionResults;
}
 
Example 20
Source File: SystemTest.java    From app-runner with MIT License 4 votes vote down vote up
private static JSONObject getAllApps() throws InterruptedException, ExecutionException, TimeoutException {
    ContentResponse resp = client.GET(appRunnerUrl + "/api/v1/apps");
    assertThat(resp.getStatus(), is(200));
    return new JSONObject(resp.getContentAsString());
}