Java Code Examples for org.apache.cxf.transport.http.AbstractHTTPDestination

The following examples show how to use org.apache.cxf.transport.http.AbstractHTTPDestination. These examples are extracted from open source projects. 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 Project: component-runtime   Source File: WebSocketBroadcastSetup.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void complete() {
    message.getExchange().getInMessage().remove(AbstractHTTPDestination.CXF_CONTINUATION_MESSAGE);
    if (callback != null) {
        final Exception ex = message.getExchange().get(Exception.class);
        if (ex == null) {
            callback.onComplete();
        } else {
            callback.onError(ex);
        }
    }
    try {
        response.getWriter().close();
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 2
Source Project: peer-os   Source File: MessageContentUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void abortChain( Message message, int errorStatus, String errorMessage )
{
    HttpServletResponse response = ( HttpServletResponse ) message.getExchange().getInMessage()
                                                                  .get( AbstractHTTPDestination.HTTP_RESPONSE );
    try
    {
        response.setStatus( errorStatus );
        response.getOutputStream().write( errorMessage.getBytes(  StandardCharsets.UTF_8 ) );
        response.getOutputStream().flush();

        LOG.error( "****** Error !!! Error in AccessInterceptor:" + " "+ errorMessage
                    +"\n * Blocked URL:" + message.get(Message.REQUEST_URL));

    }
    catch ( Exception e )
    {
        LOG.error( "Error writing to response: " + e.toString(), e );
    }

    message.getInterceptorChain().abort();
}
 
Example 3
Source Project: peer-os   Source File: ServerInInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleMessage() throws Exception
{
    Message message = InterceptorStateHelper.getMessage( InterceptorState.SERVER_IN );
    Exchange exchange = message.getExchange();
    doReturn( message ).when( exchange ).getInMessage();
    doReturn( request ).when( message ).get( AbstractHTTPDestination.HTTP_REQUEST );
    doReturn( Common.DEFAULT_PUBLIC_SECURE_PORT ).when( request ).getLocalPort();
    doReturn( "/rest/v1/peer" ).when( request ).getRequestURI();

    interceptor.handleMessage( message );

    verify( interceptor ).handlePeerMessage( anyString(), eq( message ) );

    doReturn( "/rest/v1/env/123/" ).when( request ).getRequestURI();

    interceptor.handleMessage( message );

    verify( interceptor ).handleEnvironmentMessage( anyString(), anyString(), eq( message ) );
}
 
Example 4
Source Project: sakai   Source File: AbstractCXFTest.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * This is a utility method that contains some mocks that are required for cxf local testing.
 * It adds the <code>HTTP.REQUEST</code> to the request context.
 * @param client the cxf client from the test
 */
protected void addCXFClientMocks(WebClient client) {
	Map<String, Object> requestContext = WebClient.getConfig(client).getRequestContext();
	requestContext.put(LocalConduit.DIRECT_DISPATCH, Boolean.TRUE);

	// cxf workaround for using a HttpServletRequest in a local:// call
	HashSet<String> include = new HashSet<>();
	include.add(AbstractHTTPDestination.HTTP_REQUEST);
	requestContext.put(LocalTransportFactory.MESSAGE_INCLUDE_PROPERTIES, include);

	HttpServletRequest mockRequest = mock(HttpServletRequest.class);
	when(mockRequest.getRemoteAddr()).thenReturn("127.0.0.1");
	when(mockRequest.getRequestURL()).thenReturn(new StringBuffer());
	when(mockRequest.getPathInfo()).thenReturn("");
	when(mockRequest.getContextPath()).thenReturn("");
	when(mockRequest.getServletPath()).thenReturn("");
	requestContext.put(AbstractHTTPDestination.HTTP_REQUEST, mockRequest);
}
 
Example 5
Source Project: cxf   Source File: SecurityOutFaultInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    Fault fault = (Fault)message.getContent(Exception.class);
    Throwable ex = fault.getCause();
    if (!(ex instanceof SecurityException)) {
        throw new RuntimeException("Security Exception is expected");
    }

    HttpServletResponse response = (HttpServletResponse)message.getExchange().getInMessage()
        .get(AbstractHTTPDestination.HTTP_RESPONSE);
    int status = ex instanceof AccessDeniedException ? 403 : 401;
    response.setStatus(status);
    try {
        response.getOutputStream().write(ex.getMessage().getBytes());
        response.getOutputStream().flush();
    } catch (IOException iex) {
        // ignore
    }

    message.getInterceptorChain().abort();
}
 
Example 6
Source Project: cxf   Source File: CustomOutFaultInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    if (message.getExchange().get("org.apache.cxf.systest.for-out-fault-interceptor") == null) {
        return;
    }
    handleMessageCalled = true;
    Exception ex = message.getContent(Exception.class);
    if (ex == null) {
        throw new RuntimeException("Exception is expected");
    }
    if (!(ex instanceof Fault)) {
        throw new RuntimeException("Fault is expected");
    }
    // deal with the actual exception : fault.getCause()
    HttpServletResponse response = (HttpServletResponse)message.getExchange()
        .getInMessage().get(AbstractHTTPDestination.HTTP_RESPONSE);
    response.setStatus(500);
    try {
        response.getOutputStream().write("<nobook/>".getBytes());
        response.getOutputStream().flush();
        message.getInterceptorChain().abort();
    } catch (IOException ioex) {
        throw new RuntimeException("Error writing the response");
    }

}
 
