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

The following examples show how to use org.apache.cxf.message.Exchange#getInMessage() . These examples are extracted from open source projects. 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 Project: cxf   File: AbstractConduitSelector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called on completion of the MEP for which the Conduit was required.
 *
 * @param exchange represents the completed MEP
 */
public void complete(Exchange exchange) {
    // Clients expecting explicit InputStream responses
    // will need to keep low level conduits operating on InputStreams open
    // and will be responsible for closing the streams

    if (PropertyUtils.isTrue(exchange.get(KEEP_CONDUIT_ALIVE))) {
        return;
    }
    try {
        if (exchange.getInMessage() != null) {
            Conduit c = exchange.getOutMessage().get(Conduit.class);
            if (c == null) {
                getSelectedConduit(exchange.getInMessage()).close(exchange.getInMessage());
            } else {
                c.close(exchange.getInMessage());
            }
        }
    } catch (IOException e) {
        //IGNORE
    }
}
 
Example 2
@Test
public void testCreateWebServiceContext() {
    Exchange exchange = new ExchangeImpl();
    Message inMessage = new MessageImpl();
    Message outMessage = new MessageImpl();

    inMessage.putAll(message);

    exchange.setInMessage(inMessage);
    exchange.setOutMessage(outMessage);

    MessageContext ctx = new WrappedMessageContext(exchange.getInMessage(), Scope.APPLICATION);

    Object requestHeader = ctx.get(MessageContext.HTTP_REQUEST_HEADERS);
    assertNotNull("the request header should not be null", requestHeader);
    assertEquals("we should get the request header", requestHeader, HEADER);
    Object responseHeader = ctx.get(MessageContext.HTTP_RESPONSE_HEADERS);
    assertNull("the response header should be null", responseHeader);
    Object outMessageHeader = outMessage.get(Message.PROTOCOL_HEADERS);
    assertEquals("the outMessage PROTOCOL_HEADERS should be update", responseHeader, outMessageHeader);

    Object inAttachments = ctx.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
    assertNotNull("inbound attachments object must be initialized", inAttachments);
    assertTrue("inbound attachments must be in a Map", inAttachments instanceof Map);
    assertTrue("no inbound attachments expected", ((Map<?, ?>)inAttachments).isEmpty());
}
 
Example 3
Source Project: cxf   File: JMSDestination.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Rethrow exceptions for one way exchanges so the jms transaction can be rolled back.
 * Do not roll back for request/reply as client might expect a response
 */
private void processExceptions(Exchange exchange) {
    if (!exchange.isOneWay()) {

        return;
    }
    Message inMessage = exchange.getInMessage();
    if (inMessage == null) {
        return;
    }
    Exception ex = inMessage.getContent(Exception.class);

    if (ex != null) {
        if (ex.getCause() instanceof RuntimeException) {
            throw (RuntimeException)ex.getCause();
        }
        throw new RuntimeException(ex);
    }
}
 
Example 4
Source Project: fuchsia   File: ExchangeUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void closeConduit(Exchange exchange) throws IOException {
    ConduitSelector conduitSelector = null;
    synchronized (exchange) {
        conduitSelector = exchange.get(ConduitSelector.class);
        if (conduitSelector != null) {
            exchange.remove(ConduitSelector.class.getName());
        }
    }

    Conduit selectedConduit = null;
    Message message = exchange.getInMessage() == null ? exchange
            .getOutMessage() : exchange.getInMessage();

    if (conduitSelector != null && message != null) {
        selectedConduit = conduitSelector.selectConduit(message);
        selectedConduit.close(message);
    }

    //TODO the line below was removed, check the impact on the protobuffer importer/exporter
    //selectedConduit.close(message);
}
 
Example 5
Source Project: cxf   File: PreexistingConduitSelector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Called on completion of the MEP for which the Conduit was required.
 *
 * @param exchange represents the completed MEP
 */
public void complete(Exchange exchange) {
    try {
        if (exchange.getInMessage() != null) {
            selectedConduit.close(exchange.getInMessage());
        }
    } catch (IOException e) {
        //IGNORE
    }
}
 
