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 UriInfoImpl(Message m, MultivaluedMap<String, String> templateParams) { this.message = m; this.templateParams = templateParams; if (m != null) { this.stack = m.get(OperationResourceInfoStack.class); this.caseInsensitiveQueries = MessageUtils.isTrue(m.getContextualProperty(CASE_INSENSITIVE_QUERIES)); } }
public static final void disableMTOMResponse(WebServiceContext wsContext) { MessageContext msgCtx = wsContext.getMessageContext(); WrappedMessageContext wmc = (WrappedMessageContext) msgCtx; Exchange ex = wmc.getWrappedMessage().getExchange(); Message out = ex.getOutMessage(); if (out != null) { int i = 0; for (; MessageUtils.isTrue(out.getContextualProperty(Message.MTOM_ENABLED)) && i < 10; i++) { out.setContextualProperty(Message.MTOM_ENABLED, false); log.debug( "###### disableMTOM! enabled:{}", out.getContextualProperty(Message.MTOM_ENABLED)); } if (i > 1) log.warn( "###### disable MTOM needs " + i + " tries! enabled:{}", out.getContextualProperty(Message.MTOM_ENABLED)); } log.debug("###### MTOM enabled? {}:", out.getContextualProperty(Message.MTOM_ENABLED)); }
private boolean checkBufferingMode(Message m, List<WriterInterceptor> writers, boolean firstTry) { if (!firstTry) { return false; } WriterInterceptor last = writers.get(writers.size() - 1); MessageBodyWriter<Object> w = ((WriterInterceptorMBW) last).getMBW(); Object outBuf = m.getContextualProperty(OUT_BUFFERING); boolean enabled = MessageUtils.isTrue(outBuf); boolean configurableProvider = w instanceof AbstractConfigurableProvider; if (!enabled && outBuf == null && configurableProvider) { enabled = ((AbstractConfigurableProvider) w).getEnableBuffering(); } if (enabled) { boolean streamingOn = configurableProvider ? ((AbstractConfigurableProvider) w).getEnableStreaming() : false; if (streamingOn) { m.setContent(XMLStreamWriter.class, new CachingXmlEventWriter()); } else { m.setContent(OutputStream.class, new CachedOutputStream()); } } return enabled; }
/** * Validate incoming MAPs * * @param maps the incoming MAPs * @param message the current message * @return true if incoming MAPs are valid * @pre inbound message, not requestor */ private boolean validateIncomingMAPs(AddressingProperties maps, Message message) { boolean valid = true; if (maps != null) { // WSAB spec, section 4.2 validation (SOAPAction must match action String sa = SoapActionInInterceptor.getSoapAction(message); String s1 = this.getActionUri(message, false); if (maps.getAction() == null || maps.getAction().getValue() == null) { String reason = BUNDLE.getString("MISSING_ACTION_MESSAGE"); ContextUtils.storeMAPFaultName(Names.HEADER_REQUIRED_NAME, message); ContextUtils.storeMAPFaultReason(reason, message); valid = false; } if (!StringUtils.isEmpty(sa) && valid && !MessageUtils.isTrue(message.get(MAPAggregator.ACTION_VERIFIED))) { if (sa.startsWith("\"")) { sa = sa.substring(1, sa.lastIndexOf('"')); } String action = maps.getAction() == null ? "" : maps.getAction().getValue(); if (!StringUtils.isEmpty(sa) && !sa.equals(action)) { // don't match, must send fault back.... String reason = BUNDLE.getString("INVALID_ADDRESSING_PROPERTY_MESSAGE"); ContextUtils.storeMAPFaultName(Names.ACTION_MISMATCH_NAME, message); ContextUtils.storeMAPFaultReason(reason, message); valid = false; } else if (!StringUtils.isEmpty(s1) && !action.equals(s1) && !action.equals(s1 + "Request") && !s1.equals(action + "Request")) { // if java first, it's likely to have "Request", if wsdl first, // it will depend if the wsdl:input has a name or not. Thus, we'll // check both plain and with the "Request" trailer // doesn't match what's in the wsdl/annotations String reason = BundleUtils.getFormattedString(BUNDLE, "ACTION_NOT_SUPPORTED_MSG", action); ContextUtils.storeMAPFaultName(Names.ACTION_NOT_SUPPORTED_NAME, message); ContextUtils.storeMAPFaultReason(reason, message); valid = false; } } AttributedURIType messageID = maps.getMessageID(); if (!message.getExchange().isOneWay() && (messageID == null || messageID.getValue() == null) && valid) { String reason = BUNDLE.getString("MISSING_ACTION_MESSAGE"); ContextUtils.storeMAPFaultName(Names.HEADER_REQUIRED_NAME, message); ContextUtils.storeMAPFaultReason(reason, message); valid = false; } // Always cache message IDs, even when the message is not valid for some // other reason. if (!allowDuplicates && messageID != null && messageID.getValue() != null && !messageIdCache.checkUniquenessAndCacheId(messageID.getValue())) { LOG.log(Level.WARNING, "DUPLICATE_MESSAGE_ID_MSG", messageID.getValue()); // Only throw the fault if something else has not already marked the // message as invalid. if (valid) { String reason = BUNDLE.getString("DUPLICATE_MESSAGE_ID_MSG"); String l7dReason = MessageFormat.format(reason, messageID.getValue()); ContextUtils.storeMAPFaultName(Names.DUPLICATE_MESSAGE_ID_NAME, message); ContextUtils.storeMAPFaultReason(l7dReason, message); } valid = false; } } else if (usingAddressingAdvisory) { String reason = BUNDLE.getString("MISSING_ACTION_MESSAGE"); ContextUtils.storeMAPFaultName(Names.HEADER_REQUIRED_NAME, message); ContextUtils.storeMAPFaultReason(reason, message); valid = false; } if (Names.INVALID_CARDINALITY_NAME.equals(ContextUtils.retrieveMAPFaultName(message))) { valid = false; } return valid; }
// Some CXF interceptors such as FIStaxOutInterceptor will indirectly initiate // an early copying of response code and headers into the HttpServletResponse // TODO : Pushing the filter processing and copying response headers into say // PRE-LOGICAl and PREPARE_SEND interceptors will most likely be a good thing // however JAX-RS MessageBodyWriters are also allowed to add response headers // which is reason why a MultipartMap parameter in MessageBodyWriter.writeTo // method is modifiable. Thus we do need to know if the initial copy has already // occurred: for now we will just use to ensure the correct status is set private boolean isResponseHeadersCopied(Message message) { return MessageUtils.isTrue(message.get(AbstractHTTPDestination.RESPONSE_HEADERS_COPIED)); }
// CHECKSTYLE:OFF - spec requires a bunch of params public W3CEndpointReference createW3CEndpointReference( String address, QName interfaceName, QName serviceName, QName portName, List<Element> metadata, String wsdlDocumentLocation, List<Element> referenceParameters, List<Element> elements, Map<QName, String> attributes) { // CHECKSTYLE:ON if (serviceName != null && portName != null && wsdlDocumentLocation != null && interfaceName == null) { Bus bus = BusFactory.getThreadDefaultBus(); WSDLManager wsdlManager = bus.getExtension(WSDLManager.class); try { Definition def = wsdlManager.getDefinition(wsdlDocumentLocation); interfaceName = def.getService(serviceName) .getPort(portName.getLocalPart()) .getBinding() .getPortType() .getQName(); } catch (Exception e) { // do nothing } } if (serviceName == null && portName == null && address == null) { throw new IllegalStateException( "Address in an EPR cannot be null, " + " when serviceName or portName is null"); } try { W3CDOMStreamWriter writer = new W3CDOMStreamWriter(); writer.setPrefix(JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.NS_WSA); writer.writeStartElement( JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.WSA_ERF_NAME, JAXWSAConstants.NS_WSA); writer.writeNamespace(JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.NS_WSA); writer.writeStartElement( JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.WSA_ADDRESS_NAME, JAXWSAConstants.NS_WSA); address = address == null ? "" : address; writer.writeCharacters(address); writer.writeEndElement(); if (referenceParameters != null) { writer.writeStartElement( JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.WSA_REFERENCEPARAMETERS_NAME, JAXWSAConstants.NS_WSA); for (Element ele : referenceParameters) { StaxUtils.writeElement(ele, writer, true); } writer.writeEndElement(); } if (wsdlDocumentLocation != null || interfaceName != null || serviceName != null || (metadata != null && metadata.size() > 0)) { writer.writeStartElement( JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.WSA_METADATA_NAME, JAXWSAConstants.NS_WSA); writer.writeNamespace(JAXWSAConstants.WSAW_PREFIX, JAXWSAConstants.NS_WSAW); writer.writeNamespace(JAXWSAConstants.WSAM_PREFIX, JAXWSAConstants.NS_WSAM); if (wsdlDocumentLocation != null) { boolean includeLocationOnly = false; org.apache.cxf.message.Message message = PhaseInterceptorChain.getCurrentMessage(); if (message != null) { includeLocationOnly = MessageUtils.isTrue( message.getContextualProperty("org.apache.cxf.wsa.metadata.wsdlLocationOnly")); } String attrubuteValue = serviceName != null && !includeLocationOnly ? serviceName.getNamespaceURI() + " " + wsdlDocumentLocation : wsdlDocumentLocation; writer.writeNamespace(JAXWSAConstants.WSDLI_PFX, JAXWSAConstants.NS_WSDLI); writer.writeAttribute( JAXWSAConstants.WSDLI_PFX, JAXWSAConstants.NS_WSDLI, JAXWSAConstants.WSDLI_WSDLLOCATION, attrubuteValue); } if (interfaceName != null) { writer.writeStartElement( JAXWSAConstants.WSAM_PREFIX, JAXWSAConstants.WSAM_INTERFACE_NAME, JAXWSAConstants.NS_WSAM); String portTypePrefix = interfaceName.getPrefix(); if (portTypePrefix == null || portTypePrefix.equals("")) { portTypePrefix = "ns1"; } writer.writeNamespace(portTypePrefix, interfaceName.getNamespaceURI()); writer.writeCharacters(portTypePrefix + ":" + interfaceName.getLocalPart()); writer.writeEndElement(); } String serviceNamePrefix = null; if (serviceName != null) { serviceNamePrefix = (serviceName.getPrefix() == null || serviceName.getPrefix().length() == 0) ? "ns2" : serviceName.getPrefix(); writer.writeStartElement( JAXWSAConstants.WSAM_PREFIX, JAXWSAConstants.WSAM_SERVICENAME_NAME, JAXWSAConstants.NS_WSAM); if (portName != null) { writer.writeAttribute(JAXWSAConstants.WSAM_ENDPOINT_NAME, portName.getLocalPart()); } writer.writeNamespace(serviceNamePrefix, serviceName.getNamespaceURI()); writer.writeCharacters(serviceNamePrefix + ":" + serviceName.getLocalPart()); writer.writeEndElement(); } if (wsdlDocumentLocation != null) { writer.writeStartElement( WSDLConstants.WSDL_PREFIX, WSDLConstants.QNAME_DEFINITIONS.getLocalPart(), WSDLConstants.NS_WSDL11); writer.writeNamespace(WSDLConstants.WSDL_PREFIX, WSDLConstants.NS_WSDL11); writer.writeStartElement( WSDLConstants.WSDL_PREFIX, WSDLConstants.QNAME_IMPORT.getLocalPart(), WSDLConstants.QNAME_IMPORT.getNamespaceURI()); if (serviceName != null) { writer.writeAttribute(WSDLConstants.ATTR_NAMESPACE, serviceName.getNamespaceURI()); } writer.writeAttribute(WSDLConstants.ATTR_LOCATION, wsdlDocumentLocation); writer.writeEndElement(); writer.writeEndElement(); } if (metadata != null) { for (Element e : metadata) { StaxUtils.writeElement(e, writer, true); } } writer.writeEndElement(); } if (elements != null) { for (Element e : elements) { StaxUtils.writeElement(e, writer, true); } } writer.writeEndElement(); writer.flush(); Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller(); return (W3CEndpointReference) unmarshaller.unmarshal(writer.getDocument()); } catch (Exception e) { throw new WebServiceException( new Message("ERROR_UNMARSHAL_ENDPOINTREFERENCE", LOG).toString(), e); } }
@Override protected void writeParts( Message message, Exchange exchange, BindingOperationInfo operation, MessageContentsList objs, List<MessagePartInfo> parts) { // TODO Auto-generated method stub OutputStream out = message.getContent(OutputStream.class); XMLStreamWriter origXmlWriter = message.getContent(XMLStreamWriter.class); Service service = exchange.getService(); XMLStreamWriter xmlWriter = origXmlWriter; CachingXmlEventWriter cache = null; Object en = message.getContextualProperty(OUT_BUFFERING); boolean allowBuffer = true; boolean buffer = false; if (en != null) { buffer = Boolean.TRUE.equals(en) || "true".equals(en); allowBuffer = !(Boolean.FALSE.equals(en) || "false".equals(en)); } // need to cache the events in case validation fails or buffering is enabled if (buffer || (allowBuffer && shouldValidate(message) && !isRequestor(message))) { cache = new CachingXmlEventWriter(); try { cache.setNamespaceContext(origXmlWriter.getNamespaceContext()); } catch (XMLStreamException e) { // ignorable, will just get extra namespace decls } xmlWriter = cache; out = null; } if (out != null && writeToOutputStream(message, operation.getBinding(), service) && !MessageUtils.isTrue(message.getContextualProperty(DISABLE_OUTPUTSTREAM_OPTIMIZATION))) { if (xmlWriter != null) { try { xmlWriter.writeCharacters(""); xmlWriter.flush(); } catch (XMLStreamException e) { throw new Fault(e); } } DataWriter<OutputStream> osWriter = getDataWriter(message, service, OutputStream.class); for (MessagePartInfo part : parts) { if (objs.hasValue(part)) { Object o = objs.get(part); osWriter.write(o, part, out); } } } else { DataWriter<XMLStreamWriter> dataWriter = new CustomDataWriter(prismContext); for (MessagePartInfo part : parts) { if (objs.hasValue(part)) { Object o = objs.get(part); dataWriter.write(o, part, xmlWriter); } } } if (cache != null) { try { for (XMLEvent event : cache.getEvents()) { StaxUtils.writeEvent(event, origXmlWriter); } } catch (XMLStreamException e) { throw new Fault(e); } } }
protected URI calculateNewRequestURI(Map<String, Object> reqContext) { URI newBaseURI = URI.create(reqContext.get(Message.ENDPOINT_ADDRESS).toString()); URI requestURI = URI.create(reqContext.get(Message.REQUEST_URI).toString()); return calculateNewRequestURI( newBaseURI, requestURI, MessageUtils.isTrue(reqContext.get(PROXY_PROPERTY))); }
protected boolean responseStreamCanBeClosed(Message outMessage, Class<?> cls) { return cls != InputStream.class && MessageUtils.isTrue(outMessage.getContextualProperty("response.stream.auto.close")); }
protected ResponseBuilder setResponseBuilder(Message outMessage, Exchange exchange) throws Exception { Response response = exchange.get(Response.class); if (response != null) { outMessage .getExchange() .getInMessage() .put(Message.PROTOCOL_HEADERS, response.getStringHeaders()); return JAXRSUtils.fromResponse(JAXRSUtils.copyResponseIfNeeded(response)); } Integer status = getResponseCode(exchange); ResponseBuilder currentResponseBuilder = JAXRSUtils.toResponseBuilder(status); Message responseMessage = exchange.getInMessage() != null ? exchange.getInMessage() : exchange.getInFaultMessage(); // if there is no response message, we just send the response back directly if (responseMessage == null) { return currentResponseBuilder; } Map<String, List<Object>> protocolHeaders = CastUtils.cast((Map<?, ?>) responseMessage.get(Message.PROTOCOL_HEADERS)); boolean splitHeaders = MessageUtils.isTrue(outMessage.getContextualProperty(HEADER_SPLIT_PROPERTY)); for (Map.Entry<String, List<Object>> entry : protocolHeaders.entrySet()) { if (null == entry.getKey()) { continue; } if (entry.getValue().size() > 0) { if (HttpUtils.isDateRelatedHeader(entry.getKey())) { currentResponseBuilder.header(entry.getKey(), entry.getValue().get(0)); continue; } for (Object valObject : entry.getValue()) { if (splitHeaders && valObject instanceof String) { String val = (String) valObject; String[] values; if (val == null || val.length() == 0) { values = new String[] {""}; } else if (val.charAt(0) == '"' && val.charAt(val.length() - 1) == '"') { // if the value starts with a quote and ends with a quote, we do a best // effort attempt to determine what the individual values are. values = parseQuotedHeaderValue(val); } else { boolean splitPossible = !(HttpHeaders.SET_COOKIE.equalsIgnoreCase(entry.getKey()) && val.toUpperCase().contains(HttpHeaders.EXPIRES.toUpperCase())); values = splitPossible ? val.split(",") : new String[] {val}; } for (String s : values) { String theValue = s.trim(); if (theValue.length() > 0) { currentResponseBuilder.header(entry.getKey(), theValue); } } } else { currentResponseBuilder.header(entry.getKey(), valObject); } } } } String ct = (String) responseMessage.get(Message.CONTENT_TYPE); if (ct != null) { currentResponseBuilder.type(ct); } InputStream mStream = responseMessage.getContent(InputStream.class); currentResponseBuilder.entity(mStream); return currentResponseBuilder; }
/** * This method is called by {@link CxfConsumer} to populate a CXF response exchange from a Camel * exchange. */ public void populateCxfResponseFromExchange( Exchange camelExchange, org.apache.cxf.message.Exchange cxfExchange) { if (cxfExchange.isOneWay()) { return; } // create response context Map<String, Object> responseContext = new HashMap<String, Object>(); org.apache.camel.Message response; if (camelExchange.getPattern().isOutCapable()) { if (camelExchange.hasOut()) { response = camelExchange.getOut(); LOG.trace("Get the response from the out message"); } else { // Take the in message as a fall back response = camelExchange.getIn(); LOG.trace("Get the response from the in message as a fallback"); } } else { response = camelExchange.getIn(); LOG.trace("Get the response from the in message"); } // propagate response context Map<String, Object> camelHeaders = response.getHeaders(); extractInvocationContextFromCamel( camelExchange, camelHeaders, responseContext, Client.RESPONSE_CONTEXT); propagateHeadersFromCamelToCxf(camelExchange, camelHeaders, cxfExchange, responseContext); // create out message Endpoint ep = cxfExchange.get(Endpoint.class); Message outMessage = ep.getBinding().createMessage(); cxfExchange.setOutMessage(outMessage); DataFormat dataFormat = camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class); // make sure the "requestor role" property does not get propagated as we do switch role responseContext.remove(Message.REQUESTOR_ROLE); outMessage.putAll(responseContext); // Do we still need to put the response context back like this outMessage.put(Client.RESPONSE_CONTEXT, responseContext); LOG.trace("Set out response context = {}", responseContext); // set body Object outBody = DefaultCxfBinding.getBodyFromCamel(response, dataFormat); if (outBody != null) { if (dataFormat == DataFormat.PAYLOAD) { CxfPayload<?> payload = (CxfPayload<?>) outBody; outMessage.setContent( List.class, getResponsePayloadList(cxfExchange, payload.getBodySources())); outMessage.put(Header.HEADER_LIST, payload.getHeaders()); } else { if (responseContext.get(Header.HEADER_LIST) != null) { outMessage.put(Header.HEADER_LIST, responseContext.get(Header.HEADER_LIST)); } MessageContentsList resList = null; // Create a new MessageContentsList to avoid OOM from the HolderOutInterceptor if (outBody instanceof List) { resList = new MessageContentsList((List<?>) outBody); } else if (outBody.getClass().isArray()) { resList = new MessageContentsList((Object[]) outBody); } else { resList = new MessageContentsList(outBody); } if (resList != null) { outMessage.setContent(List.class, resList); LOG.trace("Set Out CXF message content = {}", resList); } } } else if (!cxfExchange.isOneWay() && cxfExchange.getInMessage() != null && MessageUtils.isTrue( cxfExchange .getInMessage() .getContextualProperty("jaxws.provider.interpretNullAsOneway"))) { // treat this non-oneway call as oneway when the provider returns a null changeToOneway(cxfExchange); return; } // propagate attachments Set<Attachment> attachments = null; boolean isXop = Boolean.valueOf(camelExchange.getProperty(Message.MTOM_ENABLED, String.class)); for (Map.Entry<String, DataHandler> entry : camelExchange.getOut().getAttachments().entrySet()) { if (attachments == null) { attachments = new HashSet<Attachment>(); } AttachmentImpl attachment = new AttachmentImpl(entry.getKey(), entry.getValue()); attachment.setXOP(isXop); attachments.add(attachment); } if (attachments != null) { outMessage.setAttachments(attachments); } BindingOperationInfo boi = cxfExchange.get(BindingOperationInfo.class); if (boi != null) { cxfExchange.put(BindingMessageInfo.class, boi.getOutput()); } }