Example 7
Source Project: cxf   Source File: UndertowHTTPDestinationTest.java    License: Apache License 2.0 6 votes vote down vote up
private void verifyDoService() throws Exception {
    assertSame("Default thread bus has not been set for request",
                bus, threadDefaultBus);
    assertNotNull("unexpected null message", inMessage);
    assertSame("unexpected HTTP request",
               inMessage.get(AbstractHTTPDestination.HTTP_REQUEST),
               request);
    assertSame("unexpected HTTP response",
               inMessage.get(AbstractHTTPDestination.HTTP_RESPONSE),
               response);
    assertEquals("unexpected method",
                 inMessage.get(Message.HTTP_REQUEST_METHOD),
                 "POST");
    assertEquals("unexpected path",
                 inMessage.get(Message.PATH_INFO),
                 "/bar/foo");
    assertEquals("unexpected query",
                 inMessage.get(Message.QUERY_STRING),
                 "?name");
    assertNotNull("unexpected query",
               inMessage.get(TLSSessionInfo.class));
    verifyRequestHeaders();

}
 
Example 8
Source Project: cxf   Source File: EventMapper.java    License: Apache License 2.0 6 votes vote down vote up
protected void handleEvent(TokenCancellerParametersSupport event, Map<String, Object> map) {
    TokenCancellerParameters params = event.getTokenParameters();
    HttpServletRequest req =
        (HttpServletRequest)params.getMessageContext().get(AbstractHTTPDestination.HTTP_REQUEST);
    map.put(KEYS.REMOTE_HOST.name(), req.getRemoteHost());
    map.put(KEYS.REMOTE_PORT.name(), String.valueOf(req.getRemotePort()));
    map.put(KEYS.URL.name(), params.getMessageContext().get("org.apache.cxf.request.url"));
    map.put(KEYS.TOKENTYPE.name(), params.getTokenRequirements().getTokenType());
    if (params.getTokenRequirements().getActAs() != null) {
        map.put(KEYS.CANCEL_PRINCIPAL.name(), params.getTokenRequirements().getCancelTarget().getPrincipal()
            .getName());
    }
    if (params.getKeyRequirements() != null) {
        map.put(KEYS.KEYTYPE.name(), params.getKeyRequirements().getKeyType());
    }
    if (params.getPrincipal() != null) {
        map.put(KEYS.WS_SEC_PRINCIPAL.name(), params.getPrincipal().getName());
    }
}
 