Example 6
@Test
public void testCreateWebServiceContextWithInAttachments() {
    Exchange exchange = new ExchangeImpl();
    Message inMessage = new MessageImpl();

    Collection<Attachment> attachments = new LinkedList<>();

    DataSource source = new ByteDataSource(new byte[0], "text/xml");

    DataHandler handler1 = new DataHandler(source);
    attachments.add(new AttachmentImpl("part1", handler1));
    DataHandler handler2 = new DataHandler(source);
    attachments.add(new AttachmentImpl("part2", handler2));
    inMessage.setAttachments(attachments);

    inMessage.putAll(message);
    exchange.setInMessage(inMessage);
    exchange.setOutMessage(new MessageImpl());

    MessageContext ctx = new WrappedMessageContext(exchange.getInMessage(), Scope.APPLICATION);

    Object inAttachments = ctx.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
    assertNotNull("inbound attachments object must be initialized", inAttachments);
    assertTrue("inbound attachments must be in a Map", inAttachments instanceof Map);
    Map<String, DataHandler> dataHandlers = CastUtils.cast((Map<?, ?>)inAttachments);
    assertEquals("two inbound attachments expected", 2, dataHandlers.size());

    assertTrue("part1 attachment is missing", dataHandlers.containsKey("part1"));
    // should do as it's the same instance
    assertTrue("part1 handler is missing", dataHandlers.get("part1") == handler1);
    assertTrue("part2 attachment is missing", dataHandlers.containsKey("part2"));
    assertTrue("part2 handler is missing", dataHandlers.get("part2") == handler2);
}
 
Example 7
Source Project: cxf   File: JAXRSUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void setMessageContentType(Message message, Response response) {
    if (response != null) {
        Object ct = response.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE);
        if (ct != null) {
            Exchange ex = message.getExchange();
            if (ex.getInMessage() == message) {
                ex.put(Message.CONTENT_TYPE, ct.toString());
            } else {
                message.put(Message.CONTENT_TYPE, ct.toString());
            }
        }
    }

}
 
Example 8
Source Project: cxf   File: WSS4JStaxOutInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private String getEncoding(Message message) {
    Exchange ex = message.getExchange();
    String encoding = (String) message.get(Message.ENCODING);
    if (encoding == null && ex.getInMessage() != null) {
        encoding = (String) ex.getInMessage().get(Message.ENCODING);
        message.put(Message.ENCODING, encoding);
    }

    if (encoding == null) {
        encoding = StandardCharsets.UTF_8.name();
        message.put(Message.ENCODING, encoding);
    }
    return encoding;
}
 
Example 9
Source Project: cxf   File: CodahaleMetricsContext.java    License: Apache License 2.0 5 votes vote down vote up
public void stop(long timeInNS, long inSize, long outSize, Exchange ex) {
    totals.update(timeInNS, TimeUnit.NANOSECONDS);

    if (inSize != -1) {
        incomingData.mark(inSize);
    }
    if (outSize != -1) {
        outgoingData.mark(outSize);
    }
    FaultMode fm = ex.get(FaultMode.class);
    if (fm == null && ex.getOutFaultMessage() != null) {
        fm = ex.getOutFaultMessage().get(FaultMode.class);
    }
    if (fm == null && ex.getInMessage() != null) {
        fm = ex.getInMessage().get(FaultMode.class);
    }
    if (fm != null) {
        switch (fm) {
        case CHECKED_APPLICATION_FAULT:
            checkedApplicationFaults.update(timeInNS,  TimeUnit.NANOSECONDS);
            break;
        case UNCHECKED_APPLICATION_FAULT:
            uncheckedApplicationFaults.update(timeInNS,  TimeUnit.NANOSECONDS);
            break;
        case RUNTIME_FAULT:
            runtimeFaults.update(timeInNS,  TimeUnit.NANOSECONDS);
            break;
        case LOGICAL_RUNTIME_FAULT:
            logicalRuntimeFaults.update(timeInNS,  TimeUnit.NANOSECONDS);
            break;
        default:
        }
    }
    inFlight.dec();
}
 
Example 10
Source Project: cxf   File: OAuthInvoker.java    License: Apache License 2.0 5 votes vote down vote up
@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 11
Source Project: cxf   File: XmlSecOutInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private String getEncoding(Message message) {
    Exchange ex = message.getExchange();
    String encoding = (String) message.get(Message.ENCODING);
    if (encoding == null && ex.getInMessage() != null) {
        encoding = (String) ex.getInMessage().get(Message.ENCODING);
        message.put(Message.ENCODING, encoding);
    }

    if (encoding == null) {
        encoding = StandardCharsets.UTF_8.name();
        message.put(Message.ENCODING, encoding);
    }
    return encoding;
}
 
