Java Code Examples for org.apache.cxf.message.message#setContent()

The following examples show how to use org.apache.cxf.message.message#setContent() . 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: LoggingOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    if (isLoggingDisabledNow(message)) {
        return;
    }
    createExchangeId(message);
    final OutputStream os = message.getContent(OutputStream.class);
    if (os != null) {
        LoggingCallback callback = new LoggingCallback(sender, message, os, limit);
        message.setContent(OutputStream.class, createCachingOut(message, os, callback));
    } else {
        final Writer iowriter = message.getContent(Writer.class);
        if (iowriter != null) {
            message.setContent(Writer.class, new LogEventSendingWriter(sender, message, iowriter, limit));
        }
    }
}
 
Example 2
Source File: TransformTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: DepthRestrictingStreamInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) {

        if (canBeIgnored(message)) {
            return;
        }

        XMLStreamReader reader = message.getContent(XMLStreamReader.class);
        if (reader == null) {
            InputStream is = message.getContent(InputStream.class);
            if (is != null) {
                reader = StaxUtils.createXMLStreamReader(is);
                message.setContent(InputStream.class, null);
            }
            if (reader == null) {
                return;
            }
        }
        DepthRestrictingStreamReader dr =
            new DepthRestrictingStreamReader(reader,
                                             elementCountThreshold,
                                             innerElementLevelThreshold,
                                             innerElementCountThreshold);
        message.setContent(XMLStreamReader.class, dr);
    }
 
Example 4
Source File: AbstractXmlSecOutInterceptor.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(Throwable.class) != null) {
        return;
    }
    try {
        Document doc = getDomDocument(message);
        if (doc == null) {
            return;
        }
        Document finalDoc = processDocument(message, doc);

        message.setContent(List.class,
            new MessageContentsList(new DOMSource(finalDoc)));
    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }
}
 
Example 5
Source File: RetransmissionInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
void handle(Message message, boolean isFault) {
    if (null == getManager().getRetransmissionQueue()) {
        return;
    }

    OutputStream os = message.getContent(OutputStream.class);
    if (null == os) {
        return;
    }
    if (isFault) {
        RetryPolicyType rmrp = null != manager.getSourcePolicy()
            ? manager.getSourcePolicy().getRetryPolicy() : null;
        int maxRetries = null != rmrp ? rmrp.getMaxRetries() : -1;
        if (maxRetries != 0) {
            // remove the exception set by the PhaseInterceptorChain so that the
            // error does not reach the client when retransmission is scheduled
            message.setContent(Exception.class, null);
            message.getExchange().put(Exception.class, null);
        }

    }
}
 
Example 6
Source File: UDPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc}*/
@Override
protected Conduit getInbuiltBackChannel(final Message inMessage) {
    if (inMessage.getExchange().isOneWay()) {
        return null;
    }
    return new AbstractBackChannelConduit() {
        public void prepare(Message message) throws IOException {
            message.setContent(OutputStream.class, inMessage.get(OutputStream.class));
        }
    };
}
 
Example 7
Source File: MetricsMessageClientOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    if (isRequestor(message)) {
        ExchangeMetrics ctx = getExchangeMetrics(message, true);
        InputStream in = message.getContent(InputStream.class);
        if (in != null) {
            CountingInputStream newIn = new CountingInputStream(in);
            message.setContent(InputStream.class, newIn);
            message.getExchange().put(CountingInputStream.class, newIn);
        }
        addOperationMetrics(ctx, message, message.getExchange().getBindingOperationInfo());
        ctx.start();
    }
}
 
Example 8
Source File: XmlStreamReaderProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void filter(ContainerRequestContext c) throws IOException {
    String method = context.get(Message.HTTP_REQUEST_METHOD).toString();

    if ("PUT".equals(method)) {
        MultivaluedMap<String, String> map = context.getUriInfo().getPathParameters();
        if (!"123".equals(map.getFirst("id"))) {
            throw new RuntimeException();
        }
        Message m = JAXRSUtils.getCurrentMessage();
        XMLStreamReader reader =
            StaxUtils.createXMLStreamReader(m.getContent(InputStream.class));
        m.setContent(XMLStreamReader.class,
                                                  new CustomXmlStreamReader(reader));
    }
}
 