Example 9
Source Project: cxf   Source File: EventMapper.java    License: Apache License 2.0 6 votes vote down vote up
protected void handleEvent(TokenRenewerParametersSupport event, Map<String, Object> map) {
    TokenRenewerParameters params = event.getTokenParameters();
    HttpServletRequest req =
        (HttpServletRequest)params.getMessageContext().get(AbstractHTTPDestination.HTTP_REQUEST);
    map.put(KEYS.REMOTE_HOST.name(), req.getRemoteHost());
    map.put(KEYS.REMOTE_PORT.name(), String.valueOf(req.getRemotePort()));
    map.put(KEYS.URL.name(), params.getMessageContext().get("org.apache.cxf.request.url"));
    map.put(KEYS.TOKENTYPE.name(), params.getTokenRequirements().getTokenType());
    if (params.getTokenRequirements().getRenewTarget() != null) {
        map.put(KEYS.RENEW_PRINCIPAL.name(), params.getTokenRequirements().getRenewTarget().getPrincipal()
            .getName());
    }
    if (params.getPrincipal() != null) {
        map.put(KEYS.WS_SEC_PRINCIPAL.name(), params.getPrincipal().getName());
    }
    if (params.getKeyRequirements() != null) {
        map.put(KEYS.KEYTYPE.name(), params.getKeyRequirements().getKeyType());
    }
    map.put(KEYS.REALM.name(), params.getRealm());
    map.put(KEYS.APPLIESTO.name(), params.getAppliesToAddress());
}
 
Example 10
Source Project: cxf   Source File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String getEndpointAddress(Message m) {
    String address = null;
    Destination d = m.getExchange().getDestination();
    if (d != null) {
        if (d instanceof AbstractHTTPDestination) {
            EndpointInfo ei = ((AbstractHTTPDestination)d).getEndpointInfo();
            HttpServletRequest request = (HttpServletRequest)m.get(AbstractHTTPDestination.HTTP_REQUEST);
            Object property = request != null
                ? request.getAttribute("org.apache.cxf.transport.endpoint.address") : null;
            address = property != null ? property.toString() : ei.getAddress();
        } else {
            address = m.containsKey(Message.BASE_PATH)
                ? (String)m.get(Message.BASE_PATH) : d.getAddress().getAddress().getValue();
        }
    } else {
        address = (String)m.get(Message.ENDPOINT_ADDRESS);
    }
    if (address.startsWith("http") && address.endsWith("//")) {
        address = address.substring(0, address.length() - 1);
    }
    return address;
}
 
Example 11
Source Project: cxf   Source File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static <T> T createServletResourceValue(Message m, Class<T> clazz) {

        Object value = null;
        if (clazz == HttpServletRequest.class) {
            HttpServletRequest request = (HttpServletRequest)m.get(AbstractHTTPDestination.HTTP_REQUEST);
            value = request != null ? new HttpServletRequestFilter(request, m) : null;
        } else if (clazz == HttpServletResponse.class) {
            HttpServletResponse response = (HttpServletResponse)m.get(AbstractHTTPDestination.HTTP_RESPONSE);
            value = response != null ? new HttpServletResponseFilter(response, m) : null;
        } else if (clazz == ServletContext.class) {
            value = m.get(AbstractHTTPDestination.HTTP_CONTEXT);
        } else if (clazz == ServletConfig.class) {
            value = m.get(AbstractHTTPDestination.HTTP_CONFIG);
        }

        return clazz.cast(value);
    }
 
Example 12
Source Project: cxf   Source File: SpringViewResolverProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void writeTo(Object o, Class<?> clazz, Type genericType, Annotation[] annotations, MediaType type,
        MultivaluedMap<String, Object> headers, OutputStream os) throws IOException {

    View view = getView(clazz, o);
    String attributeName = getBeanName(o);
    Map<String, Object> model = Collections.singletonMap(attributeName, o);

    try {
        getMessageContext().put(AbstractHTTPDestination.REQUEST_REDIRECTED, Boolean.TRUE);
        logRedirection(view, attributeName, o);
        view.render(model, getMessageContext().getHttpServletRequest(),
                    getMessageContext().getHttpServletResponse());
    } catch (Throwable ex) {
        handleViewRenderingException(view.toString(), ex);
    }
}
 