Example 12
Source Project: tomee   File: PojoInvoker.java    License: Apache License 2.0 5 votes vote down vote up
private ClassLoader getClassLoader(final Exchange exchange) {
    final Message inMessage = exchange.getInMessage();
    if (inMessage == null) {
        return null;
    }
    final OpenEJBPerRequestPojoResourceProvider requestPojoResourceProvider = inMessage.get(OpenEJBPerRequestPojoResourceProvider.class);
    if (requestPojoResourceProvider != null) {
        return requestPojoResourceProvider.getClassLoader();
    }
    return null;
}
 
Example 13
Source Project: cxf   File: AbstractClient.java    License: Apache License 2.0 5 votes vote down vote up
private Integer getResponseCode(Exchange exchange) {
    Integer responseCode = (Integer)exchange.get(Message.RESPONSE_CODE);
    if (responseCode == null && exchange.getInMessage() != null) {
        responseCode = (Integer)exchange.getInMessage().get(Message.RESPONSE_CODE);
    }
    if (responseCode == null && exchange.isOneWay() && !state.getBaseURI().toString().startsWith("http")) {
        responseCode = 202;
    }
    return responseCode;
}
 
Example 14
Source Project: cxf   File: LocalDestination.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void close(Message message) throws IOException {
    // set the pseudo status code if not set (REVISIT add this method in MessageUtils to be reused elsewhere?)
    Integer i = (Integer)message.get(Message.RESPONSE_CODE);
    if (i == null) {
        int code = ((message.getExchange().isOneWay() && !MessageUtils.isPartialResponse(message))
            || MessageUtils.isEmptyPartialResponse(message)) ? 202 : 200;
        message.put(Message.RESPONSE_CODE, code);
    }
    if (Boolean.TRUE.equals(message.getExchange().get(LocalConduit.DIRECT_DISPATCH))) {
        final Exchange exchange = (Exchange)message.getExchange().get(LocalConduit.IN_EXCHANGE);

        MessageImpl copy = new MessageImpl();
        copy.putAll(message);
        message.getContent(OutputStream.class).close();
        CachedOutputStream stream = message.getContent(CachedOutputStream.class);
        message.setContent(OutputStream.class, stream);
        MessageImpl.copyContent(message, copy);
        copy.setContent(InputStream.class, stream.getInputStream());
        stream.releaseTempFileHold();
        if (exchange != null && exchange.getInMessage() == null) {
            exchange.setInMessage(copy);
        }
        conduit.getMessageObserver().onMessage(copy);
        return;
    }

    super.close(message);
}
 
Example 15
Source Project: cxf   File: TransformOutInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private String getEncoding(Message message) {
    Exchange ex = message.getExchange();
    String encoding = (String)message.get(Message.ENCODING);
    if (encoding == null && ex.getInMessage() != null) {
        encoding = (String) ex.getInMessage().get(Message.ENCODING);
        message.put(Message.ENCODING, encoding);
    }

    if (encoding == null) {
        encoding = StandardCharsets.UTF_8.name();
        message.put(Message.ENCODING, encoding);
    }
    return encoding;
}
 
Example 16
Source Project: cxf   File: StaxOutInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private String getEncoding(Message message) {
    Exchange ex = message.getExchange();
    String encoding = (String)message.get(Message.ENCODING);
    if (encoding == null && ex.getInMessage() != null) {
        encoding = (String) ex.getInMessage().get(Message.ENCODING);
        message.put(Message.ENCODING, encoding);
    }

    if (encoding == null) {
        encoding = StandardCharsets.UTF_8.name();
        message.put(Message.ENCODING, encoding);
    }
    return encoding;
}
 