Example 9
Source File: XmlSecInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void prepareMessage(Message inMsg) throws Fault {

        XMLStreamReader originalXmlStreamReader = inMsg.getContent(XMLStreamReader.class);
        if (originalXmlStreamReader == null) {
            InputStream is = inMsg.getContent(InputStream.class);
            if (is != null) {
                originalXmlStreamReader = StaxUtils.createXMLStreamReader(is);
            }
        }

        try {
            XMLSecurityProperties properties = new XMLSecurityProperties();
            configureDecryptionKeys(inMsg, properties);
            Crypto signatureCrypto = getSignatureCrypto(inMsg);
            configureSignatureKeys(signatureCrypto, inMsg, properties);

            SecurityEventListener securityEventListener =
                configureSecurityEventListener(signatureCrypto, inMsg, properties);
            InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);

            XMLStreamReader newXmlStreamReader =
                inboundXMLSec.processInMessage(originalXmlStreamReader, null, securityEventListener);
            inMsg.setContent(XMLStreamReader.class, newXmlStreamReader);

        } catch (XMLStreamException | XMLSecurityException | IOException | UnsupportedCallbackException e) {
            throwFault(e.getMessage(), e);
        }
    }
 
Example 10
Source File: FormUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void restoreForm(FormEncodingProvider<Form> provider,
                               Form form,
                               Message message)
    throws Exception {
    CachedOutputStream os = new CachedOutputStream();
    writeForm(provider, form, os);
    message.setContent(InputStream.class, os.getInputStream());
}
 
Example 11
Source File: ColocUtil.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void convertSourceToObject(Message message) {
    List<Object> content = CastUtils.cast(message.getContent(List.class));
    if (content == null || content.isEmpty()) {
        // nothing to convert
        return;
    }
    // only supporting the wrapped style for now  (one pojo <-> one source)
    Source source = (Source)content.get(0);
    DataReader<XMLStreamReader> reader =
        message.getExchange().getService().getDataBinding().createReader(XMLStreamReader.class);
    MessagePartInfo mpi = getMessageInfo(message).getMessagePart(0);
    XMLStreamReader streamReader = null;
    Object wrappedObject = null;
    try {
        streamReader = StaxUtils.createXMLStreamReader(source);
        wrappedObject = reader.read(mpi, streamReader);
    } finally {
        try {
            StaxUtils.close(streamReader);
        } catch (XMLStreamException e) {
            // Ignore
        }
    }
    MessageContentsList parameters = new MessageContentsList();
    parameters.put(mpi, wrappedObject);

    message.setContent(List.class, parameters);
}
 
Example 12
Source File: FailoverTargetSelector.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean performFailover(Exchange exchange, InvocationContext invocation) {
    Exception prevExchangeFault = (Exception)exchange.remove(Exception.class.getName());
    Message outMessage = exchange.getOutMessage();
    Exception prevMessageFault = outMessage.getContent(Exception.class);
    outMessage.setContent(Exception.class, null);
    overrideAddressProperty(invocation.getContext());

    Retryable retry = exchange.get(Retryable.class);
    exchange.clear();
    boolean failover = false;
    if (retry != null) {
        try {
            failover = true;
            long delay = getDelayBetweenRetries();
            if (delay > 0) {
                Thread.sleep(delay);
            }
            retry.invoke(invocation.getBindingOperationInfo(),
                         invocation.getParams(),
                         invocation.getContext(),
                         exchange);
        } catch (Exception e) {
            if (exchange.get(Exception.class) != null) {
                exchange.put(Exception.class, prevExchangeFault);
            }
            if (outMessage.getContent(Exception.class) != null) {
                outMessage.setContent(Exception.class,
                                      prevMessageFault);
            }
        }
    }
    return failover;
}
 
