Search in sources :

Example 6 with ClientHttpRequest

use of org.apache.geode.management.internal.web.http.ClientHttpRequest in project geode by apache.

the class RestHttpOperationInvokerJUnitTest method testCreateHttpRequestWithEnvironmentVariables.

@Test
public void testCreateHttpRequestWithEnvironmentVariables() {
    final Map<String, String> commandOptions = new HashMap<>(2);
    commandOptions.put("name", "ElLibreDeCongress");
    commandOptions.put("isbn", "${ISBN}");
    final Map<String, String> environment = new HashMap<>(2);
    environment.put("ISBN", "0-987654321");
    environment.put("VAR", "test");
    final CommandRequest command = createCommandRequest("get-book", commandOptions, environment);
    final ClientHttpRequest request = getOperationInvoker().createHttpRequest(command);
    assertNotNull(request);
    assertEquals("GET http://host.domain.com/service/v1/libraries/{name}/books/{isbn}", request.getLink().toHttpRequestLine());
    assertEquals("${ISBN}", request.getParameterValue("isbn"));
    assertFalse(request.getParameters().containsKey("ISBN"));
    assertEquals("0-987654321", request.getParameterValue(RestHttpOperationInvoker.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "ISBN"));
    assertFalse(request.getParameters().containsKey("VAR"));
    assertEquals("test", request.getParameterValue(RestHttpOperationInvoker.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "VAR"));
}
Also used : CommandRequest(org.apache.geode.management.internal.cli.CommandRequest) HashMap(java.util.HashMap) ClientHttpRequest(org.apache.geode.management.internal.web.http.ClientHttpRequest) UnitTest(org.apache.geode.test.junit.categories.UnitTest) Test(org.junit.Test)

Example 7 with ClientHttpRequest

use of org.apache.geode.management.internal.web.http.ClientHttpRequest in project geode by apache.

the class RestHttpOperationInvokerJUnitTest method testCreateHttpRequestWithFileData.

@Test
public void testCreateHttpRequestWithFileData() {
    final Map<String, String> commandOptions = Collections.singletonMap("isbn", "0-123456789");
    final byte[][] fileData = { "/path/to/book/content.txt".getBytes(), "Once upon a time in a galaxy far, far away...".getBytes() };
    final CommandRequest command = createCommandRequest("add-book", commandOptions, fileData);
    final ClientHttpRequest request = getOperationInvoker().createHttpRequest(command);
    assertNotNull(request);
    assertEquals("POST http://host.domain.com/service/v1/libraries/{name}/books", request.getLink().toHttpRequestLine());
    assertEquals("0-123456789", request.getParameterValue("isbn"));
    assertTrue(request.getParameters().containsKey(RestHttpOperationInvoker.RESOURCES_REQUEST_PARAMETER));
    assertTrue(request.getParameterValue(RestHttpOperationInvoker.RESOURCES_REQUEST_PARAMETER) instanceof Resource);
    final List<Object> resources = request.getParameterValues(RestHttpOperationInvoker.RESOURCES_REQUEST_PARAMETER);
    assertNotNull(resources);
    assertFalse(resources.isEmpty());
    assertEquals(1, resources.size());
}
Also used : CommandRequest(org.apache.geode.management.internal.cli.CommandRequest) Resource(org.springframework.core.io.Resource) ClientHttpRequest(org.apache.geode.management.internal.web.http.ClientHttpRequest) UnitTest(org.apache.geode.test.junit.categories.UnitTest) Test(org.junit.Test)

Example 8 with ClientHttpRequest

use of org.apache.geode.management.internal.web.http.ClientHttpRequest in project geode by apache.

the class AbstractHttpOperationInvoker method downloadResponseToTempFile.

