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

The following examples show how to use org.apache.cxf.transport.http.AbstractHTTPDestination. 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: JettyHTTPDestinationTest.java    From cxf with 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 #2
Source File: ServerInInterceptorTest.java    From peer-os with 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 #3
Source File: MessageContentUtil.java    From peer-os with 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 #4
Source File: WebSocketBroadcastSetup.java    From component-runtime with 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 #5
Source File: AbstractCXFTest.java    From sakai with 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 #6
Source File: SecurityOutFaultInterceptor.java    From cxf with 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 #7
Source File: CustomOutFaultInterceptor.java    From cxf with 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 #8
Source File: UndertowHTTPDestinationTest.java    From cxf with 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 #9
Source File: EventMapper.java    From cxf with 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 #10
Source File: EventMapper.java    From cxf with 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 #11
Source File: HttpUtils.java    From cxf with 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 #12
Source File: HttpUtils.java    From cxf with 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 #13
Source File: JAXRSUtilsTest.java    From cxf with 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 #14
Source File: JAXRSUtilsTest.java    From cxf with 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 #15
Source File: SseEventSinkContextProvider.java    From cxf with 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 #16
Source File: WebSocketTransportFactory.java    From cxf with 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 #17
Source File: FormattedServiceListWriter.java    From cxf with 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 #18
Source File: ServletController.java    From cxf with 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 #19
Source File: ServletController.java    From cxf with 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 #20
Source File: CXFNonSpringServlet.java    From cxf with 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 #21
Source File: NioReadEntity.java    From cxf with 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 #22
Source File: SpringViewResolverProvider.java    From cxf with 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 #23
Source File: ServletControllerTest.java    From cxf with 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 File: HttpDestinationBPBeanDefinitionParser.java    From cxf with 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 #25
Source File: HttpUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplaceAnyIPAddress() {
    Message m = new MessageImpl();
    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, req);
    req.getScheme();
    EasyMock.expectLastCall().andReturn("http");
    req.getServerName();
    EasyMock.expectLastCall().andReturn("localhost");
    req.getServerPort();
    EasyMock.expectLastCall().andReturn(8080);
    EasyMock.replay(req);
    URI u = HttpUtils.toAbsoluteUri(URI.create("http://0.0.0.0/bar/foo"), m);
    assertEquals("http://localhost:8080/bar/foo", u.toString());
}
 
Example #26
Source File: HttpUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doTestReplaceAnyIPAddressWithPort(boolean anyIp) {
    Message m = new MessageImpl();
    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, req);
    req.getScheme();
    EasyMock.expectLastCall().andReturn("http");
    req.getServerName();
    EasyMock.expectLastCall().andReturn("localhost");
    req.getServerPort();
    EasyMock.expectLastCall().andReturn(8080);
    EasyMock.replay(req);
    String host = anyIp ? "0.0.0.0" : "127.0.0.1";
    URI u = HttpUtils.toAbsoluteUri(URI.create("http://" + host + ":8080/bar/foo"), m);
    assertEquals("http://localhost:8080/bar/foo", u.toString());
}
 
Example #27
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSingletonHttpResourceFields() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    Customer c = new Customer();
    cri.setResourceProvider(new SingletonResourceProvider(c));

    Message m = createMessage();
    ServletContext servletContextMock = EasyMock.createNiceMock(ServletContext.class);
    m.put(AbstractHTTPDestination.HTTP_CONTEXT, servletContextMock);
    HttpServletRequest httpRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, httpRequest);
    HttpServletResponse httpResponse = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, httpResponse);
    InjectionUtils.injectContextProxies(cri, cri.getResourceProvider().getInstance(null));
    InjectionUtils.injectContextFields(c, cri, m);
    assertSame(servletContextMock,
               ((ThreadLocalProxy<ServletContext>)c.getServletContextResource()).get());
    HttpServletRequest currentReq =
        ((ThreadLocalProxy<HttpServletRequest>)c.getServletRequestResource()).get();
    assertSame(httpRequest,
               ((HttpServletRequestFilter)currentReq).getRequest());
    HttpServletResponseFilter filter = (
        HttpServletResponseFilter)((ThreadLocalProxy<HttpServletResponse>)c.getServletResponseResource())
            .get();
    assertSame(httpResponse, filter.getResponse());
}
 
Example #28
Source File: SpringViewResolverProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    this.viewResolver = new SpringViewResolverProvider(viewResolverMock, localeResolverMock);
    ExchangeImpl exchange = new ExchangeImpl();
    Endpoint endpoint = new MockEndpoint();
    endpoint.put(ServerProviderFactory.class.getName(), ServerProviderFactory.getInstance());
    exchange.put(Endpoint.class, endpoint);
    exchange.put(ServerProviderFactory.class.getName(), ServerProviderFactory.getInstance());
    MessageImpl message = new MessageImpl();
    message.setExchange(exchange);
    message.put(AbstractHTTPDestination.HTTP_REQUEST, requestMock);
    message.put(AbstractHTTPDestination.HTTP_RESPONSE, responseMock);
    message.put(AbstractHTTPDestination.HTTP_CONTEXT, servletContextMock);
    viewResolver.setMessageContext(new MessageContextImpl(message));
}
 
Example #29
Source File: MessageContextImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpResponse() {
    Message m = createMessage();
    MessageContext mc = new MessageContextImpl(m);
    HttpServletResponse request = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, request);
    HttpServletResponseFilter filter = (HttpServletResponseFilter)mc.getHttpServletResponse();
    assertSame(request.getClass(), filter.getResponse().getClass());
    filter = (HttpServletResponseFilter)mc.getContext(HttpServletResponse.class);
    assertSame(request.getClass(), filter.getResponse().getClass());
}
 
Example #30
Source File: MessageContextImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpRequest() {
    Message m = createMessage();
    MessageContext mc = new MessageContextImpl(m);
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, request);

    assertSame(request.getClass(),
               ((HttpServletRequestFilter)mc.getHttpServletRequest()).getRequest().getClass());
    assertSame(request.getClass(),
               ((HttpServletRequestFilter)mc.getContext(HttpServletRequest.class)).getRequest().getClass());
}