Example 13
Source File: JsonpInterceptorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonWithoutPadding() throws Exception {
    Message message = new MessageImpl();
    message.put(Message.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    message.setExchange(new ExchangeImpl());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    message.setContent(OutputStream.class, bos);

    // Process the message
    in.handleMessage(message);
    preStream.handleMessage(message);
    postStream.handleMessage(message);
    assertEquals("", bos.toString());
}
 
Example 14
Source File: XMLFaultInterceptorsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) {

            try {
                ByteArrayOutputStream baos = (ByteArrayOutputStream) message.getContent(OutputStream.class);
                ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
                message.setContent(InputStream.class, bis);
                XMLStreamReader xsr = StaxUtils.createXMLStreamReader(bis);
                xsr.nextTag();
                message.setContent(XMLStreamReader.class, xsr);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
 
Example 15
Source File: AttachmentDeserializerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testCXF3582b() throws Exception {
    String contentType = "multipart/related; type=\"application/xop+xml\"; "
        + "boundary=\"uuid:906fa67b-85f9-4ef5-8e3d-52416022d463\"; "
        + "start=\"<[email protected]>\"; start-info=\"text/xml\"";


    Message message = new MessageImpl();
    message.put(Message.CONTENT_TYPE, contentType);
    message.setContent(InputStream.class, getClass().getResourceAsStream("cxf3582.data"));
    message.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY, System
            .getProperty("java.io.tmpdir"));
    message.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD, String
            .valueOf(AttachmentDeserializer.THRESHOLD));


    AttachmentDeserializer ad
        = new AttachmentDeserializer(message,
                                     Collections.singletonList("multipart/related"));

    ad.initializeAttachments();

    String cid = "[email protected]";
    DataSource ds = AttachmentUtil.getAttachmentDataSource(cid, message.getAttachments());
    byte[] bts = new byte[1024];
    InputStream ins = ds.getInputStream();
    int count = 0;
    int x = ins.read(bts, 500, 200);
    while (x != -1) {
        count += x;
        x = ins.read(bts, 500, 200);
    }
    assertEquals(500, count);
    assertEquals(-1, ins.read(new byte[1000], 500, 500));

    ins.close();

    cid = "[email protected]";
    ds = AttachmentUtil.getAttachmentDataSource(cid, message.getAttachments());
    bts = new byte[1024];
    ins = ds.getInputStream();
    count = 0;
    x = ins.read(bts, 500, 200);
    while (x != -1) {
        count += x;
        x = ins.read(bts, 500, 200);
    }
    assertEquals(1249, count);
    assertEquals(-1, ins.read(new byte[1000], 500, 500));
    ins.close();
}
 
Example 16
Source File: AbstractClient.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected Message createMessage(Object body,
                                String httpMethod,
                                MultivaluedMap<String, String> headers,
                                URI currentURI,
                                Exchange exchange,
                                Map<String, Object> invocationContext,
                                boolean proxy) {
    checkClosed();
    Message m = cfg.getConduitSelector().getEndpoint().getBinding().createMessage();
    m.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
    m.put(Message.INBOUND_MESSAGE, Boolean.FALSE);

    setRequestMethod(m, 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());
    }

    String ct = headers.getFirst(HttpHeaders.CONTENT_TYPE);
    m.put(Message.CONTENT_TYPE, ct);

    body = checkIfBodyEmpty(body, ct);
    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;
}
 
