Search in sources :

Example 66 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project ddf by codice.

the class CatalogServiceImplTest method testAddDocumentWithMetadataPositiveCase.

@Test
@SuppressWarnings({ "unchecked" })
public void testAddDocumentWithMetadataPositiveCase() throws Exception {
    CatalogFramework framework = givenCatalogFramework();
    HttpHeaders headers = createHeaders(Collections.singletonList(MediaType.APPLICATION_JSON));
    BundleContext bundleContext = mock(BundleContext.class);
    Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>();
    ServiceReference serviceReference = mock(ServiceReference.class);
    InputTransformer inputTransformer = mock(InputTransformer.class);
    when(inputTransformer.transform(any())).thenReturn(new MetacardImpl());
    when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer);
    serviceReferences.add(serviceReference);
    when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences);
    CatalogServiceImpl catalogService = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry) {

        @Override
        protected BundleContext getBundleContext() {
            return bundleContext;
        }
    };
    UuidGenerator uuidGenerator = mock(UuidGenerator.class);
    when(uuidGenerator.generateUuid()).thenReturn(UUID.randomUUID().toString());
    catalogService.setUuidGenerator(uuidGenerator);
    when(attributeRegistry.lookup(Core.METADATA)).thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA)));
    addMatchingService(catalogService, Collections.singletonList(getSimpleTransformer()));
    List<Attachment> attachments = new ArrayList<>();
    ContentDisposition contentDisposition = new ContentDisposition("form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt");
    Attachment attachment = new Attachment("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), contentDisposition);
    attachments.add(attachment);
    ContentDisposition contentDisposition1 = new ContentDisposition("form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml");
    Attachment attachment1 = new Attachment("parse.metadata", new ByteArrayInputStream("Some Text Again".getBytes()), contentDisposition1);
    attachments.add(attachment1);
    ContentDisposition contentDisposition2 = new ContentDisposition("form-data; name=metadata; filename=C:\\DDF\\metacard.xml");
    Attachment attachment2 = new Attachment("metadata", new ByteArrayInputStream("<meta>beta</meta>".getBytes()), contentDisposition2);
    attachments.add(attachment2);
    MultipartBody multipartBody = new MultipartBody(attachments);
    String response = catalogService.addDocument(headers.getRequestHeader(HttpHeaders.CONTENT_TYPE), multipartBody, null, new ByteArrayInputStream("".getBytes()));
    LOGGER.debug(ToStringBuilder.reflectionToString(response));
    assertThat(response, equalTo(SAMPLE_ID));
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) CoreAttributes(ddf.catalog.data.impl.types.CoreAttributes) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) InputTransformer(ddf.catalog.transform.InputTransformer) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) ServiceReference(org.osgi.framework.ServiceReference) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) CatalogFramework(ddf.catalog.CatalogFramework) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 67 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project ddf by codice.

the class CatalogServiceImplTest method assertExceptionThrown.

@SuppressWarnings({ "unchecked" })
private void assertExceptionThrown(Class<? extends Throwable> klass) throws Exception {
    CatalogFramework framework = mock(CatalogFramework.class);
    when(framework.create(isA(CreateRequest.class))).thenThrow(klass);
    when(framework.create(isA(CreateStorageRequest.class))).thenThrow(klass);
    HttpHeaders headers = createHeaders(Collections.singletonList(MediaType.APPLICATION_JSON));
    CatalogServiceImpl catalogService = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry);
    addMatchingService(catalogService, Collections.singletonList(getSimpleTransformer()));
    try {
        catalogService.addDocument(headers.getRequestHeader(HttpHeaders.CONTENT_TYPE), mock(MultipartBody.class), null, new ByteArrayInputStream("".getBytes()));
    } catch (InternalServerErrorException e) {
        if (klass.getName().equals(SourceUnavailableException.class.getName())) {
            assertThat(e.getResponse().getStatus(), equalTo(INTERNAL_SERVER_ERROR));
        }
    } catch (CatalogServiceException e) {
        if (klass.getName().equals(IngestException.class.getName())) {
            assertEquals(e.getMessage(), "Error while storing entry in catalog: ");
        } else {
            fail();
        }
    }
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) CatalogServiceException(org.codice.ddf.rest.api.CatalogServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) CreateRequest(ddf.catalog.operation.CreateRequest) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) CatalogFramework(ddf.catalog.CatalogFramework) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest)

Example 68 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project cxf by apache.

the class AbstractServiceProviderFilter method checkSecurityContext.

