Search in sources :

Example 26 with WebClient

use of org.apache.cxf.jaxrs.client.WebClient in project ddf by codice.

the class TestOpenSearchSource method testQueryBySearchPhraseContentTypeSet.

@Test
public void testQueryBySearchPhraseContentTypeSet() throws UnsupportedQueryException, URISyntaxException, IOException {
    WebClient client = mock(WebClient.class);
    Response clientResponse = mock(Response.class);
    when(client.get()).thenReturn(clientResponse);
    when(clientResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(clientResponse.getEntity()).thenReturn(getSampleAtomStream());
    SecureCxfClientFactory factory = getMockFactory(client);
    OverriddenOpenSearchSource source = new OverriddenOpenSearchSource(FILTER_ADAPTER, encryptionService);
    InputTransformer inputTransformer = mock(InputTransformer.class);
    MetacardImpl generatedMetacard = new MetacardImpl();
    generatedMetacard.setMetadata(getSample());
    generatedMetacard.setId(SAMPLE_ID);
    generatedMetacard.setContentTypeName("myType");
    try {
        when(inputTransformer.transform(isA(InputStream.class))).thenReturn(generatedMetacard);
        when(inputTransformer.transform(isA(InputStream.class), isA(String.class))).thenReturn(generatedMetacard);
    } catch (IOException e) {
        fail();
    } catch (CatalogTransformerException e) {
        fail();
    }
    source.setInputTransformer(inputTransformer);
    source.setEndpointUrl("http://localhost:8181/services/catalog/query");
    source.init();
    source.setParameters(DEFAULT_PARAMETERS);
    source.factory = factory;
    Filter filter = filterBuilder.attribute(Metacard.METADATA).like().text(SAMPLE_SEARCH_PHRASE);
    SourceResponse response = source.query(new QueryRequestImpl(new QueryImpl(filter)));
    Assert.assertEquals(1, response.getHits());
    List<Result> results = response.getResults();
    Assert.assertTrue(results.size() == 1);
    Result result = results.get(0);
    Metacard metacard = result.getMetacard();
    Assert.assertNotNull(metacard);
    Assert.assertEquals("myType", metacard.getContentTypeName());
}
Also used : SourceResponse(ddf.catalog.operation.SourceResponse) SecureCxfClientFactory(org.codice.ddf.cxf.SecureCxfClientFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) InputTransformer(ddf.catalog.transform.InputTransformer) WebClient(org.apache.cxf.jaxrs.client.WebClient) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Result(ddf.catalog.data.Result) Response(javax.ws.rs.core.Response) ResourceResponse(ddf.catalog.operation.ResourceResponse) SourceResponse(ddf.catalog.operation.SourceResponse) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Metacard(ddf.catalog.data.Metacard) Filter(org.opengis.filter.Filter) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) Test(org.junit.Test)

Example 27 with WebClient

use of org.apache.cxf.jaxrs.client.WebClient in project ddf by codice.

the class TestOpenSearchSiteUtil method populateNullTemporal.

/**
     * Verify that passing in null will still remove the parameters from the URL.
     */
@Test
public void populateNullTemporal() {
    StringBuilder resultStr = new StringBuilder(url);
    WebClient webClient = WebClient.create(url.toString());
    OpenSearchSiteUtil.populateTemporal(webClient, null, Arrays.asList("q,src,mr,start,count,mt,dn,lat,lon,radius,bbox,polygon,dtstart,dtend,dateName,filter,sort".split(",")));
    String urlStr = webClient.getCurrentURI().toString();
    assertTrue(urlStr.indexOf(OpenSearchSiteUtil.TIME_START) == -1);
    assertTrue(urlStr.indexOf(OpenSearchSiteUtil.TIME_END) == -1);
    assertTrue(urlStr.indexOf(OpenSearchSiteUtil.TIME_NAME) == -1);
}
Also used : Matchers.containsString(org.hamcrest.Matchers.containsString) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Example 28 with WebClient

use of org.apache.cxf.jaxrs.client.WebClient in project ddf by codice.

the class TestOpenSearchSiteUtil method populateContextual.

@Test
public void populateContextual() {
    String searchPhrase = "TestQuery123";
    assertTrue(url.indexOf(OpenSearchSiteUtil.SEARCH_TERMS) != -1);
    WebClient webClient = WebClient.create(url.toString());
    OpenSearchSiteUtil.populateContextual(webClient, searchPhrase, Arrays.asList("q,src,mr,start,count,mt,dn,lat,lon,radius,bbox,polygon,dtstart,dtend,dateName,filter,sort".split(",")));
    String urlStr = webClient.getCurrentURI().toString();
    assertTrue(urlStr.indexOf(searchPhrase) != -1);
    assertTrue(urlStr.indexOf("?" + OpenSearchSiteUtil.SEARCH_TERMS) != -1);
    try {
        new URL(urlStr.toString());
    } catch (MalformedURLException mue) {
        fail("URL is not valid: " + mue.getMessage());
    }
    LOGGER.info("URL after contextual population: {}", urlStr.toString());
}
Also used : MalformedURLException(java.net.MalformedURLException) Matchers.containsString(org.hamcrest.Matchers.containsString) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL) Test(org.junit.Test)

Example 29 with WebClient

use of org.apache.cxf.jaxrs.client.WebClient in project ddf by codice.

the class URLResourceReader method retrieveHttpProduct.

