@Override public void handleMessage(final Exchange exchange) throws HandlerException { _messages.offer(exchange); if (_behavior == null || exchange .getContract() .getProviderOperation() .getExchangePattern() .equals(ExchangePattern.IN_ONLY)) { return; } switch (_behavior) { case FORWARD_IN_TO_OUT: exchange.send(exchange.getMessage().copy()); break; case FORWARD_IN_TO_FAULT: exchange.sendFault(exchange.getMessage().copy()); break; case REPLY_WITH_OUT: exchange.send(exchange.createMessage().setContent(_replyContent)); break; case REPLY_WITH_FAULT: exchange.sendFault(exchange.createMessage().setContent(_replyContent)); break; } }
/** {@inheritDoc} */ @Override public RESTEasyBindingData decompose(Exchange exchange, RESTEasyBindingData target) throws Exception { Object content = exchange.getMessage().getContent(); if (exchange.getState().equals(ExchangeState.FAULT)) { if (content instanceof HandlerException) { HandlerException he = (HandlerException) content; if (he.getCause() instanceof ItemNotFoundException) { throw (Exception) he.getCause(); } if (he.getMessage() != null && he.getMessage().startsWith("SWITCHYARD014014")) { UnauthorizedException ue = new UnauthorizedException("Unauthorized"); throw (Exception) ue; } } } target = super.decompose(exchange, target); if (target.getOperationName().equals("addItem") && (content != null) && (content instanceof Item)) { // Unwrap the parameters target.setParameters(new Object[] {((Item) content).getItemId(), ((Item) content).getName()}); } return target; }
protected static void assertCause(String message, Exchange exchange) { assertEquals(ExchangeState.FAULT, exchange.getState()); HandlerException exception = exchange.getMessage().getContent(HandlerException.class); assertTrue(exception.isWrapper()); assertNotNull("Cause should not be null", exception.getCause()); assertEquals(message, exception.getCause().getMessage()); }
protected static void assertNoCause(String message, Exchange exchange) { assertEquals(ExchangeState.FAULT, exchange.getState()); Exception exception = exchange.getMessage().getContent(Exception.class); assertNotNull("Exception should not be null", exception); assertNull("Cause should be null", exception.getCause()); assertEquals(message, exception.getMessage()); }
@Test public void testMessageIdSetOnSend() { ServiceReference service = _domain.createInOnlyService(new QName("IdTest")); Exchange exchange = service.createExchange(); exchange.send(exchange.createMessage()); Assert.assertNotNull(exchange.getMessage().getContext().getProperty(Exchange.MESSAGE_ID)); }
@Test public void testRelatesToSetOnReply() { ServiceReference service = _domain.createInOutService(new QName("ReplyTest"), new MockHandler().forwardInToOut()); MockHandler replyHandler = new MockHandler(); Exchange exchange = service.createExchange(replyHandler); Message message = exchange.createMessage(); exchange.send(message); String requestId = message.getContext().getPropertyValue(Exchange.MESSAGE_ID); String replyId = exchange.getMessage().getContext().getPropertyValue(Exchange.MESSAGE_ID); String replyRelatesTo = exchange.getMessage().getContext().getPropertyValue(Exchange.RELATES_TO); Assert.assertEquals(requestId, replyRelatesTo); Assert.assertFalse(requestId.equals(replyId)); }
/** {@inheritDoc} */ @Override public StreamableRecordBindingData decompose( Exchange exchange, StreamableRecordBindingData target) throws Exception { Message sourceMessage = exchange.getMessage(); getContextMapper().mapTo(exchange.getContext(), target); final InputStream content = sourceMessage.getContent(InputStream.class); target.getRecord().read(content); return target; }
/** {@inheritDoc} */ @Override public Message compose(StreamableRecordBindingData source, Exchange exchange, boolean create) throws Exception { final org.switchyard.Message message = create ? exchange.createMessage() : exchange.getMessage(); getContextMapper().mapFrom(source, exchange.getContext(message)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); source.getRecord().write(baos); message.setContent(new ByteArrayInputStream(baos.toByteArray())); return message; }
@Test public void handleMessageWithOutputType() throws HandlerException { final Exchange camelExchange = createMockCamelExchange(); final ServiceReference serviceReference = createMockServiceRef(); final org.switchyard.Exchange switchYardExchange = createMockExchangeWithBody(10); final CamelResponseHandler responseHandler = new CamelResponseHandler(camelExchange, serviceReference, _messageComposer); responseHandler.handleMessage(switchYardExchange); assertThat( switchYardExchange.getMessage().getContent(Integer.class), is(equalTo(new Integer(10)))); }
@Test public void testFaultTransformSequence() throws Exception { final QName serviceName = new QName("testFaultTransformSequence"); // Provide the service MockHandler provider = new MockHandler() { @Override public void handleMessage(Exchange exchange) throws HandlerException { Message fault = exchange.createMessage(); fault.setContent(new Exception("testFaultTransformSequence")); exchange.sendFault(fault); } }; InOutOperation providerContract = new InOutOperation( "faultOp", JavaTypes.toMessageType(String.class), // input JavaTypes.toMessageType(String.class), // output JavaTypes.toMessageType(Exception.class)); // fault InOutOperation consumerContract = new InOutOperation( "faultOp", JavaTypes.toMessageType(String.class), // input JavaTypes.toMessageType(String.class), // output JavaTypes.toMessageType(String.class)); // fault _domain.registerService(serviceName, new InOutService(providerContract), provider); _domain.getTransformerRegistry().addTransformer(new ExceptionToStringTransformer()); ServiceReference service = _domain.registerServiceReference(serviceName, new InOutService(consumerContract)); // Consume the service Exchange exchange = service.createExchange(new MockHandler()); exchange.send(exchange.createMessage()); // Make sure the exchange is in fault status Assert.assertEquals(String.class, exchange.getMessage().getContent().getClass()); Assert.assertEquals(exchange.getMessage().getContent(), "testFaultTransformSequence"); }
/** Triggers the 'GreetingService' by sending a HornetQ Mesage to the 'GreetingServiceQueue' */ @Test public void triggerGreetingService() throws Exception { final String payload = "dummy payload"; final MockHandler greetingService = _testKit.registerInOnlyService("GreetingService"); final ClientProducer producer = _mixIn.getClientSession().createProducer("jms.queue.GreetingServiceQueue"); final ClientMessage message = _mixIn.createMessage(payload); producer.send(message); Thread.sleep(1000); final Exchange recievedExchange = greetingService.getMessages().iterator().next(); assertThat(recievedExchange.getMessage().getContent(String.class), is(equalTo(payload))); HornetQUtil.closeClientProducer(producer); }
private org.switchyard.Exchange createMockExchangeWithBody(final Integer payload) { final org.switchyard.Exchange switchYardExchange = mock(org.switchyard.Exchange.class); final org.switchyard.Context switchYardContext = mock(org.switchyard.Context.class); final ExchangeContract exchangeContract = mock(ExchangeContract.class); final InvocationContract invocationContract = mock(InvocationContract.class); final Message message = mock(Message.class); when(message.getContent(Integer.class)).thenReturn(payload); when(switchYardExchange.getContext()).thenReturn(switchYardContext); when(switchYardExchange.getMessage()).thenReturn(message); when(invocationContract.getOutputType()).thenReturn(new QName("java:java.lang.String")); when(exchangeContract.getInvokerInvocationMetaData()).thenReturn(invocationContract); when(switchYardExchange.getContract()).thenReturn(exchangeContract); return switchYardExchange; }
@Override public void handleMessage(Exchange exchange) throws HandlerException { if (exchange.getPattern().equals(ExchangePattern.IN_OUT)) { Message message; Element request = exchange.getMessage().getContent(Element.class); Element name = XMLHelper.getFirstChildElementByName(request, "arg0"); String toWhom = ""; if (name != null) { toWhom = name.getTextContent(); } String response = null; if (toWhom.length() == 0) { message = MessageBuilder.newInstance(FaultMessage.class).buildMessage(); response = "<soap:fault xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + " <faultcode>soap:Server.AppError</faultcode>" + " <faultstring>Invalid name</faultstring>" + " <detail>" + " <message>Looks like you did not specify a name!</message>" + " <errorcode>1000</errorcode>" + " </detail>" + "</soap:fault>"; } else { message = MessageBuilder.newInstance().buildMessage(); response = "<test:sayHelloResponse xmlns:test=\"http://test.ws/\">" + " <return>Hello " + toWhom + "</return>" + "</test:sayHelloResponse>"; } try { Document responseDom = SOAPUtil.parseAsDom(response); message.setContent(responseDom.getDocumentElement()); } catch (Exception e) { // Generate fault } exchange.send(message); } }
/** * Send a message hash to the specified operation. * * @param operationName The operation name. * @param rubyHash The message hash. * @return The response object if an IN_OUT operation was invoked, otherwise null. * @throws Throwable An exception occurred while invoking the target operation. */ public Object send(String operationName, RubyHash rubyHash) throws Throwable { if (operationName == null) { throw new IllegalArgumentException("null 'operationName' argument."); } if (rubyHash == null) { throw new IllegalArgumentException("null 'rubyHash' argument."); } ServiceOperation operation = _serviceReference.getInterface().getOperation(operationName); if (operation == null) { throw new IllegalArgumentException( "Unknown operation name '" + operationName + "' on Service '" + _serviceReference.getName() + "'."); } // Clone the RubyHash to convert it to a normal Map based graph. This makes it possible // to more safely transport the payload data out of the ruby app via a SwitchYard Exchange... Map<String, Object> payload = deepClone(rubyHash); // Create the exchange contract... BaseExchangeContract exchangeContract = new BaseExchangeContract(operation); // Set the input type... exchangeContract .getInvokerInvocationMetaData() .setInputType(JavaService.toMessageType(payload.getClass())); if (operation.getExchangePattern() == ExchangePattern.IN_OUT) { final BlockingQueue<Exchange> responseQueue = new ArrayBlockingQueue<Exchange>(1); AtomicReference<ExchangeHandler> responseExchangeHandler = new AtomicReference<ExchangeHandler>( new ExchangeHandler() { public void handleMessage(Exchange exchange) throws HandlerException { responseQueue.offer(exchange); } public void handleFault(Exchange exchange) { responseQueue.offer(exchange); } }); Exchange exchange = _serviceReference.createExchange(exchangeContract, responseExchangeHandler.get()); Message message = exchange.createMessage().setContent(payload); exchange.send(message); Exchange exchangeOut = null; try { exchangeOut = responseQueue.take(); } catch (InterruptedException e) { throw new SwitchYardException( "Operation '" + operationName + "' on Service '" + _serviceReference.getName() + "' interrupted.", e); } if (exchangeOut.getState() == ExchangeState.OK) { return exchangeOut.getMessage().getContent(); } else { Object failureObj = exchangeOut.getMessage().getContent(); if (failureObj instanceof Throwable) { if (failureObj instanceof InvocationTargetException) { throw ((Throwable) failureObj).getCause(); } else { throw (Throwable) failureObj; } } else { throw new SwitchYardException( "Service invocation failure. Service '" + _serviceReference.getName() + "', operation '" + operationName + "'. Non Throwable failure message payload: " + failureObj); } } } else { Exchange exchange = _serviceReference.createExchange(exchangeContract); Message message = exchange.createMessage().setContent(payload); exchange.send(message); } return null; }
/** {@inheritDoc} */ @Override public void handleMessage(Exchange exchange) throws HandlerException { if (!ExchangePhase.IN.equals(exchange.getPhase())) { return; } Context context = exchange.getContext(); ServiceOperation serviceOperation = exchange.getContract().getServiceOperation(); ProcessActionModel processActionModel = _actionModels.get(serviceOperation.getName()); ProcessActionType processActionType = getProcessActionType(context, processActionModel); Message messageIn = exchange.getMessage(); Long processInstanceId = null; ProcessInstance processInstance = null; switch (processActionType) { case START_PROCESS: if (_processId != null) { Object messageContentIn = messageIn.getContent(); if (messageContentIn != null) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(_messageContentInName, messageContentIn); processInstance = _ksession.startProcess(_processId, parameters); } else { processInstance = _ksession.startProcess(_processId); } processInstanceId = Long.valueOf(processInstance.getId()); } else { throwNullParameterException(processActionType, PROCESS_ID_VAR); } break; case SIGNAL_EVENT: String processEventType = getProcessEventType(context, processActionModel); Object processEvent = getProcessEvent(context, messageIn); processInstanceId = getProcessInstanceId(context); if (processInstanceId != null) { _ksession.signalEvent(processEventType, processEvent, processInstanceId.longValue()); } else { throwNullParameterException(processActionType, PROCESS_INSTANCE_ID_VAR); } break; case ABORT_PROCESS_INSTANCE: processInstanceId = getProcessInstanceId(context); if (processInstanceId != null) { _ksession.abortProcessInstance(processInstanceId.longValue()); } else { throwNullParameterException(processActionType, PROCESS_INSTANCE_ID_VAR); } break; } if (processInstanceId != null) { context.setProperty(PROCESS_INSTANCE_ID_VAR, processInstanceId, Scope.EXCHANGE); ExchangePattern exchangePattern = serviceOperation.getExchangePattern(); if (ExchangePattern.IN_OUT.equals(exchangePattern)) { if (processInstance == null) { processInstance = _ksession.getProcessInstance(processInstanceId.longValue()); } Message messageOut = exchange.createMessage(); Object messageContentOut = null; if (processInstance != null) { messageContentOut = ((WorkflowProcessInstance) processInstance).getVariable(_messageContentOutName); } if (messageContentOut != null) { messageOut.setContent(messageContentOut); } exchange.send(messageOut); } } }
private void sendResponseToSwitchyard(final Exchange switchyardExchange, final Object payload) { switchyardExchange.getMessage().setContent(payload); switchyardExchange.send(switchyardExchange.getMessage()); }
/** {@inheritDoc} */ @Override public void handleAction(Exchange exchange, KnowledgeAction action) throws HandlerException { RulesActionType actionType = (RulesActionType) action.getType(); switch (actionType) { case EXECUTE: { KnowledgeSession session = newStatelessSession(); setGlobals(exchange, action, session, true); List<Object> input = getInputList(exchange, action); session.getStateless().execute(input); break; } case INSERT: case FIRE_ALL_RULES: { /* if (!isContinue(exchange)) { disposeStatefulSession(); } */ KnowledgeSession session = getStatefulSession(); setGlobals(exchange, action, session, true); List<Object> input = getInputList(exchange, action); for (Object fact : input) { session.getStateful().insert(fact); } if (RulesActionType.FIRE_ALL_RULES.equals(actionType)) { session.getStateful().fireAllRules(); } if (isDispose(exchange)) { disposeStatefulSession(); } break; } case FIRE_UNTIL_HALT: { /* if (!isContinue(exchange)) { disposeStatefulSession(); } */ KnowledgeSession session = getStatefulSession(); setGlobals(exchange, action, session, false); if (_fireUntilHaltThread == null) { FireUntilHalt fireUntilHalt = new FireUntilHalt(this, session, getLoader()); session.addDisposals(fireUntilHalt); _fireUntilHaltThread = fireUntilHalt.startThread(); } final String undefinedVariable = toVariable(exchange); Map<String, List<Object>> listMap = getListMap(exchange, action.getInputExpressionMappings(), true, undefinedVariable); if (listMap.size() > 0) { for (Entry<String, List<Object>> entry : listMap.entrySet()) { String key = entry.getKey(); if (undefinedVariable.equals(key)) { String id = Strings.trimToNull(action.getId()); if (id != null) { key = id; } } List<Object> input = entry.getValue(); if (undefinedVariable.equals(key)) { for (Object fact : input) { session.getStateful().insert(fact); } } else { SessionEntryPoint sep = session.getStateful().getEntryPoint(key); if (sep != null) { for (Object fact : input) { sep.insert(fact); } } else { throw new HandlerException( "Unknown entry point: " + sep + "; please check your rules source."); } } } } else { Object content = exchange.getMessage().getContent(); if (content != null) { session.getStateful().insert(content); } } if (isDispose(exchange)) { disposeStatefulSession(); } break; } default: { throw new HandlerException("Unsupported action type: " + actionType); } } Object output = getOutput(exchange, action); if (ExchangePattern.IN_OUT.equals( exchange.getContract().getProviderOperation().getExchangePattern())) { Message message = exchange.createMessage().setContent(output); exchange.send(message); } }