Example 13
Source Project: cxf   Source File: NioReadEntity.java    License: Apache License 2.0 6 votes vote down vote up
public NioReadEntity(NioReadHandler reader, NioReadCompletionHandler completion, NioErrorHandler error) {
    this.reader = reader;
    this.completion = completion;
    this.error = error;
    
    final Message m = JAXRSUtils.getCurrentMessage();
    try {
        if (m.get(AsyncResponse.class) == null) {
            throw new IllegalStateException("AsyncResponse is not available");
        }
        final HttpServletRequest request = (HttpServletRequest)m.get(AbstractHTTPDestination.HTTP_REQUEST);
        request.getInputStream().setReadListener(new NioReadListenerImpl(this, request.getInputStream()));
    } catch (final Throwable ex) {
        throw new RuntimeException("Unable to initialize NIO entity", ex);
    }
    
}
 
Example 14
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPerRequestContextFields() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    cri.setResourceProvider(new PerRequestResourceProvider(Customer.class));
    OperationResourceInfo ori = new OperationResourceInfo(Customer.class.getMethod("postConstruct",
                                                                                   new Class[]{}), cri);

    Customer c = new Customer();

    Message m = createMessage();
    m.put(Message.PROTOCOL_HEADERS, new HashMap<String, List<String>>());
    HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, response);

    InjectionUtils.injectContextFields(c, ori.getClassResourceInfo(), m);
    assertSame(UriInfoImpl.class, c.getUriInfo2().getClass());
    assertSame(HttpHeadersImpl.class, c.getHeaders().getClass());
    assertSame(RequestImpl.class, c.getRequest().getClass());
    assertSame(SecurityContextImpl.class, c.getSecurityContext().getClass());
    assertSame(ProvidersImpl.class, c.getBodyWorkers().getClass());

}
 
Example 15
Source Project: cxf   Source File: JAXRSUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testContextResolverFields() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    cri.setResourceProvider(new PerRequestResourceProvider(Customer.class));
    OperationResourceInfo ori = new OperationResourceInfo(Customer.class.getMethod("postConstruct",
                                                                                   new Class[]{}), cri);

    Message m = createMessage();
    HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, response);
    Customer c = new Customer();
    ContextResolver<JAXBContext> cr = new JAXBContextProvider();
    ProviderFactory.getInstance(m).registerUserProvider(cr);

    m.put(Message.BASE_PATH, "/");
    InjectionUtils.injectContextFields(c, ori.getClassResourceInfo(), m);
    assertSame(cr.getClass(), c.getContextResolver().getClass());
}
 