private ResourceResponse retrieveHttpProduct(URI resourceURI, String productName, String bytesToSkip, Map<String, Serializable> properties) throws ResourceNotFoundException {
    try {
        LOGGER.debug("Opening connection to: {}", resourceURI.toString());
        WebClient client = getWebClient(resourceURI.toString(), properties);
        Object subjectObj = properties.get(SecurityConstants.SECURITY_SUBJECT);
        if (subjectObj != null) {
            Subject subject = (Subject) subjectObj;
            LOGGER.debug("Setting Subject on webclient: {}", subject);
            RestSecurity.setSubjectOnClient(subject, client);
        }
        Response response = client.get();
        MultivaluedMap<String, Object> headers = response.getHeaders();
        List<Object> cdHeaders = headers.get(HttpHeaders.CONTENT_DISPOSITION);
        if (cdHeaders != null && !cdHeaders.isEmpty()) {
            String contentHeader = (String) cdHeaders.get(0);
            productName = StringUtils.defaultIfBlank(handleContentDispositionHeader(contentHeader), productName);
        }
        String mimeType = getMimeType(resourceURI, productName);
        Response clientResponse = client.get();
        InputStream is = null;
        Object entityObj = clientResponse.getEntity();
        if (entityObj instanceof InputStream) {
            is = (InputStream) entityObj;
            if (Response.Status.OK.getStatusCode() != clientResponse.getStatus() && Response.Status.PARTIAL_CONTENT.getStatusCode() != clientResponse.getStatus()) {
                String error = null;
                try {
                    if (is != null) {
                        error = IOUtils.toString(is);
                    }
                } catch (IOException ioe) {
                    LOGGER.debug("Could not convert error message to a string for output.", ioe);
                }
                String errorMsg = "Received error code while retrieving resource (status " + clientResponse.getStatus() + "): " + error;
                throw new ResourceNotFoundException(errorMsg);
            }
        } else {
            throw new ResourceNotFoundException("Received null response while retrieving resource.");
        }
        long responseBytesSkipped = 0L;
        if (headers.getFirst(HttpHeaders.CONTENT_RANGE) != null) {
            String contentRangeHeader = String.valueOf(headers.getFirst(HttpHeaders.CONTENT_RANGE));
            responseBytesSkipped = Long.parseLong(StringUtils.substringBetween(contentRangeHeader.toLowerCase(), "bytes ", "-"));
        }
        alignStream(is, Long.parseLong(bytesToSkip), responseBytesSkipped);
        return new ResourceResponseImpl(new ResourceImpl(new BufferedInputStream(is), mimeType, FilenameUtils.getName(productName)));
    } catch (MimeTypeResolutionException | IOException | WebApplicationException e) {
        LOGGER.info("Error retrieving resource", e);
        throw new ResourceNotFoundException("Unable to retrieve resource at: " + resourceURI.toString(), e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) WebClient(org.apache.cxf.jaxrs.client.WebClient) Subject(ddf.security.Subject) ResourceResponse(ddf.catalog.operation.ResourceResponse) Response(javax.ws.rs.core.Response) MimeTypeResolutionException(ddf.mime.MimeTypeResolutionException) BufferedInputStream(java.io.BufferedInputStream) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException)

Example 30 with WebClient

use of org.apache.cxf.jaxrs.client.WebClient in project ddf by codice.

the class ResourceReaderTest method testSetRedirect.

@Test
public void testSetRedirect() throws Exception {
    URLResourceReader resourceReader = new URLResourceReader(mimeTypeMapper);
    WebClient client = resourceReader.getWebClient(HTTP_SCHEME_PLUS_SEP + HOST + TEST_PATH + JPEG_FILE_NAME_1, new HashMap<>());
    assertFalse(WebClient.getConfig(client).getHttpConduit().getClient().isAutoRedirect());
    resourceReader.setFollowRedirects(true);
    client = resourceReader.getWebClient(HTTP_SCHEME_PLUS_SEP + HOST + TEST_PATH + JPEG_FILE_NAME_1, new HashMap<>());
    assertTrue(WebClient.getConfig(client).getHttpConduit().getClient().isAutoRedirect());
    resourceReader.setFollowRedirects(false);
    client = resourceReader.getWebClient(HTTP_SCHEME_PLUS_SEP + HOST + TEST_PATH + JPEG_FILE_NAME_1, new HashMap<>());
    assertFalse(WebClient.getConfig(client).getHttpConduit().getClient().isAutoRedirect());
}
Also used : HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Aggregations

WebClient (org.apache.cxf.jaxrs.client.WebClient)723 Test (org.junit.Test)400 Response (javax.ws.rs.core.Response)351 URL (java.net.URL)198 HashMap (java.util.HashMap)100 Book (org.apache.cxf.systest.jaxrs.security.Book)94 ArrayList (java.util.ArrayList)88 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)87 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)77 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)60 Bus (org.apache.cxf.Bus)48 SpringBusFactory (org.apache.cxf.bus.spring.SpringBusFactory)46 Test (org.testng.annotations.Test)46 Form (javax.ws.rs.core.Form)44 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)42 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)40 JwtAuthenticationClientFilter (org.apache.cxf.rs.security.jose.jaxrs.JwtAuthenticationClientFilter)32 InputStream (java.io.InputStream)28 ResponseProcessingException (javax.ws.rs.client.ResponseProcessingException)28 Document (org.w3c.dom.Document)27