1 17 package org.apache.servicemix.sca.handler; 18 19 import java.io.ByteArrayOutputStream ; 20 import java.lang.reflect.Method ; 21 22 import javax.jbi.messaging.DeliveryChannel; 23 import javax.jbi.messaging.ExchangeStatus; 24 import javax.jbi.messaging.InOut; 25 import javax.jbi.messaging.NormalizedMessage; 26 import javax.xml.bind.JAXBContext; 27 28 import org.apache.servicemix.jbi.jaxp.StringSource; 29 import org.apache.servicemix.sca.ScaServiceUnit; 30 import org.apache.servicemix.sca.assembly.JbiBinding; 31 import org.apache.tuscany.model.assembly.ExternalService; 32 33 public class ExternalJbiServiceClient { 34 35 private ExternalService externalService; 36 37 private JbiBinding jbiBinding; 38 39 private ScaServiceUnit serviceUnit; 40 41 47 public ExternalJbiServiceClient(ExternalService externalService) { 48 this.serviceUnit = ScaServiceUnit.getCurrentScaServiceUnit(); 49 this.externalService = externalService; 50 this.jbiBinding = (JbiBinding) this.externalService.getBindings().get(0); 51 } 52 53 60 public Object invoke(Method method, Object [] args) { 61 if (args == null || args.length != 1) { 62 throw new IllegalStateException ("args should have exactly one object"); 63 } 64 try { 65 Object payload = args[0]; 66 Class inputClass = method.getParameterTypes()[0]; 67 Class outputClass = method.getReturnType(); 68 JAXBContext context = JAXBContext.newInstance(inputClass, outputClass); 69 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 70 context.createMarshaller().marshal(payload, baos); 71 72 DeliveryChannel channel = serviceUnit.getComponent().getComponentContext().getDeliveryChannel(); 73 InOut inout = channel.createExchangeFactory().createInOutExchange(); 77 inout.setService(jbiBinding.getServiceName()); 78 NormalizedMessage in = inout.createMessage(); 79 inout.setInMessage(in); 80 in.setContent(new StringSource(baos.toString())); 81 boolean sent = channel.sendSync(inout); 82 NormalizedMessage out = inout.getOutMessage(); 84 Object response = context.createUnmarshaller().unmarshal(out.getContent()); 85 inout.setStatus(ExchangeStatus.DONE); 86 channel.send(inout); 87 return response; 88 } catch (Exception e) { 89 throw new RuntimeException (e); 90 } 91 } 92 } 93 | Popular Tags |