Example 16
Source Project: cxf   Source File: SseEventSinkContextProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SseEventSink createContext(Message message) {
    final HttpServletRequest request = (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
    if (request == null) {
        throw new IllegalStateException("Unable to retrieve HTTP request from the context");
    }

    final MessageBodyWriter<OutboundSseEvent> writer = new OutboundSseEventBodyWriter(
        ServerProviderFactory.getInstance(message), message.getExchange());

    final AsyncResponse async = new AsyncResponseImpl(message);
    final Integer bufferSize = PropertyUtils.getInteger(message, SseEventSinkImpl.BUFFER_SIZE_PROPERTY);
    
    final SseEventSink sink = createSseEventSink(request, writer, async, bufferSize);
    message.put(SseEventSink.class, sink);
    
    return sink;
}
 
Example 17
Source Project: cxf   Source File: WebSocketTransportFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Destination getDestination(EndpointInfo endpointInfo, Bus bus) throws IOException {
    if (endpointInfo == null) {
        throw new IllegalArgumentException("EndpointInfo cannot be null");
    }
    synchronized (registry) {
        AbstractHTTPDestination d = registry.getDestinationForPath(endpointInfo.getAddress());
        if (d == null) {
            d = factory.createDestination(endpointInfo, bus, registry);
            if (d == null) {
                String error = "No destination available. The CXF websocket transport needs either the "
                    + "Jetty WebSocket or Atmosphere dependencies to be available";
                throw new IOException(error);
            }
            registry.addDestination(d);
            configure(bus, d);
            d.finalizeConfig();
        }
        return d;
    }
}
 
Example 18
Source Project: cxf   Source File: FormattedServiceListWriter.java    License: Apache License 2.0 6 votes vote down vote up
private void writeRESTfulEndpoint(PrintWriter writer,
                                  String basePath,
                                  AbstractDestination sd) {
    String absoluteURL = getAbsoluteAddress(basePath, sd);
    if (absoluteURL == null) {
        return;
    }
    absoluteURL = StringEscapeUtils.escapeHtml4(absoluteURL);

    writer.write("<tr><td>");
    writer.write("<span class=\"field\">Endpoint address:</span> " + "<span class=\"value\">"
                 + absoluteURL + "</span>");

    Bus sb = bus;
    if (sd instanceof AbstractHTTPDestination) {
        sb = ((AbstractHTTPDestination)sd).getBus();
    }

    addWadlIfNeeded(absoluteURL, sb, writer);
    addOpenApiIfNeeded(absoluteURL, sb, writer);
    addSwaggerIfNeeded(absoluteURL, sb, writer);
    addAtomLinkIfNeeded(absoluteURL, atomMap, writer);
    writer.write("</td></tr>");
}
 
Example 19
Source Project: cxf   Source File: ServletController.java    License: Apache License 2.0 6 votes vote down vote up
protected void updateDestination(HttpServletRequest request,
                                 String base,
                                 AbstractHTTPDestination d) {
    String ad = d.getEndpointInfo().getAddress();
    if (ad == null
        && d.getAddress() != null
        && d.getAddress().getAddress() != null) {
        ad = d.getAddress().getAddress().getValue();
        if (ad == null) {
            ad = "/";
        }
    }
    // Using HTTP_PREFIX check is safe for ServletController
    // URI.create(ad).isRelative() can be used - a bit more expensive though
    if (ad != null && !ad.startsWith(HTTP_PREFIX)) {
        if (disableAddressUpdates) {
            request.setAttribute("org.apache.cxf.transport.endpoint.address",
                                 base + ad);
        } else {
            BaseUrlHelper.setAddress(d, base + ad);
        }
    }
}
 
Example 20
Source Project: cxf   Source File: ServletController.java    License: Apache License 2.0 6 votes vote down vote up
public void invokeDestination(final HttpServletRequest request, HttpServletResponse response,
                              AbstractHTTPDestination d) throws ServletException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Service http request on thread: " + Thread.currentThread());
    }

    try {
        d.invoke(servletConfig, servletConfig.getServletContext(), request, response);
    } catch (IOException e) {
        throw new ServletException(e);
    } finally {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Finished servicing http request on thread: " + Thread.currentThread());
        }
    }
}
 
Example 21
Source Project: cxf   Source File: CXFNonSpringServlet.java    License: Apache License 2.0 6 votes vote down vote up
public void destroy() {
    if (!globalRegistry) {
        for (String path : destinationRegistry.getDestinationsPaths()) {
            // clean up the destination in case the destination itself can
            // no longer access the registry later
            AbstractHTTPDestination dest = destinationRegistry.getDestinationForPath(path);
            synchronized (dest) {
                destinationRegistry.removeDestination(path);
                dest.releaseRegistry();
            }
        }
        destinationRegistry = null;
    }
    destroyBus();
    super.destroy();
}
 
Example 22
Source Project: cxf   Source File: HttpDestinationBPBeanDefinitionParser.java    License: Apache License 2.0 6 votes vote down vote up
public Metadata parse(Element element, ParserContext context) {
    MutableBeanMetadata bean = context.createMetadata(MutableBeanMetadata.class);

    bean.setRuntimeClass(AbstractHTTPDestination.class);

    mapElementToJaxbProperty(context, bean, element, new QName(HTTP_NS, "server"), "server",
                             HTTPServerPolicy.class);
    mapElementToJaxbProperty(context, bean, element, new QName(HTTP_NS, "fixedParameterOrder"),
                             "fixedParameterOrder", Boolean.class);
    mapElementToJaxbProperty(context, bean, element, new QName(HTTP_NS, "contextMatchStrategy"),
                             "contextMatchStrategy", String.class);

    parseAttributes(element, context, bean);
    parseChildElements(element, context, bean);

    bean.setScope(BeanMetadata.SCOPE_PROTOTYPE);

    return bean;
}
 