Example 17
Source File: GiornaleEventiCollectorOutInterceptor.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
	String url = null;
	String httpMethodS = null;
	String principal = null;
	Esito esito = null;
	try {
		if(this.giornaleEventiConfig.isAbilitaGiornaleEventi()) {
			boolean logEvento = false;
			boolean dumpEvento = false;
			IContext context = ContextThreadLocal.get();
			GpContext appContext = (GpContext) context.getApplicationContext();
			EventoContext eventoCtx = appContext.getEventoCtx();

			Exchange exchange = message.getExchange();

			Message inMessage = exchange.getInMessage();
			final LogEvent eventRequest = new DefaultLogEventMapper().map(inMessage);
			url = eventoCtx.getUrl() != null ? eventoCtx.getUrl() : eventRequest.getAddress();
			httpMethodS = eventoCtx.getMethod() != null ? eventoCtx.getMethod() : eventRequest.getHttpMethod();
			principal = eventoCtx.getPrincipal()!= null ? eventoCtx.getPrincipal() : eventRequest.getPrincipal();
			
			HttpMethodEnum httpMethod = GiornaleEventiUtilities.getHttpMethod(httpMethodS);
			esito = eventoCtx.getEsito() != null ? eventoCtx.getEsito() : Esito.KO;
			this.log.debug("Log Evento API: ["+this.giornaleEventiConfig.getApiName()+"] Method ["+httpMethodS+"], Url ["+url+"], Esito ["+esito+"]");

			GdeInterfaccia configurazioneInterfaccia = GiornaleEventiUtilities.getConfigurazioneGiornaleEventi(context, this.configurazioneDAO, this.giornaleEventiConfig);

			if(configurazioneInterfaccia != null) {
				this.log.debug("Configurazione Giornale Eventi API: ["+this.giornaleEventiConfig.getApiName()+"]: " + ConverterUtils.toJSON(configurazioneInterfaccia,null));
				
				if(GiornaleEventiUtilities.isRequestLettura(httpMethod, this.giornaleEventiConfig.getApiNameEnum(), eventoCtx.getTipoEvento())) {
					logEvento = GiornaleEventiUtilities.logEvento(configurazioneInterfaccia.getLetture(), esito);
					dumpEvento = GiornaleEventiUtilities.dumpEvento(configurazioneInterfaccia.getLetture(), esito);
					this.log.debug("Tipo Operazione 'Lettura', Log ["+logEvento+"], Dump ["+dumpEvento+"].");
				} else if(GiornaleEventiUtilities.isRequestScrittura(httpMethod, this.giornaleEventiConfig.getApiNameEnum(), eventoCtx.getTipoEvento())) {
					logEvento = GiornaleEventiUtilities.logEvento(configurazioneInterfaccia.getScritture(), esito);
					dumpEvento = GiornaleEventiUtilities.dumpEvento(configurazioneInterfaccia.getScritture(), esito);
					this.log.debug("Tipo Operazione 'Scrittura', Log ["+logEvento+"], Dump ["+dumpEvento+"].");
				} else {
					this.log.debug("Tipo Operazione non riconosciuta, l'evento non verra' salvato.");
				}

				eventoCtx.setRegistraEvento(logEvento);
				if(logEvento) {
					Date dataIngresso = eventoCtx.getDataRichiesta();
					Date dataUscita = new Date();
					// lettura informazioni dalla richiesta
					
					DettaglioRichiesta dettaglioRichiesta = new DettaglioRichiesta();
					
				
					dettaglioRichiesta.setPrincipal(principal);
					dettaglioRichiesta.setUtente(eventoCtx.getUtente());
					dettaglioRichiesta.setUrl(url);
					dettaglioRichiesta.setMethod(httpMethodS);
					dettaglioRichiesta.setDataOraRichiesta(dataIngresso);
					dettaglioRichiesta.setHeadersFromMap(eventRequest.getHeaders());
					
					// lettura informazioni dalla response
					final LogEvent eventResponse = new DefaultLogEventMapper().map(message);
					DettaglioRisposta dettaglioRisposta = new DettaglioRisposta();
					dettaglioRisposta.setHeadersFromMap(eventResponse.getHeaders());
					dettaglioRisposta.setDataOraRisposta(dataUscita);

					eventoCtx.setDataRisposta(dataUscita);
					eventoCtx.setDettaglioRichiesta(dettaglioRichiesta);
					eventoCtx.setDettaglioRisposta(dettaglioRisposta);

					if(dumpEvento) {
						// dump richiesta
						if (shouldLogContent(eventRequest)) {
							GiornaleEventiUtilities.addContent(inMessage, eventRequest, this.giornaleEventiConfig);
						} else {
							eventRequest.setPayload(AbstractLoggingInterceptor.CONTENT_SUPPRESSED);
						}
						if(eventRequest.getPayload() != null)
							dettaglioRichiesta.setPayload(Base64.getEncoder().encodeToString(eventRequest.getPayload().getBytes()));

						// dump risposta
						final OutputStream os = message.getContent(OutputStream.class);
						if (os != null) {
							LoggingCallback callback = new LoggingCallback(this.sender, message, eventoCtx, os, this.limit);
							message.setContent(OutputStream.class, createCachingOut(message, os, callback));
						}
					} 
				}
			} else {
				this.log.warn("La configurazione per l'API ["+this.giornaleEventiConfig.getApiName()+"] non e' corretta, salvataggio evento non eseguito."); 
			}
		}
	} catch (Throwable e) {
		this.log.error(e.getMessage(),e);
	} finally {

	}
}
 
