public void prepare(final Message message) throws IOException { inMessage.getExchange().setOutMessage(message); final ZMQ.Socket zmqSocket = (ZMQ.Socket) inMessage.get("socket"); Exchange exchange = inMessage.getExchange(); exchange.setOutMessage(message); message.setContent( OutputStream.class, new ByteArrayOutputStream() { @Override public void close() throws IOException { super.close(); if (endpointConfig.getSocketType() == ZMQURIConstants.SocketType.REP) { getLogger().log(Level.FINE, "send out the message!"); if (hasNoResponseContent(message)) { ZMQUtils.sendMessage(zmqSocket, new byte[] {0}); } else { ZMQUtils.sendMessage(zmqSocket, toByteArray()); } } } }); }
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); }
/** * Return true if the provided certificate matches the regular expression defined in the Subject * DN Certificate Constraints. * * @param message * @return true if the certificate matches the constraints */ @Override public void handleMessage(Message message) throws Fault { if (message != null) { String subjectDNConstraints = (String) message.get(WSHandlerConstants.SIG_SUBJECT_CERT_CONSTRAINTS); if (subjectDNConstraints == null) { logger.warn( "No Subject DN Certificate Constraints were defined. This could be a security issue"); } else { Collection<Pattern> subjectDNPatterns = setSubjectDNPatterns(subjectDNConstraints); X509Certificate[] cert; cert = ((X509Certificate[]) (((Request) message.get("HTTP.REQUEST")) .getAttribute("javax.servlet.request.X509Certificate"))); if (cert == null) { throw new AccessDeniedException("No certificate provided."); } if (!(matches(cert[0], subjectDNPatterns))) { logger.warn("Certificate does not match Subject DN Certificate Constraints"); throw new AccessDeniedException("Certificate DN does not match allowed pattern(s)."); } } } }
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 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 void handleMessage(Message message) throws Fault { // check the fault from the message Throwable ex = message.getContent(Throwable.class); if (ex != null) { if (ex instanceof Fault) { throw (Fault) ex; } else { throw new Fault(ex); } } List<?> params = message.getContent(List.class); if (null != params) { InputStream is = (InputStream) params.get(0); OutputStream os = message.getContent(OutputStream.class); try { if (is instanceof StreamCache) { ((StreamCache) is).writeTo(os); } else { IOUtils.copy(is, os); } } catch (Exception e) { throw new Fault(e); } finally { IOHelper.close(is, "input stream", null); // Should not close the output stream as the interceptor chain will close it } } }
@Test public void testAuthPolicyFromEndpointInfo() throws Exception { Bus bus = new ExtensionManagerBus(); EndpointInfo ei = new EndpointInfo(); AuthorizationPolicy ap = new AuthorizationPolicy(); ap.setPassword("password"); ap.setUserName("testUser"); ei.addExtensor(ap); ei.setAddress("http://nowhere.com/bar/foo"); HTTPConduit conduit = new URLConnectionHTTPConduit(bus, ei, null); conduit.finalizeConfig(); 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("testUser:password".getBytes()), headers.get("Authorization").get(0)); }
public void prepare(final Message message) throws IOException { if (!Boolean.TRUE.equals(message.getExchange().get(LocalConduit.DIRECT_DISPATCH))) { final Exchange exchange = (Exchange) message.getExchange().get(LocalConduit.IN_EXCHANGE); AbstractWrappedOutputStream cout = new AbstractWrappedOutputStream() { protected void onFirstWrite() throws IOException { final PipedInputStream stream = new PipedInputStream(); wrappedStream = new PipedOutputStream(stream); final MessageImpl m = new MessageImpl(); localDestinationFactory.copy(message, m); m.setContent(InputStream.class, stream); final Runnable receiver = new Runnable() { public void run() { if (exchange != null) { exchange.setInMessage(m); } conduit.getMessageObserver().onMessage(m); } }; new Thread(receiver).start(); } }; message.setContent(OutputStream.class, cout); } else { CachedOutputStream stream = new CachedOutputStream(); message.setContent(OutputStream.class, stream); } }
private void doFromSoapMessage(Message message, Object sm) { SOAPMessage m = (SOAPMessage) sm; MessageContentsList list = (MessageContentsList) message.getContent(List.class); if (list == null) { list = new MessageContentsList(); message.setContent(List.class, list); } Object o = m; if (StreamSource.class.isAssignableFrom(type)) { try { try (CachedOutputStream out = new CachedOutputStream()) { XMLStreamWriter xsw = StaxUtils.createXMLStreamWriter(out); StaxUtils.copy(new DOMSource(m.getSOAPPart()), xsw); xsw.close(); o = new StreamSource(out.getInputStream()); } } catch (Exception e) { throw new Fault(e); } } else if (SAXSource.class.isAssignableFrom(type)) { o = new StaxSource(new W3CDOMStreamReader(m.getSOAPPart())); } else if (Source.class.isAssignableFrom(type)) { o = new DOMSource(m.getSOAPPart()); } list.set(0, o); }
protected void doRunInterceptorChain(Message m) { try { m.getInterceptorChain().doIntercept(m); } catch (Exception ex) { m.setContent(Exception.class, ex); } }
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); }
protected <T> void writeBody( T o, Message outMessage, Class<?> cls, Type type, Annotation[] anns, OutputStream os) { if (o == null) { return; } @SuppressWarnings("unchecked") MultivaluedMap<String, Object> headers = (MultivaluedMap<String, Object>) outMessage.get(Message.PROTOCOL_HEADERS); @SuppressWarnings("unchecked") Class<T> theClass = (Class<T>) cls; MediaType contentType = JAXRSUtils.toMediaType(headers.getFirst("Content-Type").toString()); List<WriterInterceptor> writers = ClientProviderFactory.getInstance(outMessage) .createMessageBodyWriterInterceptor( theClass, type, anns, contentType, outMessage, null); if (writers != null) { try { JAXRSUtils.writeMessageBody( writers, o, theClass, type, anns, contentType, headers, outMessage); OutputStream realOs = outMessage.get(OutputStream.class); if (realOs != null) { realOs.flush(); } } catch (Exception ex) { reportMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, contentType, ex); } } else { reportMessageHandlerProblem("NO_MSG_WRITER", cls, contentType, null); } }
@Override public void handleMessage(Message message) throws Fault { Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); TraceScope scope = super.startTraceSpan(headers, (String) message.get(Message.REQUEST_URI)); message.getExchange().put(TRACE_SPAN, scope); }
protected Object handleResponse(Message outMessage, Class<?> serviceCls) throws Throwable { try { Response r = setResponseBuilder(outMessage, outMessage.getExchange()).build(); ((ResponseImpl) r).setOutMessage(outMessage); getState().setResponse(r); Method method = outMessage.getExchange().get(Method.class); checkResponse(method, r, outMessage); if (method.getReturnType() == Void.class || method.getReturnType() == Void.TYPE) { return null; } if (method.getReturnType() == Response.class && (r.getEntity() == null || InputStream.class.isAssignableFrom(r.getEntity().getClass()) && ((InputStream) r.getEntity()).available() == 0)) { return r; } if (PropertyUtils.isTrue( super.getConfiguration().getResponseContext().get(BUFFER_PROXY_RESPONSE))) { r.bufferEntity(); } Class<?> returnType = method.getReturnType(); Type genericType = InjectionUtils.processGenericTypeIfNeeded( serviceCls, returnType, method.getGenericReturnType()); returnType = InjectionUtils.updateParamClassToTypeIfNeeded(returnType, genericType); return readBody(r, outMessage, returnType, genericType, method.getDeclaredAnnotations()); } finally { ClientProviderFactory.getInstance(outMessage).clearThreadLocalProxies(); } }
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); }
/** * 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()); } }
public AsyncResponseImpl(Message inMessage) { inMessage.put(AsyncResponse.class, this); inMessage.getExchange().put(ContinuationCallback.class, this); this.inMessage = inMessage; initContinuation(); }
/** * Copy the response headers into the response. * * @param message the current message * @param headers the current set of headers */ protected void copyResponseHeaders(Message message, HttpServletResponse response) { String ct = (String) message.get(Message.CONTENT_TYPE); String enc = (String) message.get(Message.ENCODING); if (null != ct && null != enc && ct.indexOf("charset=") == -1 && !ct.toLowerCase().contains("multipart/related")) { ct = ct + "; charset=" + enc; } Map<?, ?> headers = (Map<?, ?>) message.get(Message.PROTOCOL_HEADERS); if (null != headers) { if (!headers.containsKey(Message.CONTENT_TYPE)) { response.setContentType(ct); } for (Iterator<?> iter = headers.keySet().iterator(); iter.hasNext(); ) { String header = (String) iter.next(); List<?> headerList = (List<?>) headers.get(header); StringBuilder sb = new StringBuilder(); for (int i = 0; i < headerList.size(); i++) { sb.append(headerList.get(i)); if (i + 1 < headerList.size()) { sb.append(','); } } response.addHeader(header, sb.toString()); } } else { response.setContentType(ct); } }
protected Message getMessage() { Message m = message; if (m != null && m.getExchange().getInMessage() != null) { m = m.getExchange().getInMessage(); } return m; }
public void handleMessage(Message msg) { Fault fault = (Fault) msg.getContent(Exception.class); if (fault.getDetail() != null && !MessageUtils.getContextualBoolean(msg, DISABLE_FAULT_MAPPING, false)) { processFaultDetail(fault, msg); setStackTrace(fault, msg); } FaultMode faultMode = FaultMode.UNCHECKED_APPLICATION_FAULT; // Check if the raised exception is declared in the WSDL or by the JAX-RS resource Method m = msg.getExchange().get(Method.class); if (m != null) { Exception e = msg.getContent(Exception.class); for (Class<?> cl : m.getExceptionTypes()) { if (cl.isInstance(e)) { faultMode = FaultMode.CHECKED_APPLICATION_FAULT; break; } } } msg.getExchange().put(FaultMode.class, faultMode); }
@Test public void testNoWadl() { WadlGenerator wg = new WadlGenerator(); Message m = new MessageImpl(); m.setExchange(new ExchangeImpl()); assertNull(handleRequest(wg, m)); }
protected AhcWebSocketWrappedOutputStream( Message message, boolean possibleRetransmit, boolean isChunking, int chunkThreshold, String conduitName, URI url) { super(message, possibleRetransmit, isChunking, chunkThreshold, conduitName, url); entity = message.get(AhcWebSocketConduitRequest.class); // REVISIT how we prepare the request String requri = (String) message.getContextualProperty("org.apache.cxf.request.uri"); if (requri != null) { // jaxrs speicfies a sub-path using prop org.apache.cxf.request.uri if (requri.startsWith("ws")) { entity.setPath(requri.substring(requri.indexOf('/', 3 + requri.indexOf(':')))); } else { entity.setPath(url.getPath() + requri); } } else { // jaxws entity.setPath(url.getPath()); } entity.setId(UUID.randomUUID().toString()); uncorrelatedRequests.put(entity.getId(), new RequestResponse(entity)); }
private HttpSession getSession() { Message message = PhaseInterceptorChain.getCurrentMessage(); HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST); HttpSession session = request.getSession(true); return session; }
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 checkCachedStream(Message m, OutputStream osOriginal, boolean enabled) throws Exception { XMLStreamWriter writer = null; if (enabled) { writer = m.getContent(XMLStreamWriter.class); } else { writer = (XMLStreamWriter) m.get(XMLStreamWriter.class.getName()); } if (writer instanceof CachingXmlEventWriter) { CachingXmlEventWriter cache = (CachingXmlEventWriter) writer; if (cache.getEvents().size() != 0) { XMLStreamWriter origWriter = null; try { origWriter = StaxUtils.createXMLStreamWriter(osOriginal); for (XMLEvent event : cache.getEvents()) { StaxUtils.writeEvent(event, origWriter); } } finally { StaxUtils.close(origWriter); } } m.setContent(XMLStreamWriter.class, null); return; } if (enabled) { OutputStream os = m.getContent(OutputStream.class); if (os != osOriginal && os instanceof CachedOutputStream) { CachedOutputStream cos = (CachedOutputStream) os; if (cos.size() != 0) { cos.writeCacheTo(osOriginal); } } } }
@Override public void handleMessage(Message message) { if (!shouldSchemaValidate(message)) { return; } if (checkContextProperty(message)) { return; } // 1. Try to get and transform XMLStreamWriter message content XMLStreamWriter xWriter = message.getContent(XMLStreamWriter.class); if (xWriter != null) { transformXWriter(message, xWriter); } else { // 2. Try to get and transform OutputStream message content OutputStream out = message.getContent(OutputStream.class); if (out != null) { transformOS(message, out); } else { // 3. Try to get and transform Writer message content (actually used for JMS TextMessage) Writer writer = message.getContent(Writer.class); if (writer != null) { transformWriter(message, writer); } } } }
/* (non-Javadoc) * @see org.apache.cxf.interceptor.Interceptor#handleMessage(org.apache.cxf.message.Message) */ public void handleMessage(Message message) { try { if (message != null) { List<Object> params = message.getContent(List.class); // parameter instances if (params.get(0) instanceof HasXsl) { OperationResourceInfo ori = message.getExchange().get(OperationResourceInfo.class); JAXBElementProvider provider = (JAXBElementProvider) ProviderFactory.getInstance(message) .createMessageBodyWriter( ori.getMethodToInvoke().getReturnType(), ori.getMethodToInvoke().getGenericReturnType(), ori.getMethodToInvoke().getAnnotations(), MediaType.APPLICATION_XML_TYPE, message); Map<String, Object> properties = new HashMap<String, Object>(); HasXsl hasXsl = (HasXsl) params.get(0); // System.out.println("Stylesheet params " + hasXsl.getClass() + " " + hasXsl.getXsl()); if (hasXsl == null || hasXsl.getXsl().equalsIgnoreCase(Constants.NO_XSL)) { properties.put(XML_HEADERS, "<!-- no stylesheet -->"); } else { properties.put( XML_HEADERS, "<?xml-stylesheet type='application/xml' href='" + hasXsl.getXsl() + "'?>"); } provider.setMarshallerProperties(properties); } } } catch (Throwable x) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST).build()); } }
private EndpointReferenceType getReplyTo(Message message, EndpointReferenceType originalReplyTo) { Exchange exchange = message.getExchange(); Endpoint info = exchange.getEndpoint(); if (info == null) { return originalReplyTo; } synchronized (info) { EndpointInfo ei = info.getEndpointInfo(); Destination dest = ei.getProperty(DECOUPLED_DESTINATION, Destination.class); if (dest == null) { dest = createDecoupledDestination(message); if (dest != null) { info.getEndpointInfo().setProperty(DECOUPLED_DESTINATION, dest); } } if (dest != null) { // if the decoupled endpoint context prop is set and the address is relative, return the // absolute url. final String replyTo = dest.getAddress().getAddress().getValue(); if (replyTo.startsWith("/")) { String debase = (String) message.getContextualProperty(WSAContextUtils.DECOUPLED_ENDPOINT_BASE_PROPERTY); if (debase != null) { return EndpointReferenceUtils.getEndpointReference(debase + replyTo); } } return dest.getAddress(); } } return originalReplyTo; }
private Destination createDecoupledDestination(Message message) { String replyToAddress = (String) message.getContextualProperty(WSAContextUtils.REPLYTO_PROPERTY); if (replyToAddress != null) { return setUpDecoupledDestination(message.getExchange().getBus(), replyToAddress, message); } return null; }
@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")); }