Example 23
Source Project: cxf   Source File: ServletControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHideServiceListing() throws Exception {
    req.getPathInfo();
    EasyMock.expectLastCall().andReturn(null);

    registry.getDestinationForPath("", true);
    EasyMock.expectLastCall().andReturn(null).atLeastOnce();
    AbstractHTTPDestination dest = EasyMock.createMock(AbstractHTTPDestination.class);
    registry.checkRestfulRequest("");
    EasyMock.expectLastCall().andReturn(dest).atLeastOnce();
    dest.getBus();
    EasyMock.expectLastCall().andReturn(null).anyTimes();
    dest.getMessageObserver();
    EasyMock.expectLastCall().andReturn(EasyMock.createMock(MessageObserver.class)).atLeastOnce();

    expectServiceListGeneratorNotCalled();

    EasyMock.replay(req, registry, serviceListGenerator, dest);
    TestServletController sc = new TestServletController(registry, serviceListGenerator);
    sc.setHideServiceList(true);
    sc.invoke(req, res);
    assertTrue(sc.invokeDestinationCalled());
}
 
Example 24
Source Project: cxf   Source File: JettyHTTPDestinationTest.java    License: Apache License 2.0 6 votes vote down vote up
private void verifyDoService() throws Exception {
    assertSame("Default thread bus has not been set for request",
                bus, threadDefaultBus);
    assertNotNull("unexpected null message", inMessage);
    assertSame("unexpected HTTP request",
               inMessage.get(AbstractHTTPDestination.HTTP_REQUEST),
               request);
    assertSame("unexpected HTTP response",
               inMessage.get(AbstractHTTPDestination.HTTP_RESPONSE),
               response);
    assertEquals("unexpected method",
                 inMessage.get(Message.HTTP_REQUEST_METHOD),
                 "POST");
    assertEquals("unexpected path",
                 inMessage.get(Message.PATH_INFO),
                 "/bar/foo");
    assertEquals("unexpected query",
                 inMessage.get(Message.QUERY_STRING),
                 "?name");
    assertNotNull("unexpected query",
               inMessage.get(TLSSessionInfo.class));
    verifyRequestHeaders();

}
 
Example 25
@Override
public String getParameter(String name) {
	if (AbstractHTTPDestination.SERVICE_REDIRECTION.equals(name)) {
		return "true";
	}
	return super.getParameter(name);
}
 
Example 26
Source Project: cxf   Source File: UndertowHTTPDestinationTest.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyBackChannelSend(Conduit backChannel,
                                   Message outMsg,
                                   int status,
                                   boolean oneway) throws Exception {
    outMsg.getExchange().setOneWay(oneway);

    assertTrue("unexpected back channel type",
               backChannel instanceof UndertowHTTPDestination.BackChannelConduit);
    assertTrue("unexpected content formats",
               outMsg.getContentFormats().contains(OutputStream.class));
    OutputStream responseOS = outMsg.getContent(OutputStream.class);
    assertNotNull("expected output stream", responseOS);
    assertTrue("unexpected output stream type",
               responseOS instanceof AbstractWrappedOutputStream);

    outMsg.put(Message.RESPONSE_CODE, status);
    responseOS.write(PAYLOAD.getBytes());

    setUpResponseHeaders(outMsg);

    responseOS.flush();
    assertEquals("unexpected status",
                 status,
                 response.getStatus());

    verifyResponseHeaders(outMsg);

    if (oneway) {
        assertNull("unexpected HTTP response",
                   outMsg.get(AbstractHTTPDestination.HTTP_RESPONSE));
    } else {
        assertNotNull("expected HTTP response",
                       outMsg.get(AbstractHTTPDestination.HTTP_RESPONSE));
        responseOS.close();
    }
}
 