protected Object downloadResponseToTempFile(ClientHttpRequest request, Map<String, ?> uriVariables) {
    final URI url = request.getURL(uriVariables);
    // Optional Accept header
    RequestCallback requestCallback = r -> {
        r.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
        HttpHeaders header = request.getHeaders();
        r.getHeaders().setAll(request.getHeaders().toSingleValueMap());
    };
    // Streams the response instead of loading it all in memory
    ResponseExtractor<Object> responseExtractor = resp -> {
        MediaType mediaType = resp.getHeaders().getContentType();
        if (mediaType.equals(MediaType.APPLICATION_JSON)) {
            return org.apache.commons.io.IOUtils.toString(resp.getBody(), "UTF-8");
        } else {
            Path tempFile = Files.createTempFile("fileDownload", "");
            if (tempFile.toFile().exists()) {
                FileUtils.deleteQuietly(tempFile.toFile());
            }
            Files.copy(resp.getBody(), tempFile);
            return tempFile;
        }
    };
    return getRestTemplate().execute(url, org.springframework.http.HttpMethod.GET, requestCallback, responseExtractor);
}
Also used : Arrays(java.util.Arrays) QueryExp(javax.management.QueryExp) DistributedSystemMXBean(org.apache.geode.management.DistributedSystemMXBean) MBeanJMXAdapter(org.apache.geode.management.internal.MBeanJMXAdapter) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) LogService(org.apache.geode.internal.logging.LogService) Map(java.util.Map) HttpHeader(org.apache.geode.management.internal.web.http.HttpHeader) URI(java.net.URI) Path(java.nio.file.Path) RestTemplate(org.springframework.web.client.RestTemplate) ResponseExtractor(org.springframework.web.client.ResponseExtractor) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) Set(java.util.Set) ObjectName(javax.management.ObjectName) Executors(java.util.concurrent.Executors) List(java.util.List) Logger(org.apache.logging.log4j.Logger) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) ClientHttpRequest(org.apache.geode.management.internal.web.http.ClientHttpRequest) Entry(java.util.Map.Entry) HttpMBeanProxyFactory(org.apache.geode.management.internal.web.shell.support.HttpMBeanProxyFactory) IOUtils(org.apache.geode.internal.util.IOUtils) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) QueryParameterSource(org.apache.geode.management.internal.web.domain.QueryParameterSource) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) Link(org.apache.geode.management.internal.web.domain.Link) ManagementConstants(org.apache.geode.management.internal.ManagementConstants) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Gfsh(org.apache.geode.management.internal.cli.shell.Gfsh) SimpleClientHttpRequestFactory(org.springframework.http.client.SimpleClientHttpRequestFactory) Iterator(java.util.Iterator) Files(java.nio.file.Files) UriUtils(org.apache.geode.management.internal.web.util.UriUtils) GemFireVersion(org.apache.geode.internal.GemFireVersion) FileUtils(org.apache.commons.io.FileUtils) ResourceAccessException(org.springframework.web.client.ResourceAccessException) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) RequestCallback(org.springframework.web.client.RequestCallback) SerializableObjectHttpMessageConverter(org.apache.geode.management.internal.web.http.converter.SerializableObjectHttpMessageConverter) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) StringUtils(org.apache.geode.internal.lang.StringUtils) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpMethod(org.apache.geode.management.internal.web.http.HttpMethod) ResponseEntity(org.springframework.http.ResponseEntity) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) Path(java.nio.file.Path) HttpHeaders(org.springframework.http.HttpHeaders) RequestCallback(org.springframework.web.client.RequestCallback) MediaType(org.springframework.http.MediaType) URI(java.net.URI)

Example 9 with ClientHttpRequest

use of org.apache.geode.management.internal.web.http.ClientHttpRequest in project geode by apache.

the class AbstractHttpOperationInvoker method invoke.

