/** * Called for an incoming message. * * @param inMessage */ public void onMessage(Message inMessage) { // disposable exchange, swapped with real Exchange on correlation inMessage.setExchange(new ExchangeImpl()); inMessage.getExchange().put(Bus.class, bus); inMessage.put(Message.DECOUPLED_CHANNEL_MESSAGE, Boolean.TRUE); inMessage.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_OK); // remove server-specific properties // inMessage.remove(AbstractHTTPDestination.HTTP_REQUEST); // inMessage.remove(AbstractHTTPDestination.HTTP_RESPONSE); inMessage.remove(Message.ASYNC_POST_RESPONSE_DISPATCH); updateResponseCode(inMessage); // cache this inputstream since it's defer to use in case of async try { InputStream in = inMessage.getContent(InputStream.class); if (in != null) { CachedOutputStream cos = new CachedOutputStream(); IOUtils.copy(in, cos); inMessage.setContent(InputStream.class, cos.getInputStream()); } observer.onMessage(inMessage); } catch (IOException e) { e.printStackTrace(); } }
private Message mockMessage( String baseAddress, String pathInfo, String query, List<ClassResourceInfo> cris) throws Exception { Message m = new MessageImpl(); Exchange e = new ExchangeImpl(); e.put(Service.class, new JAXRSServiceImpl(cris)); m.setExchange(e); control.reset(); ServletDestination d = control.createMock(ServletDestination.class); EndpointInfo epr = new EndpointInfo(); epr.setAddress(baseAddress); d.getEndpointInfo(); EasyMock.expectLastCall().andReturn(epr).anyTimes(); Endpoint endpoint = new EndpointImpl(null, null, epr); e.put(Endpoint.class, endpoint); endpoint.put(ServerProviderFactory.class.getName(), ServerProviderFactory.getInstance()); e.setDestination(d); BindingInfo bi = control.createMock(BindingInfo.class); epr.setBinding(bi); bi.getProperties(); EasyMock.expectLastCall().andReturn(Collections.emptyMap()).anyTimes(); m.put(Message.REQUEST_URI, pathInfo); m.put(Message.QUERY_STRING, query); m.put(Message.HTTP_REQUEST_METHOD, "GET"); control.replay(); return m; }
protected void invokeInboundChain(Exchange ex, Endpoint ep) { Message m = getInBoundMessage(ex); Message inMsg = ep.getBinding().createMessage(); MessageImpl.copyContent(m, inMsg); // Copy Response Context to Client inBound Message // TODO a Context Filter Strategy required. inMsg.putAll(m); inMsg.put(Message.REQUESTOR_ROLE, Boolean.TRUE); inMsg.put(Message.INBOUND_MESSAGE, Boolean.TRUE); inMsg.setExchange(ex); Exception exc = inMsg.getContent(Exception.class); if (exc != null) { ex.setInFaultMessage(inMsg); ColocInFaultObserver observer = new ColocInFaultObserver(bus); observer.onMessage(inMsg); } else { // Handle Response ex.setInMessage(inMsg); PhaseManager pm = bus.getExtension(PhaseManager.class); SortedSet<Phase> phases = new TreeSet<Phase>(pm.getInPhases()); ColocUtil.setPhases(phases, Phase.USER_LOGICAL, Phase.PRE_INVOKE); InterceptorChain chain = ColocUtil.getInInterceptorChain(ex, phases); inMsg.setInterceptorChain(chain); chain.doIntercept(inMsg); } ex.put(ClientImpl.FINISHED, Boolean.TRUE); }
/** * Cache HTTP headers in message. * * @param message the current message */ protected void setHeaders(Message message) { Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>(); copyRequestHeaders(message, requestHeaders); message.put(Message.PROTOCOL_HEADERS, requestHeaders); if (requestHeaders.containsKey("Authorization")) { List<String> authorizationLines = requestHeaders.get("Authorization"); String credentials = authorizationLines.get(0); String authType = credentials.split(" ")[0]; if ("Basic".equals(authType)) { String authEncoded = credentials.split(" ")[1]; try { String authDecoded = new String(Base64Utility.decode(authEncoded)); String authInfo[] = authDecoded.split(":"); String username = (authInfo.length > 0) ? authInfo[0] : ""; // Below line for systems that blank out password after authentication; // see CXF-1495 for more info String password = (authInfo.length > 1) ? authInfo[1] : ""; AuthorizationPolicy policy = new AuthorizationPolicy(); policy.setUserName(username); policy.setPassword(password); message.put(AuthorizationPolicy.class, policy); } catch (Base64Exception ex) { // ignore, we'll leave things alone. They can try decoding it themselves } } } if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Request Headers: " + requestHeaders.toString()); } }
/** * Mark message as a partial message. * * @param partialResponse the partial response message * @param the decoupled target * @return true iff partial responses are supported */ protected final boolean markPartialResponse( Message partialResponse, EndpointReferenceType decoupledTarget) { // setup the outbound message to for 202 Accepted partialResponse.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_ACCEPTED); partialResponse.getExchange().put(EndpointReferenceType.class, decoupledTarget); partialResponse.put(PARTIAL_RESPONSE, Boolean.TRUE); return true; }
public void handleMessage(Message message) throws Fault { if (bus == null) { bus = message.getExchange().getBus(); if (bus == null) { bus = BusFactory.getDefaultBus(false); } if (bus == null) { throw new Fault(new org.apache.cxf.common.i18n.Message("BUS_NOT_FOUND", BUNDLE)); } } ServerRegistry registry = bus.getExtension(ServerRegistry.class); if (registry == null) { throw new Fault(new org.apache.cxf.common.i18n.Message("SERVER_REGISTRY_NOT_FOUND", BUNDLE)); } Exchange exchange = message.getExchange(); Endpoint senderEndpoint = exchange.getEndpoint(); if (senderEndpoint == null) { throw new Fault(new org.apache.cxf.common.i18n.Message("ENDPOINT_NOT_FOUND", BUNDLE)); } BindingOperationInfo boi = exchange.getBindingOperationInfo(); if (boi == null) { throw new Fault(new org.apache.cxf.common.i18n.Message("OPERATIONINFO_NOT_FOUND", BUNDLE)); } Server srv = isColocated(registry.getServers(), senderEndpoint, boi); if (srv != null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Operation:" + boi.getName() + " dispatched as colocated call."); } InterceptorChain outChain = message.getInterceptorChain(); outChain.abort(); exchange.put(Bus.class, bus); message.put(COLOCATED, Boolean.TRUE); message.put(Message.WSDL_OPERATION, boi.getName()); message.put(Message.WSDL_INTERFACE, boi.getBinding().getInterface().getName()); invokeColocObserver(message, srv.getEndpoint()); if (!exchange.isOneWay()) { invokeInboundChain(exchange, senderEndpoint); } } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Operation:" + boi.getName() + " dispatched as remote call."); } message.put(COLOCATED, Boolean.FALSE); } }
protected Message createMessage( Object body, String httpMethod, MultivaluedMap<String, String> headers, URI currentURI, Exchange exchange, Map<String, Object> invocationContext, boolean proxy) { Message m = cfg.getConduitSelector().getEndpoint().getBinding().createMessage(); m.put(Message.REQUESTOR_ROLE, Boolean.TRUE); m.put(Message.INBOUND_MESSAGE, Boolean.FALSE); m.put(Message.HTTP_REQUEST_METHOD, httpMethod); m.put(Message.PROTOCOL_HEADERS, headers); if (currentURI.isAbsolute() && currentURI.getScheme().startsWith(HTTP_SCHEME)) { m.put(Message.ENDPOINT_ADDRESS, currentURI.toString()); } else { m.put(Message.ENDPOINT_ADDRESS, state.getBaseURI().toString()); } Object requestURIProperty = cfg.getRequestContext().get(Message.REQUEST_URI); if (requestURIProperty == null) { m.put(Message.REQUEST_URI, currentURI.toString()); } else { m.put(Message.REQUEST_URI, requestURIProperty.toString()); } m.put(Message.CONTENT_TYPE, headers.getFirst(HttpHeaders.CONTENT_TYPE)); body = checkIfBodyEmpty(body); setEmptyRequestPropertyIfNeeded(m, body); m.setContent(List.class, getContentsList(body)); m.put(URITemplate.TEMPLATE_PARAMETERS, getState().getTemplates()); PhaseInterceptorChain chain = setupOutInterceptorChain(cfg); chain.setFaultObserver(setupInFaultObserver(cfg)); m.setInterceptorChain(chain); exchange = createExchange(m, exchange); exchange.put(Message.REST_MESSAGE, Boolean.TRUE); exchange.setOneWay("true".equals(headers.getFirst(Message.ONE_WAY_REQUEST))); exchange.put(Retryable.class, new RetryableImpl()); // context setContexts(m, exchange, invocationContext, proxy); // setup conduit selector prepareConduitSelector(m, currentURI, proxy); return m; }
private void writeResponseErrorMessage( Message message, OutputStream out, String name, Class<?> cls, MediaType ct) { message.put(Message.CONTENT_TYPE, "text/plain"); message.put(Message.RESPONSE_CODE, 500); try { String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct); if (out != null) { out.write(errorMessage.getBytes(StandardCharsets.UTF_8)); } } catch (IOException another) { // ignore } }
protected void handle(Message message) throws SequenceFault, RMException { LOG.entering(getClass().getName(), "handleMessage"); // This message capturing mechanism will need to be changed at some point. // Until then, we keep this interceptor here and utilize the robust // option to avoid the unnecessary message capturing/caching. if (!MessageUtils.isTrue(message.getContextualProperty(Message.ROBUST_ONEWAY))) { InputStream is = message.getContent(InputStream.class); if (is != null) { CachedOutputStream saved = new CachedOutputStream(); try { IOUtils.copy(is, saved); saved.flush(); is.close(); saved.lockOutputStream(); LOG.fine("Capturing the original RM message"); RewindableInputStream ris = RewindableInputStream.makeRewindable(saved.getInputStream()); message.setContent(InputStream.class, ris); message.put(RMMessageConstants.SAVED_CONTENT, ris); } catch (Exception e) { throw new Fault(e); } } } }
public AsyncResponseImpl(Message inMessage) { inMessage.put(AsyncResponse.class, this); inMessage.getExchange().put(ContinuationCallback.class, this); this.inMessage = inMessage; initContinuation(); }
protected void transformXWriter(Message message, XMLStreamWriter xWriter) { CachedWriter writer = new CachedWriter(); XMLStreamWriter delegate = StaxUtils.createXMLStreamWriter(writer); XSLTStreamWriter wrapper = new XSLTStreamWriter(getXSLTTemplate(), writer, delegate, xWriter); message.setContent(XMLStreamWriter.class, wrapper); message.put(AbstractOutDatabindingInterceptor.DISABLE_OUTPUTSTREAM_OPTIMIZATION, Boolean.TRUE); }
public void handleMessage(Message message) throws Fault { final OutputStream os = message.getContent(OutputStream.class); final Writer iowriter = message.getContent(Writer.class); if (os == null && iowriter == null) { return; } Logger logger = getMessageLogger(message); if (logger.isLoggable(Level.INFO) || writer != null) { // Write the output while caching it for the log message boolean hasLogged = message.containsKey(LOG_SETUP); if (!hasLogged) { message.put(LOG_SETUP, Boolean.TRUE); if (os != null) { final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(os); if (threshold > 0) { newOut.setThreshold(threshold); } if (limit > 0) { newOut.setCacheLimit(limit); } message.setContent(OutputStream.class, newOut); newOut.registerCallback(new LoggingCallback(logger, message, os)); } else { message.setContent(Writer.class, new LogWriter(logger, message, iowriter)); } } } }
private void recoverSourceSequence( Endpoint endpoint, Conduit conduit, Source s, SourceSequence ss) { Collection<RMMessage> ms = store.getMessages(ss.getIdentifier(), true); if (null == ms || 0 == ms.size()) { store.removeSourceSequence(ss.getIdentifier()); return; } LOG.log(Level.FINE, "Number of messages in sequence: {0}", ms.size()); s.addSequence(ss, false); // choosing an arbitrary valid source sequence as the current source sequence if (s.getAssociatedSequence(null) == null && !ss.isExpired() && !ss.isLastMessage()) { s.setCurrent(ss); } for (RMMessage m : ms) { Message message = new MessageImpl(); Exchange exchange = new ExchangeImpl(); message.setExchange(exchange); exchange.setOutMessage(message); if (null != conduit) { exchange.setConduit(conduit); message.put(Message.REQUESTOR_ROLE, Boolean.TRUE); } exchange.put(Endpoint.class, endpoint); exchange.put(Service.class, endpoint.getService()); exchange.put(Binding.class, endpoint.getBinding()); exchange.put(Bus.class, bus); SequenceType st = new SequenceType(); st.setIdentifier(ss.getIdentifier()); st.setMessageNumber(m.getMessageNumber()); RMProperties rmps = new RMProperties(); rmps.setSequence(st); rmps.exposeAs(ss.getProtocol().getWSRMNamespace()); if (ss.isLastMessage() && ss.getCurrentMessageNr() == m.getMessageNumber()) { CloseSequenceType close = new CloseSequenceType(); close.setIdentifier(ss.getIdentifier()); rmps.setCloseSequence(close); } RMContextUtils.storeRMProperties(message, rmps, true); if (null == conduit) { String to = m.getTo(); AddressingProperties maps = new AddressingProperties(); maps.setTo(RMUtils.createReference(to)); RMContextUtils.storeMAPs(maps, message, true, false); } try { // RMMessage is stored in a serialized way, therefore // RMMessage content must be splitted into soap root message // and attachments PersistenceUtils.decodeRMContent(m, message); RMContextUtils.setProtocolVariation(message, ss.getProtocol()); retransmissionQueue.addUnacknowledged(message); } catch (IOException e) { LOG.log(Level.SEVERE, "Error reading persisted message data", e); } } }
private void processResponse(ServerProviderFactory providerFactory, Message message) { if (isResponseAlreadyHandled(message)) { return; } MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs == null || objs.size() == 0) { return; } Object responseObj = objs.get(0); Response response = null; if (responseObj instanceof Response) { response = (Response) responseObj; if (response.getStatus() == 500 && message.getExchange().get(JAXRSUtils.EXCEPTION_FROM_MAPPER) != null) { message.put(Message.RESPONSE_CODE, 500); return; } } else { int status = getStatus(message, responseObj != null ? 200 : 204); response = JAXRSUtils.toResponseBuilder(status).entity(responseObj).build(); } Exchange exchange = message.getExchange(); OperationResourceInfo ori = (OperationResourceInfo) exchange.get(OperationResourceInfo.class.getName()); serializeMessage(providerFactory, message, response, ori, true); }
protected void setContexts( Message message, Exchange exchange, Map<String, Object> context, boolean proxy) { Map<String, Object> reqContext = null; Map<String, Object> resContext = null; if (context == null) { context = new HashMap<String, Object>(); } reqContext = CastUtils.cast((Map<?, ?>) context.get(REQUEST_CONTEXT)); resContext = CastUtils.cast((Map<?, ?>) context.get(RESPONSE_CONTEXT)); if (reqContext == null) { reqContext = new HashMap<String, Object>(cfg.getRequestContext()); context.put(REQUEST_CONTEXT, reqContext); } reqContext.put(Message.PROTOCOL_HEADERS, message.get(Message.PROTOCOL_HEADERS)); reqContext.put(Message.REQUEST_URI, message.get(Message.REQUEST_URI)); reqContext.put(Message.ENDPOINT_ADDRESS, message.get(Message.ENDPOINT_ADDRESS)); reqContext.put(PROXY_PROPERTY, proxy); if (resContext == null) { resContext = new HashMap<String, Object>(); context.put(RESPONSE_CONTEXT, resContext); } message.put(Message.INVOCATION_CONTEXT, context); message.putAll(reqContext); exchange.putAll(reqContext); }
@Test public void testGetProperty() { Message m = new MessageImpl(); m.put("a", "b"); MessageContext mc = new MessageContextImpl(m); assertEquals("b", mc.get("a")); assertNull(mc.get("b")); }
@Override protected void updateResponseHeaders(Message inMessage) throws IOException { Headers h = new Headers(inMessage); String ct = getResponse().getContentType(); inMessage.put(Message.CONTENT_TYPE, ct); // REVISIT if we are allowing more headers, we need to add them into the cxf's headers h.headerMap().put(Message.CONTENT_TYPE, Collections.singletonList(ct)); }
protected void updateResponseHeaders(Message message) { Map<String, List<String>> responseHeaders = CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS)); if (responseHeaders == null) { responseHeaders = new HashMap<String, List<String>>(); message.put(Message.PROTOCOL_HEADERS, responseHeaders); } setPolicies(responseHeaders); }
private Map<String, List<String>> getHeaders(Message message) { Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); if (headers == null) { headers = new HashMap<>(); message.put(Message.PROTOCOL_HEADERS, headers); } return headers; }
public void handleMessage(Message message) throws Fault { String method = (String) message.get(Message.HTTP_REQUEST_METHOD); if (!method.equals("POST")) { return; } StringBuilder sb = new StringBuilder(); sb.append("Foo"); message.put(StringBuilder.class, sb); }
private void setResponseStatus(Message message, int status) { message.put(Message.RESPONSE_CODE, status); boolean responseHeadersCopied = isResponseHeadersCopied(message); if (responseHeadersCopied) { HttpServletResponse response = (HttpServletResponse) message.get(AbstractHTTPDestination.HTTP_RESPONSE); response.setStatus(status); } }
@Test public void testServletConfig() { Message m = createMessage(); MessageContext mc = new MessageContextImpl(m); ServletConfig request = EasyMock.createMock(ServletConfig.class); m.put(AbstractHTTPDestination.HTTP_CONFIG, request); assertSame(request.getClass(), mc.getServletConfig().getClass()); assertSame(request.getClass(), mc.getContext(ServletConfig.class).getClass()); }
/** * This test verifies the precedence of Authorization Information. Setting authorization * information on the Message takes precedence over a Basic Auth Supplier with preemptive * UserPass, and that followed by setting it directly on the Conduit. */ @Test public void testAuthPolicyPrecedence() throws Exception { Bus bus = new ExtensionManagerBus(); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://nowhere.com/bar/foo"); HTTPConduit conduit = new URLConnectionHTTPConduit(bus, ei, null); conduit.finalizeConfig(); conduit.getAuthorization().setUserName("Satan"); conduit.getAuthorization().setPassword("hell"); Message message = getNewMessage(); // Test call conduit.prepare(message); Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); assertNotNull("Authorization Header should exist", headers.get("Authorization")); assertEquals( "Unexpected Authorization Token", "Basic " + Base64Utility.encode("Satan:hell".getBytes()), headers.get("Authorization").get(0)); // Setting a Basic Auth User Pass should override conduit.setAuthSupplier(new TestAuthSupplier()); message = getNewMessage(); // Test Call conduit.prepare(message); headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); List<String> authorization = headers.get("Authorization"); assertNotNull("Authorization Token must be set", authorization); assertEquals("Wrong Authorization Token", "myauth", authorization.get(0)); conduit.setAuthSupplier(null); // Setting authorization policy on the message should override // conduit setting AuthorizationPolicy authPolicy = new AuthorizationPolicy(); authPolicy.setUserName("Hello"); authPolicy.setPassword("world"); authPolicy.setAuthorizationType("Basic"); message = getNewMessage(); message.put(AuthorizationPolicy.class, authPolicy); conduit.prepare(message); headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); assertEquals( "Unexpected Authorization Token", "Basic " + Base64Utility.encode("Hello:world".getBytes()), headers.get("Authorization").get(0)); }
private Message prepareMessage( Class<?> cls, String methodName, org.apache.cxf.rt.security.claims.Claim... claim) throws Exception { ClaimCollection claims = new ClaimCollection(); claims.addAll(Arrays.asList(claim)); Set<Principal> roles = SAMLUtils.parseRolesFromClaims( claims, SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT, SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED); SecurityContext sc = new SAMLSecurityContext(new SimplePrincipal("user"), roles, claims); Message m = new MessageImpl(); m.setExchange(new ExchangeImpl()); m.put(SecurityContext.class, sc); m.put("org.apache.cxf.resource.method", cls.getMethod(methodName, new Class[] {})); return m; }
@Override public void onMessage(byte[] message, ZMQ.Socket zmqSocket) { getLogger().log(Level.FINE, "server received request: ", message); Message inMessage = new MessageImpl(); inMessage.setContent(InputStream.class, new ByteArrayInputStream(message)); ((MessageImpl) inMessage).setDestination(this); inMessage.put("socket", zmqSocket); incomingObserver.onMessage(inMessage); }
public void copyJaxWsContext( org.apache.cxf.message.Exchange cxfExchange, Map<String, Object> context) { if (cxfExchange.getOutMessage() != null) { org.apache.cxf.message.Message outMessage = cxfExchange.getOutMessage(); for (Map.Entry<String, Object> entry : context.entrySet()) { if (outMessage.get(entry.getKey()) == null) { outMessage.put(entry.getKey(), entry.getValue()); } } } }
@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()); }
// Note that some conduit selectors may update Message.ENDPOINT_ADDRESS // after the conduit selector has been prepared but before the actual // invocation thus it is also important to have baseURI and currentURI // synched up with the latest endpoint address, after a successful proxy // or web client invocation has returned protected void prepareConduitSelector(Message message, URI currentURI, boolean proxy) { try { cfg.prepareConduitSelector(message); } catch (Fault ex) { LOG.warning("Failure to prepare a message from conduit selector"); } message.getExchange().put(ConduitSelector.class, cfg.getConduitSelector()); message.getExchange().put(Service.class, cfg.getConduitSelector().getEndpoint().getService()); String address = (String) message.get(Message.ENDPOINT_ADDRESS); // custom conduits may override the initial/current address if (address.startsWith(HTTP_SCHEME) && !address.equals(currentURI.toString())) { URI baseAddress = URI.create(address); currentURI = calculateNewRequestURI(baseAddress, currentURI, proxy); message.put(Message.ENDPOINT_ADDRESS, currentURI.toString()); message.put(Message.REQUEST_URI, currentURI.toString()); } message.put(Message.BASE_PATH, getBaseURI().toString()); }
/** Generates a new message. */ private Message getNewMessage() { Message message = new MessageImpl(); Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); List<String> contentTypes = new ArrayList<String>(); contentTypes.add("text/xml"); contentTypes.add("charset=utf8"); headers.put("content-type", contentTypes); message.put(Message.PROTOCOL_HEADERS, headers); return message; }
@Test public void testGetPropertyFromOtherMessage() { Message m1 = new MessageImpl(); Message m2 = new MessageImpl(); m2.put("a", "b"); Exchange ex = new ExchangeImpl(); ex.setInMessage(m1); ex.setOutMessage(m2); MessageContext mc = new MessageContextImpl(m1); assertEquals("b", mc.get("a")); assertNull(mc.get("b")); }