Example 27
Source Project: component-runtime   Source File: WebSocketBroadcastSetup.java    License: Apache License 2.0 5 votes vote down vote up
private WebSocketContinuation(final Message message, final HttpServletRequest request,
        final HttpServletResponse response, final WebSocketRegistry registry) {
    this.message = message;
    this.request = request;
    this.response = response;
    this.registry = registry;
    this.request
            .setAttribute(AbstractHTTPDestination.CXF_CONTINUATION_MESSAGE,
                    message.getExchange().getInMessage());
    this.callback = message.getExchange().get(ContinuationCallback.class);
}
 
Example 28
Source Project: peer-os   Source File: ServerOutInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Intercepts a message. interceptor chain will take care of this.
 */
@Override
public void handleMessage( final Message message )
{
    try
    {
        if ( InterceptorState.SERVER_OUT.isActive( message ) )
        {
            //obtain client request
            HttpServletRequest req = ( HttpServletRequest ) message.getExchange().getInMessage()
                                                                   .get( AbstractHTTPDestination.HTTP_REQUEST );

            if ( req.getLocalPort() == Common.DEFAULT_PUBLIC_SECURE_PORT )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                String subutaiHeader = headers.getHeaderString( Common.SUBUTAI_HTTP_HEADER );
                String path = req.getRequestURI();

                if ( path.startsWith( "/rest/v1/peer" ) )
                {
                    handlePeerMessage( subutaiHeader, message );
                }
                else
                {
                    final String prefix = "/rest/v1/env";
                    if ( path.startsWith( prefix ) )
                    {
                        String s = path.substring( prefix.length() + 1 );
                        String environmentId = s.substring( 0, s.indexOf( "/" ) );
                        handleEnvironmentMessage( subutaiHeader, environmentId, message );
                    }
                }
            }
        }
    }
    catch ( Exception e )
    {
        throw new Fault( e );
    }
}
 
Example 29
Source Project: peer-os   Source File: AccessControlInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleMessage() throws Exception
{
    Message message = InterceptorStateHelper.getMessage( InterceptorState.SERVER_IN );

    doReturn( request ).when( message ).get( AbstractHTTPDestination.HTTP_REQUEST );
    doReturn( exchange ).when( message ).getExchange();
    doReturn( interceptorChain ).when( message ).getInterceptorChain();
    doReturn( message ).when( exchange ).getInMessage();
    doReturn( Common.DEFAULT_PUBLIC_SECURE_PORT ).when( request ).getLocalPort();
    doReturn( response ).when( message ).get( AbstractHTTPDestination.HTTP_RESPONSE );
    ServletOutputStream outputStream = mock( ServletOutputStream.class );
    doReturn( outputStream ).when( response ).getOutputStream();

    accessControlInterceptor.handleMessage( message );

    verify( accessControlInterceptor ).authenticateAccess( null, null );

    verify( interceptorChain ).abort();

    doReturn( "/rest/v1/identity/auth").when( request ).getRequestURI();
    doReturn( -1 ).when( request ).getLocalPort();

    accessControlInterceptor.handleMessage( message );

    verify( accessControlInterceptor, times( 2 ) ).authenticateAccess( null, null );

    doReturn( Common.DEFAULT_PUBLIC_PORT ).when( request ).getLocalPort();
    doReturn( "/blabla" ).when( request ).getRequestURI();

    accessControlInterceptor.handleMessage( message );

    verify( accessControlInterceptor ).authenticateAccess( message, request );
}
 
Example 30
Source Project: peer-os   Source File: MessageContentUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    doReturn( exchange ).when( message ).getExchange();
    doReturn( message ).when( exchange ).getInMessage();
    doReturn( response ).when( message ).get( AbstractHTTPDestination.HTTP_RESPONSE );
    doReturn( servletOutputStream ).when( response ).getOutputStream();
    doReturn( interceptors ).when( message ).getInterceptorChain();
    doReturn( new ByteArrayInputStream( "test".getBytes() ) ).when( message ).getContent( InputStream.class );
    doReturn( keyManager ).when( securityManager ).getKeyManager();
    doReturn( encryptionTool ).when( securityManager ).getEncryptionTool();
    doReturn( secretKeys ).when( keyManager ).getSecretKeyRing( anyString() );
    doReturn( cachedOutputStream ).when( message ).getContent( OutputStream.class );
}