/** {@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;
  }
Example #2
0
 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());
 }
Example #3
0
 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());
 }
Example #4
0
 @Test
 public void testPhaseIsInAfterInputMessage() {
   ServiceReference service = _domain.createInOnlyService(new QName("InPhase"));
   Exchange exchange = service.createExchange();
   exchange.send(exchange.createMessage());
   Assert.assertEquals(ExchangePhase.IN, exchange.getPhase());
 }
Example #5
0
 @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));
 }
 /** {@inheritDoc} */
 public void after(String target, Exchange exchange) throws HandlerException {
   System.out.println("-------------- " + exchange.getProvider().getName());
   if (exchange.getPhase() == ExchangePhase.OUT
       && !exchange.getProvider().getName().toString().endsWith("OrderProcessREST")) {
     handleExchange(exchange);
   }
 }
Example #7
0
 @Test
 public void testInFaultMessageTrace() throws Exception {
   ServiceReference service =
       _domain.registerService(new QName("InFaultTrace"), new MockHandler().forwardInToFault());
   Exchange exchange = _domain.createExchange(service, ExchangeContract.IN_OUT, new MockHandler());
   exchange.send(exchange.createMessage());
 }
Example #8
0
  /** Verify consumer callback is called when fault occurs on InOnly. */
  @Test
  public void testFaultReportedOnInOnly() {
    ServiceReference ref = registerInOnlyService("inOut", new ErrorExchangeHandler());
    MockHandler consumer = new MockHandler();
    Exchange exchange = ref.createExchange(consumer);
    exchange.send(exchange.createMessage().setContent("test"));

    Assert.assertEquals(1, consumer.waitForFaultMessage().getFaults().size());
  }
Example #9
0
 @Test
 public void testNullSendFault() {
   Exchange exchange = new ExchangeImpl(_domain, _dispatch);
   try {
     exchange.sendFault(null);
     Assert.fail("Expected IllegalArgumentException.");
   } catch (IllegalArgumentException e) {
     Assert.assertEquals("Invalid null 'message' argument in method call.", e.getMessage());
   }
 }
Example #10
0
 @Test
 public void testSendFaultOnNewExchange() {
   Exchange exchange = new ExchangeImpl(_domain, _dispatch);
   try {
     exchange.sendFault(exchange.createMessage());
     Assert.fail("Sending a fault on a new exchange is not allowed");
   } catch (IllegalStateException illEx) {
     return;
   }
 }
  /** {@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;
  }
Example #12
0
 @Test
 public void testPhaseIsOutAfterFaultMessage() {
   MockHandler replyHandler = new MockHandler();
   ServiceReference service =
       _domain.createInOutService(new QName("FaultPhase"), new MockHandler().forwardInToFault());
   Exchange exchange = service.createExchange(replyHandler);
   exchange.send(exchange.createMessage());
   replyHandler.waitForFaultMessage();
   Assert.assertEquals(ExchangePhase.OUT, exchange.getPhase());
 }
Example #13
0
  @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 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))));
  }
  /** 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;
  }
Example #18
0
  @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));
  }
Example #19
0
  @Test
  public void testNoNPEOnInOnlyFault() throws Exception {

    QName serviceName = new QName("testNoNPEOnNoConsumer");
    MockHandler provider =
        new MockHandler() {
          @Override
          public void handleMessage(Exchange exchange) throws HandlerException {
            throw new HandlerException("explode");
          }
        };

    ServiceReference service = _domain.createInOnlyService(serviceName, provider);

    // Don't provide a consumer...
    Exchange exchange = service.createExchange();

    exchange.send(exchange.createMessage());
  }
Example #20
0
  @Test
  public void testFaultWithNoHandler() throws Exception {

    final QName serviceName = new QName("testFaultWithNoHandler");
    // Provide the service
    MockHandler provider =
        new MockHandler() {
          @Override
          public void handleMessage(Exchange exchange) throws HandlerException {
            throw new HandlerException("Fault With No Handler!");
          }
        };
    ServiceReference service = _domain.createInOnlyService(serviceName, provider);

    // Consume the service
    Exchange exchange = service.createExchange();
    exchange.send(exchange.createMessage());

    // Make sure the exchange is in fault status
    Assert.assertEquals(ExchangeState.FAULT, exchange.getState());
  }
Example #21
0
 @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);
   }
 }
Example #22
0
  @Test
  public void testAllExchangeEventsReceived() throws Exception {
    EventCounter counter = new EventCounter();
    _domain.addEventObserver(counter, ExchangeInitiatedEvent.class);
    _domain.addEventObserver(counter, ExchangeCompletionEvent.class);

    // send 10 in-only messages and check the counters
    for (int i = 0; i < 10; i++) {
      ServiceReference inOnlyService =
          _domain.createInOnlyService(new QName("ExchangeEvent-0" + i));
      Exchange inOnly = inOnlyService.createExchange();
      inOnly.send(inOnly.createMessage());
    }

    Assert.assertEquals(10, counter.initiatedCount);
    Assert.assertEquals(10, counter.completedCount);

    // initialize counters
    counter.initiatedCount = 0;
    counter.completedCount = 0;

    // send 10 in-out and check the count
    for (int i = 0; i < 10; i++) {
      ServiceReference inOutService =
          _domain.createInOutService(
              new QName("ExchangeEvent-1" + i), new MockHandler().forwardInToOut());
      Exchange inOut = inOutService.createExchange(new MockHandler());
      inOut.send(inOut.createMessage());
    }

    Assert.assertEquals(10, counter.initiatedCount);
    Assert.assertEquals(10, counter.completedCount);
  }
 @Override
 public final void greet(final String name) {
   ExchangeSecurity es = exchange.getSecurity();
   String msg =
       String.format(
           MSG,
           _type,
           name,
           es.getCallerPrincipal(),
           es.isCallerInRole("friend"),
           es.isCallerInRole("enemy"));
   _logger.info(msg);
 }
 @Before
 public void before() {
   _exchange = Mockito.mock(ExchangeImpl.class, Mockito.RETURNS_DEEP_STUBS);
   _message = new DefaultMessage();
   Mockito.when(_exchange.createMessage()).thenReturn(_message);
   _composer = new SOAPMessageComposer();
   _composer.setContextMapper(
       new SOAPContextMapper() {
         public void mapFrom(SOAPBindingData sbd, Context context) {
           return;
         }
       });
 }
Example #25
0
  @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");
  }
Example #26
0
  /** Make sure that the current message is set correctly when an exchange is sent. */
  @Test
  public void testGetMessage() throws Exception {

    final QName serviceName = new QName("bleh");
    final String inMsgContent = "in message";
    final String outMsgContent = "out message";

    // create a handler to test that the in and out content match
    // expected result from getMessage()
    ExchangeHandler provider =
        new BaseHandler() {
          public void handleMessage(Exchange exchange) {
            Assert.assertEquals(exchange.getMessage().getContent(), inMsgContent);

            Message outMsg = exchange.createMessage();
            outMsg.setContent(outMsgContent);
            try {
              exchange.send(outMsg);
            } catch (Exception ex) {
              Assert.fail(ex.toString());
            }
          }
        };

    ExchangeHandler consumer =
        new BaseHandler() {
          public void handleMessage(Exchange exchange) {
            Assert.assertEquals(exchange.getMessage().getContent(), outMsgContent);
          }
        };

    ServiceReference service = _domain.createInOutService(serviceName, provider);
    Exchange exchange = service.createExchange(consumer);
    Message inMsg = exchange.createMessage();
    inMsg.setContent(inMsgContent);
    exchange.send(inMsg);
  }
