Java Code Examples for org.apache.cxf.message.message#getContent()
The following examples show how to use
org.apache.cxf.message.message#getContent() .
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: TransformTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void transformOutboundInterceptorOutputStream() throws IOException { // Arrange Message message = new MessageImpl(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.setContent(OutputStream.class, outputStream); Exchange exchange = new ExchangeImpl(); message.setExchange(exchange); LogEventSenderMock logEventSender = new LogEventSenderMock(); LoggingOutInterceptor interceptor = new TransformLoggingOutInterceptor(logEventSender); // Act interceptor.handleMessage(message); byte[] payload = ORIG_LOGGING_CONTENT.getBytes(StandardCharsets.UTF_8); OutputStream out = message.getContent(OutputStream.class); out.write(payload); out.close(); // Verify LogEvent event = logEventSender.getLogEvent(); assertNotNull(event); assertEquals(TRANSFORMED_LOGGING_CONTENT, event.getPayload()); // only the first byte is read! }
Example 2
Source File: HttpAuthenticationFaultHandler.java From cxf with Apache License 2.0 | 6 votes |
@Override public void handleFault(Message message) { Exception ex = message.getContent(Exception.class); if (ex instanceof AuthenticationException) { HttpServletResponse resp = (HttpServletResponse)message.getExchange() .getInMessage().get(AbstractHTTPDestination.HTTP_RESPONSE); resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); resp.setHeader("WWW-Authenticate", authenticationType + " realm=\"" + realm + "\""); resp.setContentType("text/plain"); try { resp.getOutputStream().write(ex.getMessage().getBytes()); resp.getOutputStream().flush(); message.getInterceptorChain().setFaultObserver(null); //avoid return soap fault message.getInterceptorChain().abort(); } catch (IOException e) { // TODO } } }
Example 3
Source File: JAXRSSoapBookTest.java From cxf with Apache License 2.0 | 6 votes |
public void handleMessage(Message message) throws Fault { InputStream is = message.getContent(InputStream.class); if (is == null) { return; } byte[] payload; try { // input stream will be closed by readBytesFromStream() payload = IOUtils.readBytesFromStream(is); assertNotNull("payload was null", payload); assertTrue("payload was EMPTY", payload.length > 0); message.setContent(InputStream.class, new ByteArrayInputStream(payload)); } catch (Exception e) { String error = "Failed to read the stream properly due to " + e.getMessage(); assertNotNull(error, e); } }
Example 4
Source File: ExchangeUtils.java From fuchsia with Apache License 2.0 | 5 votes |
protected static Exception getException(Message message) { Exception ex = null; if (message != null) { ex = message.getContent(Exception.class); } return ex; }
Example 5
Source File: ClientFaultConverter.java From cxf with Apache License 2.0 | 5 votes |
private void setStackTrace(Fault fault, Message msg) { Throwable cause = null; Map<String, String> ns = new HashMap<>(); XPathUtils xu = new XPathUtils(ns); ns.put("s", Fault.STACKTRACE_NAMESPACE); String ss = (String) xu.getValue("//s:" + Fault.STACKTRACE + "/text()", fault.getDetail(), XPathConstants.STRING); List<StackTraceElement> stackTraceList = new ArrayList<>(); if (!StringUtils.isEmpty(ss)) { Iterator<String> linesIterator = Arrays.asList(CAUSE_SUFFIX_SPLITTER.split(ss)).iterator(); while (linesIterator.hasNext()) { String oneLine = linesIterator.next(); if (oneLine.startsWith("Caused by:")) { cause = getCause(linesIterator, oneLine); break; } stackTraceList.add(parseStackTrackLine(oneLine)); } if (!stackTraceList.isEmpty() || cause != null) { Exception e = msg.getContent(Exception.class); if (!stackTraceList.isEmpty()) { StackTraceElement[] stackTraceElement = new StackTraceElement[stackTraceList.size()]; e.setStackTrace(stackTraceList.toArray(stackTraceElement)); } else if (cause != null && cause.getMessage() != null && cause.getMessage().startsWith(e.getClass().getName())) { e.setStackTrace(cause.getStackTrace()); if (cause.getCause() != null) { e.initCause(cause.getCause()); } } else if (cause != null) { e.initCause(cause); } } } }
Example 6
Source File: MetricsMessageClientOutInterceptor.java From cxf with Apache License 2.0 | 5 votes |
public void handleFault(Message message) { if (isRequestor(message)) { Exception ex = message.getContent(Exception.class); if (ex != null) { FaultMode fm = message.getExchange().get(FaultMode.class); message.getExchange().put(FaultMode.class, FaultMode.RUNTIME_FAULT); stop(message); message.getExchange().put(FaultMode.class, fm); } else { stop(message); } } }
Example 7
Source File: PersistInInterceptor.java From cxf with Apache License 2.0 | 5 votes |
/** * Copied from LoggingInInterceptor * * @param soapMessage */ private void getSoapRequest(Message soapMessage, ExchangeData exchange) { InputStream is = soapMessage.getContent(InputStream.class); if (is != null) { CachedOutputStream bos = new CachedOutputStream(); try { IOUtils.copy(is, bos); bos.flush(); is.close(); soapMessage.setContent(InputStream.class, bos.getInputStream()); StringBuilder builder = new StringBuilder(); bos.writeCacheTo(builder, bos.size()); bos.close(); exchange.setRequest(builder.toString()); exchange.setRequestSize((int)bos.size()); } catch (IOException e) { throw new Fault(e); } } }
Example 8
Source File: AbstractSamlInHandler.java From cxf with Apache License 2.0 | 5 votes |
/** * Check the sender-vouches requirements against the received assertion. The SAML * Assertion and the request body must be signed by the same signature. */ protected boolean checkSenderVouches( Message message, SamlAssertionWrapper assertionWrapper, Certificate[] tlsCerts ) { // // If we have a 2-way TLS connection, then we don't have to check that the // assertion + body are signed // If no body is available (ex, with GET) then consider validating that // the base64-encoded token is signed by the same signature // if (tlsCerts != null && tlsCerts.length > 0) { return true; } List<String> confirmationMethods = assertionWrapper.getConfirmationMethods(); for (String confirmationMethod : confirmationMethods) { if (OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) { Element signedElement = message.getContent(Element.class); Node assertionParent = assertionWrapper.getElement().getParentNode(); // if we have a shared parent signed node then we can assume both // this SAML assertion and the main payload have been signed by the same // signature if (assertionParent != signedElement) { // if not then try to compare if the same cert/key was used to sign SAML token // and the payload SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSignatureKeyInfo(); if (!compareCredentials(subjectKeyInfo, message, tlsCerts)) { return false; } } } } return true; }
Example 9
Source File: ProtobufMessageOutInterceptor.java From fuchsia with Apache License 2.0 | 5 votes |
/** * @see org.apache.cxf.interceptor.Interceptor#handleMessage(org.apache.cxf.message.Message). */ public void handleMessage(Message message) throws Fault { OutputStream out = message.getContent(OutputStream.class); try { com.google.protobuf.Message m = (com.google.protobuf.Message) message.getContent(Object.class); if (m != null) { m.writeTo(out); } } catch (Exception e) { throw new RuntimeException(e); } }
Example 10
Source File: StaxOutEndingInterceptor.java From cxf with Apache License 2.0 | 5 votes |
public void handleMessage(Message message) { try { XMLStreamWriter xtw = message.getContent(XMLStreamWriter.class); if (xtw != null) { try { xtw.writeEndDocument(); xtw.flush(); } finally { StaxUtils.close(xtw); } } OutputStream os = (OutputStream)message.get(outStreamHolder); if (os != null) { message.setContent(OutputStream.class, os); } if (writerHolder != null) { Writer w = (Writer)message.get(writerHolder); if (w != null) { message.setContent(Writer.class, w); } } message.removeContent(XMLStreamWriter.class); } catch (XMLStreamException e) { throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_WRITE_EXC", BUNDLE), e); } }
Example 11
Source File: OAuthInvoker.java From cxf with Apache License 2.0 | 5 votes |
@Override protected Object performInvocation(Exchange exchange, final Object serviceObject, Method m, Object[] paramArray) throws Exception { Message inMessage = exchange.getInMessage(); ClientTokenContext tokenContext = inMessage.getContent(ClientTokenContext.class); try { if (tokenContext != null) { StaticClientTokenContext.setClientTokenContext(tokenContext); } return super.performInvocation(exchange, serviceObject, m, paramArray); } catch (InvocationTargetException ex) { if (tokenContext != null && ex.getCause() instanceof NotAuthorizedException && !inMessage.containsKey(OAUTH2_CALL_RETRIED)) { ClientAccessToken accessToken = tokenContext.getToken(); String refreshToken = accessToken.getRefreshToken(); if (refreshToken != null) { accessToken = OAuthClientUtils.refreshAccessToken(accessTokenServiceClient, consumer, accessToken); validateRefreshedToken(tokenContext, accessToken); MessageContext mc = new MessageContextImpl(inMessage); ((ClientTokenContextImpl)tokenContext).setToken(accessToken); clientTokenContextManager.setClientTokenContext(mc, tokenContext); //retry inMessage.put(OAUTH2_CALL_RETRIED, true); return super.performInvocation(exchange, serviceObject, m, paramArray); } } throw ex; } finally { if (tokenContext != null) { StaticClientTokenContext.removeClientTokenContext(); } } }
Example 12
Source File: RMCaptureInInterceptor.java From cxf with Apache License 2.0 | 5 votes |
public void handleMessage(Message message) { LOG.entering(getClass().getName(), "handleMessage"); // Capturing the soap envelope. In case of WSS was activated, decrypted envelope is captured. if (!MessageUtils.getContextualBoolean(message, Message.ROBUST_ONEWAY, false) && isApplicationMessage(message) && (getManager().getStore() != null || (getManager().getDestinationPolicy() != null && getManager() .getDestinationPolicy().getRetryPolicy() != null))) { CachedOutputStream saved = new CachedOutputStream(); SOAPMessage soapMessage = message.getContent(SOAPMessage.class); if (soapMessage != null) { try { javax.xml.transform.Source envelope = soapMessage.getSOAPPart().getContent(); StaxUtils.copy(envelope, saved); saved.flush(); // create a new source part from cos InputStream is = saved.getInputStream(); // close old saved content closeOldSavedContent(message); // keep References to clean-up tmp files in RMDeliveryInterceptor setCloseable(message, saved, is); StreamSource source = new StreamSource(is); soapMessage.getSOAPPart().setContent(source); // when WSS was activated, saved content still contains soap headers to be removed message.put(RMMessageConstants.SAVED_CONTENT, removeUnnecessarySoapHeaders(saved)); } catch (SOAPException | IOException | XMLStreamException e) { throw new Fault(e); } } } }
Example 13
Source File: JavascriptGetInterceptor.java From cxf with Apache License 2.0 | 5 votes |
public void handleMessage(Message message) throws Fault { String method = (String)message.get(Message.HTTP_REQUEST_METHOD); String query = (String)message.get(Message.QUERY_STRING); if (!"GET".equals(method) || StringUtils.isEmpty(query)) { return; } String baseUri = (String)message.get(Message.REQUEST_URL); URI uri = null; try { uri = URI.create(baseUri); } catch (IllegalArgumentException iae) { //invalid URI, ignore and continue return; } Map<String, String> map = UrlUtils.parseQueryString(query); if (isRecognizedQuery(map, uri, message.getExchange().getEndpoint().getEndpointInfo())) { try { Conduit c = message.getExchange().getDestination().getBackChannel(message); Message mout = new MessageImpl(); mout.setExchange(message.getExchange()); message.getExchange().setOutMessage(mout); mout.put(Message.CONTENT_TYPE, "application/javascript;charset=UTF-8"); c.prepare(mout); OutputStream os = mout.getContent(OutputStream.class); writeResponse(uri, map, os, message.getExchange().getEndpoint()); } catch (IOException ioe) { throw new Fault(ioe); } } }
Example 14
Source File: BasicAuthInterceptor.java From geofence with GNU General Public License v2.0 | 4 votes |
private void close(Message outMessage) throws IOException { OutputStream os = outMessage.getContent(OutputStream.class); os.flush(); os.close(); }
Example 15
Source File: AbstractOutDatabindingInterceptor.java From cxf with Apache License 2.0 | 4 votes |
protected XMLStreamWriter getXMLStreamWriter(Message message) { return message.getContent(XMLStreamWriter.class); }
Example 16
Source File: AttachmentOutInterceptor.java From cxf with Apache License 2.0 | 4 votes |
public void handleMessage(Message message) { //avoid AttachmentOutInterceptor invoked twice on the //same message if (message.get(ATTACHMENT_OUT_CHECKED) != null && (boolean)message.get(ATTACHMENT_OUT_CHECKED)) { return; } else { message.put(ATTACHMENT_OUT_CHECKED, Boolean.TRUE); } // Make it possible to step into this process in spite of Eclipse // by declaring the Object. boolean mtomEnabled = AttachmentUtil.isMtomEnabled(message); boolean writeAtts = MessageUtils.getContextualBoolean(message, WRITE_ATTACHMENTS, false) || (message.getAttachments() != null && !message.getAttachments().isEmpty()); if (!mtomEnabled && !writeAtts) { return; } if (message.getContent(OutputStream.class) == null) { return; } AttachmentSerializer serializer = new AttachmentSerializer(message, getMultipartType(), writeOptionalTypeParameters(), getRootHeaders()); serializer.setXop(mtomEnabled); String contentTransferEncoding = (String)message.getContextualProperty( org.apache.cxf.message.Message.CONTENT_TRANSFER_ENCODING); if (contentTransferEncoding != null) { serializer.setContentTransferEncoding(contentTransferEncoding); } try { serializer.writeProlog(); } catch (IOException e) { throw new Fault(new org.apache.cxf.common.i18n.Message("WRITE_ATTACHMENTS", BUNDLE), e); } message.setContent(AttachmentSerializer.class, serializer); // Add a final interceptor to write attachements message.getInterceptorChain().add(ending); }
Example 17
Source File: DocLiteralInInterceptorTest.java From cxf with Apache License 2.0 | 4 votes |
@Test public void testUnmarshalSourceDataWrapped() throws Exception { XMLStreamReader reader = StaxUtils.createXMLStreamReader(getClass() .getResourceAsStream("resources/docLitWrappedReq.xml")); assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag()); XMLStreamReader filteredReader = new PartialXMLStreamReader(reader, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body")); // advance the xml reader to the message parts StaxUtils.read(filteredReader); assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag()); Message m = new MessageImpl(); // request to keep the document as wrapped m.put(DocLiteralInInterceptor.KEEP_PARAMETERS_WRAPPER, true); Exchange exchange = new ExchangeImpl(); Service service = control.createMock(Service.class); exchange.put(Service.class, service); EasyMock.expect(service.getDataBinding()).andReturn(new SourceDataBinding()).anyTimes(); EasyMock.expect(service.size()).andReturn(0).anyTimes(); EasyMock.expect(service.isEmpty()).andReturn(true).anyTimes(); Endpoint endpoint = control.createMock(Endpoint.class); exchange.put(Endpoint.class, endpoint); // wrapped OperationInfo operationInfo = new OperationInfo(); MessageInfo messageInfo = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo")); messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "personId"), null)); messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "ssn"), null)); messageInfo.getMessagePart(0).setConcreteName(new QName(NS, "personId")); messageInfo.getMessagePart(1).setConcreteName(new QName(NS, "ssn")); operationInfo.setInput("inputName", messageInfo); // wrapper OperationInfo operationInfoWrapper = new OperationInfo(); MessageInfo messageInfoWrapper = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo")); messageInfoWrapper.addMessagePart(new MessagePartInfo(new QName(NS, "GetPerson"), null)); messageInfoWrapper.getMessagePart(0).setConcreteName(new QName(NS, "GetPerson")); operationInfoWrapper.setInput("inputName", messageInfoWrapper); operationInfoWrapper.setUnwrappedOperation(operationInfo); ServiceInfo serviceInfo = control.createMock(ServiceInfo.class); EasyMock.expect(serviceInfo.getName()).andReturn(new QName("http://foo.com", "service")).anyTimes(); InterfaceInfo interfaceInfo = control.createMock(InterfaceInfo.class); EasyMock.expect(serviceInfo.getInterface()).andReturn(interfaceInfo).anyTimes(); EasyMock.expect(interfaceInfo.getName()).andReturn(new QName("http://foo.com", "interface")) .anyTimes(); BindingInfo bindingInfo = new BindingInfo(serviceInfo, ""); BindingOperationInfo boi = new BindingOperationInfo(bindingInfo, operationInfoWrapper); exchange.put(BindingOperationInfo.class, boi); EndpointInfo endpointInfo = control.createMock(EndpointInfo.class); BindingInfo binding = control.createMock(BindingInfo.class); EasyMock.expect(endpoint.getEndpointInfo()).andReturn(endpointInfo).anyTimes(); EasyMock.expect(endpointInfo.getBinding()).andReturn(binding).anyTimes(); EasyMock.expect(binding.getProperties()).andReturn(new HashMap<String, Object>()).anyTimes(); EasyMock.expect(endpointInfo.getProperties()).andReturn(new HashMap<String, Object>()).anyTimes(); EasyMock.expect(endpoint.size()).andReturn(0).anyTimes(); EasyMock.expect(endpoint.isEmpty()).andReturn(true).anyTimes(); EasyMock.expect(endpointInfo.getService()).andReturn(serviceInfo).anyTimes(); EasyMock.expect(endpointInfo.getName()).andReturn(new QName("http://foo.com", "endpoint")).anyTimes(); EasyMock.expect(endpointInfo.getProperty("URI", URI.class)).andReturn(new URI("dummy")).anyTimes(); List<OperationInfo> operations = new ArrayList<>(); EasyMock.expect(interfaceInfo.getOperations()).andReturn(operations).anyTimes(); m.setExchange(exchange); m.put(Message.SCHEMA_VALIDATION_ENABLED, false); m.setContent(XMLStreamReader.class, reader); control.replay(); new DocLiteralInInterceptor().handleMessage(m); MessageContentsList params = (MessageContentsList)m.getContent(List.class); // we expect a wrapped document assertEquals(1, params.size()); Map<String, String> ns = new HashMap<>(); ns.put("ns", NS); XPathUtils xu = new XPathUtils(ns); assertEquals("hello", xu.getValueString("//ns:GetPerson/ns:personId", ((DOMSource)params.get(0)).getNode().getFirstChild())); assertEquals("1234", xu.getValueString("//ns:GetPerson/ns:ssn", ((DOMSource)params.get(0)).getNode().getFirstChild())); }
Example 18
Source File: RPCOutInterceptor.java From cxf with Apache License 2.0 | 4 votes |
protected XMLStreamWriter getXMLStreamWriter(Message message) { return message.getContent(XMLStreamWriter.class); }
Example 19
Source File: MessageContentUtil.java From peer-os with Apache License 2.0 | 4 votes |
public static void encryptContent( SecurityManager securityManager, String hostIdSource, String hostIdTarget, Message message ) { OutputStream os = message.getContent( OutputStream.class ); CachedStream cs = new CachedStream(); message.setContent( OutputStream.class, cs ); message.getInterceptorChain().doIntercept( message ); LOG.debug( String.format( "Encrypting IDs: %s -> %s", hostIdSource, hostIdTarget ) ); try { cs.flush(); CachedOutputStream csnew = ( CachedOutputStream ) message.getContent( OutputStream.class ); byte[] originalMessage = org.apache.commons.io.IOUtils.toByteArray( csnew.getInputStream() ); LOG.debug( String.format( "Original payload: \"%s\"", new String( originalMessage ) ) ); csnew.flush(); org.apache.commons.io.IOUtils.closeQuietly( cs ); org.apache.commons.io.IOUtils.closeQuietly( csnew ); //do something with original message to produce finalMessage byte[] finalMessage = originalMessage.length > 0 ? encryptData( securityManager, hostIdTarget, originalMessage ) : null; if ( !ArrayUtils.isEmpty( finalMessage ) ) { InputStream replaceInStream = new ByteArrayInputStream( finalMessage ); org.apache.commons.io.IOUtils.copy( replaceInStream, os ); replaceInStream.close(); org.apache.commons.io.IOUtils.closeQuietly( replaceInStream ); os.flush(); message.setContent( OutputStream.class, os ); } org.apache.commons.io.IOUtils.closeQuietly( os ); } catch ( Exception ioe ) { throw new ActionFailedException( "Error encrypting content", ioe ); } }
Example 20
Source File: XMLMessageInInterceptor.java From cxf with Apache License 2.0 | 4 votes |
public void handleMessage(Message message) throws Fault { if (isGET(message)) { LOG.fine("XMLMessageInInterceptor skipped in HTTP GET method"); return; } Endpoint ep = message.getExchange().getEndpoint(); XMLStreamReader xsr = message.getContent(XMLStreamReader.class); if (xsr == null) { return; } DepthXMLStreamReader reader = new DepthXMLStreamReader(xsr); if (!StaxUtils.toNextElement(reader)) { throw new Fault(new org.apache.cxf.common.i18n.Message("NO_OPERATION_ELEMENT", LOG)); } Exchange ex = message.getExchange(); QName startQName = reader.getName(); // handling xml fault message if (startQName.getLocalPart().equals(XMLFault.XML_FAULT_ROOT)) { message.getInterceptorChain().abort(); if (ep.getInFaultObserver() != null) { ep.getInFaultObserver().onMessage(message); return; } } // handling xml normal inbound message BindingOperationInfo boi = ex.getBindingOperationInfo(); boolean isRequestor = isRequestor(message); if (boi == null) { BindingInfo service = ep.getEndpointInfo().getBinding(); boi = getBindingOperationInfo(isRequestor, startQName, service, xsr); if (boi != null) { ex.put(BindingOperationInfo.class, boi); ex.setOneWay(boi.getOperationInfo().isOneWay()); } } else { BindingMessageInfo bmi = isRequestor ? boi.getOutput() : boi.getInput(); if (hasRootNode(bmi, startQName)) { try { xsr.nextTag(); } catch (XMLStreamException xse) { throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_READ_EXC", LOG)); } } } }