protected boolean checkSecurityContext(Message m) {
    HttpHeaders headers = new HttpHeadersImpl(m);
    Map<String, Cookie> cookies = headers.getCookies();
    Cookie securityContextCookie = cookies.get(SSOConstants.SECURITY_CONTEXT_TOKEN);
    ResponseState responseState = getValidResponseState(securityContextCookie, m);
    if (responseState == null) {
        return false;
    }
    if (!isSupportUnsolicited()) {
        Cookie relayStateCookie = cookies.get(SSOConstants.RELAY_STATE);
        if (relayStateCookie == null) {
            reportError("MISSING_RELAY_COOKIE");
            return false;
        }
        String originalRelayState = responseState.getRelayState();
        if (!originalRelayState.equals(relayStateCookie.getValue())) {
            // perhaps the response state should also be removed
            reportError("INVALID_RELAY_STATE");
            return false;
        }
    }
    try {
        String assertion = responseState.getAssertion();
        SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(StaxUtils.read(new StringReader(assertion)).getDocumentElement());
        setSecurityContext(m, assertionWrapper);
    } catch (Exception ex) {
        reportError("INVALID_RESPONSE_STATE");
        return false;
    }
    return true;
}
Also used : Cookie(javax.ws.rs.core.Cookie) HttpHeaders(javax.ws.rs.core.HttpHeaders) ResponseState(org.apache.cxf.rs.security.saml.sso.state.ResponseState) StringReader(java.io.StringReader) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) IOException(java.io.IOException) HttpHeadersImpl(org.apache.cxf.jaxrs.impl.HttpHeadersImpl)

Example 69 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project cxf by apache.

the class JAASAuthenticationFilter method handleAuthenticationException.

protected Response handleAuthenticationException(SecurityException ex, Message m) {
    HttpHeaders headers = new HttpHeadersImpl(m);
    if (redirectURI != null && isRedirectPossible(headers)) {
        final URI finalRedirectURI;
        if (!redirectURI.isAbsolute()) {
            String endpointAddress = HttpUtils.getEndpointAddress(m);
            Object basePathProperty = m.get(Message.BASE_PATH);
            if (ignoreBasePath && basePathProperty != null && !"/".equals(basePathProperty)) {
                int index = endpointAddress.lastIndexOf(basePathProperty.toString());
                if (index != -1) {
                    endpointAddress = endpointAddress.substring(0, index);
                }
            }
            finalRedirectURI = UriBuilder.fromUri(endpointAddress).path(redirectURI.toString()).build();
        } else {
            finalRedirectURI = redirectURI;
        }
        return Response.status(getRedirectStatus()).header(HttpHeaders.LOCATION, finalRedirectURI).build();
    }
    ResponseBuilder builder = Response.status(Response.Status.UNAUTHORIZED);
    StringBuilder sb = new StringBuilder();
    List<String> authHeader = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (authHeader != null && !authHeader.isEmpty()) {
        // should HttpHeadersImpl do it ?
        String[] authValues = authHeader.get(0).split(" ");
        if (authValues.length > 0) {
            sb.append(authValues[0]);
        }
    } else {
        sb.append("Basic");
    }
    if (realmName != null) {
        sb.append(" realm=\"").append(realmName).append('"');
    }
    builder.header(HttpHeaders.WWW_AUTHENTICATE, sb.toString());
    return builder.build();
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URI(java.net.URI) HttpHeadersImpl(org.apache.cxf.jaxrs.impl.HttpHeadersImpl)

Example 70 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project cxf by apache.

the class HttpHeadersImplTest method testGetNullLanguage.

@Test
public void testGetNullLanguage() throws Exception {
    Message m = createMessage(createHeaders());
    HttpHeaders h = new HttpHeadersImpl(m);
    assertNull(h.getLanguage());
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) Message(org.apache.cxf.message.Message) Test(org.junit.Test)

Aggregations

HttpHeaders (javax.ws.rs.core.HttpHeaders)87 Test (org.junit.Test)57 Message (org.apache.cxf.message.Message)31 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 Optional (java.util.Optional)11 CatalogFramework (ddf.catalog.CatalogFramework)10 MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)10 JsonObject (com.google.gson.JsonObject)9 Locale (java.util.Locale)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 Response (javax.ws.rs.core.Response)8 UriInfo (javax.ws.rs.core.UriInfo)8 IOException (java.io.IOException)7 WebApplicationException (javax.ws.rs.WebApplicationException)7 MediaType (javax.ws.rs.core.MediaType)7 RequestInfo (com.liferay.apio.architect.request.RequestInfo)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Conditions (com.liferay.apio.architect.test.util.json.Conditions)5 OutputStream (java.io.OutputStream)5 Annotation (java.lang.annotation.Annotation)5