/**
   * Invoke an operation identified by name on a remote resource identified by name with the given
   * arguments. The intent of this method is to invoke an arbitrary operation on an MBean located in
   * the remote MBeanServer.
   * 
   * @param resourceName name/url (object name) of the remote resource (MBea) on which operation is
   *        to be invoked.
   * @param operationName name of the operation to be invoked.
   * @param params an array of arguments for the parameters to be set when the operation is invoked.
   * @param signature an array containing the signature of the operation.
   * @return result of the operation invocation.
   * @throws MBeanAccessException if an MBean access error occurs.
   * @throws RestApiCallForCommandNotFoundException if the REST API web service endpoint for
   *         invoking an operation on an MBean does not exists!
   * @see #createHttpRequest(org.apache.geode.management.internal.web.domain.Link)
   * @see #findLink(String)
   * @see #send(org.apache.geode.management.internal.web.http.ClientHttpRequest, Class)
   */
// TODO research the use of Jolokia instead
@Override
public Object invoke(final String resourceName, final String operationName, final Object[] params, final String[] signature) {
    final Link link = findLink(MBEAN_OPERATION_LINK_RELATION);
    if (link != null) {
        final ClientHttpRequest request = createHttpRequest(link);
        request.addParameterValues("resourceName", resourceName);
        request.addParameterValues("operationName", operationName);
        request.addParameterValues("signature", (Object[]) signature);
        // TODO may need to convert method parameter
        request.addParameterValues("parameters", params);
        try {
            return IOUtils.deserializeObject(send(request, byte[].class));
        } catch (IOException e) {
            throw new MBeanAccessException(String.format("De-serializing the result from invoking operation (%1$s) on MBean (%2$s) failed!", resourceName, operationName), e);
        } catch (ClassNotFoundException e) {
            throw new MBeanAccessException(String.format("The Class type of the result from invoking operation (%1$s) on MBean (%2$s) was not found!", resourceName, operationName), e);
        }
    } else {
        printSevere("Invoking operation (%1$s) on MBean (%2$s) is currently an unsupported operation!", operationName, resourceName);
        throw new RestApiCallForCommandNotFoundException(MBEAN_OPERATION_LINK_RELATION);
    }
}
Also used : IOException(java.io.IOException) ClientHttpRequest(org.apache.geode.management.internal.web.http.ClientHttpRequest) Link(org.apache.geode.management.internal.web.domain.Link)

Example 10 with ClientHttpRequest

use of org.apache.geode.management.internal.web.http.ClientHttpRequest in project geode by apache.

the class SimpleHttpOperationInvokerJUnitTest method testCreateHttpRequest.

@Test
public void testCreateHttpRequest() throws Exception {
    final CommandRequest command = createCommandRequest("save resource --path=/path/to/file --size=1024KB");
    final ClientHttpRequest request = getOperationInvoker().createHttpRequest(command);
    assertNotNull(request);
    assertEquals(SimpleHttpOperationInvoker.USER_AGENT_HTTP_REQUEST_HEADER_VALUE, request.getHeaderValue(HttpHeader.USER_AGENT.getName()));
    final Link requestLink = request.getLink();
    assertNotNull(requestLink);
    assertTrue(toString(requestLink).startsWith("POST"));
    assertTrue(toString(requestLink).endsWith(command.getInput()));
}
Also used : CommandRequest(org.apache.geode.management.internal.cli.CommandRequest) ClientHttpRequest(org.apache.geode.management.internal.web.http.ClientHttpRequest) Link(org.apache.geode.management.internal.web.domain.Link) Test(org.junit.Test) UnitTest(org.apache.geode.test.junit.categories.UnitTest)

Aggregations

ClientHttpRequest (org.apache.geode.management.internal.web.http.ClientHttpRequest)10 Link (org.apache.geode.management.internal.web.domain.Link)5 IOException (java.io.IOException)4 CommandRequest (org.apache.geode.management.internal.cli.CommandRequest)4 UnitTest (org.apache.geode.test.junit.categories.UnitTest)4 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 Map (java.util.Map)2 Entry (java.util.Map.Entry)2 Set (java.util.Set)2 QueryParameterSource (org.apache.geode.management.internal.web.domain.QueryParameterSource)2 AuthenticationFailedException (org.apache.geode.security.AuthenticationFailedException)2 NotAuthorizedException (org.apache.geode.security.NotAuthorizedException)2 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 URI (java.net.URI)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1