Example 17
@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 Project: cxf   File: JAXRSInvoker.java    License: Apache License 2.0 4 votes vote down vote up
public Object invoke(Exchange exchange, Object request) {
    MessageContentsList responseList = checkExchangeForResponse(exchange);
    if (responseList != null) {
        return responseList;
    }
    AsyncResponse asyncResp = exchange.get(AsyncResponse.class);
    if (asyncResp != null) {
        AsyncResponseImpl asyncImpl = (AsyncResponseImpl)asyncResp;
        asyncImpl.prepareContinuation();
        try {
            asyncImpl.handleTimeout();
            return handleAsyncResponse(exchange, asyncImpl);
        } catch (Throwable t) {
            return handleAsyncFault(exchange, asyncImpl, t);
        }
    }

    ResourceProvider provider = getResourceProvider(exchange);
    Object rootInstance = null;
    Message inMessage = exchange.getInMessage();
    try {
        rootInstance = getServiceObject(exchange);
        Object serviceObject = getActualServiceObject(exchange, rootInstance);

        return invoke(exchange, request, serviceObject);
    } catch (WebApplicationException ex) {
        responseList = checkExchangeForResponse(exchange);
        if (responseList != null) {
            return responseList;
        }
        return handleFault(ex, inMessage);
    } finally {
        boolean suspended = isSuspended(exchange);
        if (suspended || exchange.isOneWay() || inMessage.get(Message.THREAD_CONTEXT_SWITCHED) != null) {
            ServerProviderFactory.clearThreadLocalProxies(inMessage);
        }
        if (suspended || isServiceObjectRequestScope(inMessage)) {
            persistRoots(exchange, rootInstance, provider);
        } else {
            provider.releaseInstance(inMessage, rootInstance);
        }
    }
}
 
Example 19
Source Project: cxf   File: ClientImpl.java    License: Apache License 2.0 4 votes vote down vote up
protected Object[] processResult(Message message,
                               Exchange exchange,
                               BindingOperationInfo oi,
                               Map<String, Object> resContext) throws Exception {
    Exception ex = null;
    // Check to see if there is a Fault from the outgoing chain if it's an out Message
    if (!message.get(Message.INBOUND_MESSAGE).equals(Boolean.TRUE)) {
        ex = message.getContent(Exception.class);
    }
    boolean mepCompleteCalled = false;
    if (ex != null) {
        completeExchange(exchange);
        mepCompleteCalled = true;
        if (message.getContent(Exception.class) != null) {
            throw ex;
        }
    }
    ex = message.getExchange().get(Exception.class);
    if (ex != null) {
        if (!mepCompleteCalled) {
            completeExchange(exchange);
        }
        throw ex;
    }

    //REVISIT
    // - use a protocol neutral no-content marker instead of 202?
    // - move the decoupled destination property name into api
    Integer responseCode = (Integer)exchange.get(Message.RESPONSE_CODE);
    if (null != responseCode && 202 == responseCode) {
        Endpoint ep = exchange.getEndpoint();
        if (null != ep && null != ep.getEndpointInfo() && null == ep.getEndpointInfo().
            getProperty("org.apache.cxf.ws.addressing.MAPAggregator.decoupledDestination")) {
            return null;
        }
    }

    // Wait for a response if we need to
    if (oi != null && !oi.getOperationInfo().isOneWay()) {
        waitResponse(exchange);
    }

    // leave the input stream open for the caller
    Boolean keepConduitAlive = (Boolean)exchange.get(Client.KEEP_CONDUIT_ALIVE);
    if (keepConduitAlive == null || !keepConduitAlive) {
        completeExchange(exchange);
    }

    // Grab the response objects if there are any
    List<Object> resList = null;
    Message inMsg = exchange.getInMessage();
    if (inMsg != null) {
        if (null != resContext) {
            resContext.putAll(inMsg);
            // remove the recursive reference if present
            resContext.remove(Message.INVOCATION_CONTEXT);
            setResponseContext(resContext);
        }
        resList = CastUtils.cast(inMsg.getContent(List.class));
    }

    // check for an incoming fault
    ex = getException(exchange);

    if (ex != null) {
        throw ex;
    }

    if (resList == null   
        && oi != null && !oi.getOperationInfo().isOneWay()) {
        
        BindingOperationInfo boi = oi;
        if (boi.isUnwrapped()) {
            boi = boi.getWrappedOperation();
        }
        if (!boi.getOutput().getMessageParts().isEmpty()) {
            //we were supposed to get some output, but didn't.
            throw new IllegalEmptyResponseException("Response message did not contain proper response data."
                + " Expected: " + boi.getOutput().getMessageParts().get(0).getConcreteName());
        }
    }
    if (resList != null) {
        return resList.toArray();
    }

    return null;
}
 
Example 20
private static void waitForAsyncReply(Exchange exchange) throws InterruptedException {
    for (int count = 0; exchange.getInMessage() == null && count <= 20; count++) {
        Thread.sleep(100L);
    }
}