Example 18
Source File: WrapperClassOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    Exchange ex = message.getExchange();
    BindingOperationInfo bop = ex.getBindingOperationInfo();

    MessageInfo messageInfo = message.get(MessageInfo.class);
    if (messageInfo == null || bop == null || !bop.isUnwrapped()) {
        return;
    }

    BindingOperationInfo newbop = bop.getWrappedOperation();
    MessageInfo wrappedMsgInfo;
    if (Boolean.TRUE.equals(message.get(Message.REQUESTOR_ROLE))) {
        wrappedMsgInfo = newbop.getInput().getMessageInfo();
    } else {
        wrappedMsgInfo = newbop.getOutput().getMessageInfo();
    }

    Class<?> wrapped = null;
    if (wrappedMsgInfo.getMessagePartsNumber() > 0) {
        wrapped = wrappedMsgInfo.getFirstMessagePart().getTypeClass();
    }

    if (wrapped != null) {
        MessagePartInfo firstMessagePart = wrappedMsgInfo.getFirstMessagePart();
        MessageContentsList objs = MessageContentsList.getContentsList(message);
        WrapperHelper helper = firstMessagePart.getProperty("WRAPPER_CLASS", WrapperHelper.class);
        if (helper == null) {
            helper = getWrapperHelper(message, messageInfo, wrappedMsgInfo, wrapped, firstMessagePart);
        }
        if (helper == null) {
            return;
        }

        try {
            MessageContentsList newObjs = new MessageContentsList();
            if (ServiceUtils.isSchemaValidationEnabled(SchemaValidationType.OUT, message)
                && helper instanceof AbstractWrapperHelper) {
                ((AbstractWrapperHelper)helper).setValidate(true);
            }
            Object o2 = helper.createWrapperObject(objs);
            newObjs.put(firstMessagePart, o2);

            for (MessagePartInfo p : messageInfo.getMessageParts()) {
                if (Boolean.TRUE.equals(p.getProperty(ReflectionServiceFactoryBean.HEADER))) {
                    MessagePartInfo mpi = wrappedMsgInfo.getMessagePart(p.getName());
                    if (objs.hasValue(p)) {
                        newObjs.put(mpi, objs.get(p));
                    }
                }
            }

            message.setContent(List.class, newObjs);
        } catch (Fault f) {
            throw f;
        } catch (Exception e) {
            throw new Fault(e);
        }

        // we've now wrapped the object, so use the wrapped binding op
        ex.put(BindingOperationInfo.class, newbop);

        if (messageInfo == bop.getOperationInfo().getInput()) {
            message.put(MessageInfo.class, newbop.getOperationInfo().getInput());
            message.put(BindingMessageInfo.class, newbop.getInput());
        } else if (messageInfo == bop.getOperationInfo().getOutput()) {
            message.put(MessageInfo.class, newbop.getOperationInfo().getOutput());
            message.put(BindingMessageInfo.class, newbop.getOutput());
        }
    }
}
 
Example 19
Source File: PersistOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        ExchangeData exchangeData = message.getExchange().getInMessage().getContent(ExchangeData.class);
        if (exchangeData != null) {

            final OutputStream os = message.getContent(OutputStream.class);
            if (os == null) {
                return;
            }

            try {

                Service service = message.getExchange().getService();

                String serviceName = String.valueOf(service.getName());
                OperationInfo opInfo = message.getExchange().getBindingOperationInfo().getOperationInfo();
                String operationName = opInfo == null ? null : opInfo.getName().getLocalPart();

                if (operationName == null) {
                    Object nameProperty = message.getExchange().get("org.apache.cxf.resource.operation.name");
                    if (nameProperty != null) {
                        operationName = "\"" + nameProperty.toString() + "\"";
                    }
                }

                exchangeData.setServiceName(serviceName);
                exchangeData.setOperation(operationName);

                // add all additional properties

                addPropertiesFrom(exchangeData, message.getExchange().getInMessage());
                addPropertiesFrom(exchangeData, message);

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();

            }

            // Write the output while caching it for the log message
            final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(os);
            message.setContent(OutputStream.class, newOut);
            newOut.registerCallback(new PersistOutInterceptorCallback(message, os, exchangeData));

            exchangeData.setOutDate(new Date());

            if (message.getContent(Exception.class) != null) {
                exchangeData.setStatus("ERROR");

                Exception exception = message.getContent(Exception.class);
                StringWriter stringWriter = new StringWriter();
                if (exception.getCause() != null) {
                    exchangeData.setExceptionType(exception.getCause().getClass().getName());
                    exception.getCause().printStackTrace(new PrintWriter(stringWriter));
                } else {
                    exchangeData.setExceptionType(exception.getClass().getName());
                    exception.printStackTrace(new PrintWriter(stringWriter));
                }
                exchangeData.setStackTrace(stringWriter.toString());

            } else {
                exchangeData.setStatus("OK");
            }

        }
    }
 
Example 20
Source File: XSLTOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void transformWriter(Message message, Writer writer) {
    XSLTCachedWriter wrapper = new XSLTCachedWriter(getXSLTTemplate(), writer);
    message.setContent(Writer.class, wrapper);
}