Example #27
0
  @Test
  public void testExceptionOnSendOnFaultExchange() throws Exception {

    final QName serviceName = new QName("testExceptionOnSendOnFaultExchange");
    // Provide the service
    MockHandler provider = new MockHandler().forwardInToFault();
    ServiceReference service = _domain.createInOutService(serviceName, provider);

    // Consume the service
    MockHandler consumer = new MockHandler();
    Exchange exchange = service.createExchange(consumer);
    exchange.send(exchange.createMessage());

    // wait, since this is async
    provider.waitForOKMessage();
    consumer.waitForFaultMessage();

    // Now try send another message on the Exchange... should result in an IllegalStateException...
    try {
      exchange.send(exchange.createMessage());
    } catch (IllegalStateException e) {
      Assert.assertEquals("Exchange instance is in a FAULT state.", e.getMessage());
    }
  }
  /**
   * Create a Message from the given SOAP message.
   *
   * @param soapMessage the SOAP message to be converted
   * @param exchange The message Exchange.
   * @return a Message
   * @throws SOAPException If the SOAP message is not correct.
   */
  public Message compose(final SOAPMessage soapMessage, final Exchange exchange)
      throws SOAPException {
    Message message = exchange.createMessage();

    final SOAPBody soapBody = soapMessage.getSOAPBody();
    if (soapBody == null) {
      throw new SOAPException("Missing SOAP body from request");
    }
    final Iterator children = soapBody.getChildElements();
    boolean found = false;

    try {
      while (children.hasNext()) {
        final Node node = (Node) children.next();
        if (node instanceof SOAPElement) {
          if (found) {
            throw new SOAPException("Found multiple SOAPElements in SOAPBody");
          }
          node.detachNode();
          message.setContent(node);
          found = true;
        }
      }
    } catch (Exception ex) {
      if (ex instanceof SOAPException) {
        throw (SOAPException) ex;
      }
      throw new SOAPException(ex);
    }

    if (!found) {
      throw new SOAPException("Could not find SOAPElement in SOAPBody");
    }

    return message;
  }
Example #29
0
  @Test
  public void testExchangeCompletedEvent() {
    EventCounter counter = new EventCounter();
    _domain.addEventObserver(counter, ExchangeCompletionEvent.class);

    // send in-only and check the count
    ServiceReference inOnlyService =
        _domain.createInOnlyService(new QName("ExchangeCompleteEvent-1"));
    Exchange inOnly = inOnlyService.createExchange();
    inOnly.send(inOnly.createMessage());
    Assert.assertEquals(1, counter.completedCount);

    // reset count
    counter.completedCount = 0;

    // send in-out and check the count
    ServiceReference inOutService =
        _domain.createInOutService(
            new QName("ExchangeCompleteEvent-2"), new MockHandler().forwardInToOut());
    Exchange inOut = inOutService.createExchange(new MockHandler());
    inOut.send(inOut.createMessage());
    Assert.assertEquals(1, counter.completedCount);
  }
Example #30
0
 private void sendResponseToSwitchyard(final Exchange switchyardExchange, final Object payload) {
   switchyardExchange.getMessage().setContent(payload);
   switchyardExchange.send(switchyardExchange.getMessage());
 }