@Test public void testSimpleDiscovery() throws Exception { Transformer t = muleContext .getRegistry() .lookupTransformer(DataTypeFactory.STRING, DataTypeFactory.create(Apple.class)); assertNotNull(t); assertEquals(StringToApple.class, t.getClass()); t = muleContext .getRegistry() .lookupTransformer(DataTypeFactory.STRING, DataTypeFactory.create(Orange.class)); assertNotNull(t); assertEquals(StringToOrange.class, t.getClass()); try { muleContext .getRegistry() .lookupTransformer(DataTypeFactory.STRING, DataTypeFactory.create(Banana.class)); fail("There is no transformer to go from String to Banana"); } catch (TransformerException e) { // expected } muleContext.getRegistry().registerTransformer(new StringToRedApple()); t = muleContext .getRegistry() .lookupTransformer(DataTypeFactory.STRING, DataTypeFactory.create(RedApple.class)); assertNotNull(t); assertEquals(StringToRedApple.class, t.getClass()); }
public Transformer build() { Transformer transformer; if (name == null || name.isEmpty()) { transformer = mock(getClassToMock()); } else { transformer = mock(getClassToMock(), name); doReturn(name).when(transformer).getName(); } if (resultDataType != null) { doReturn(resultDataType).when(transformer).getReturnDataType(); } if (sourceDataTypes != null) { doReturn(Arrays.asList(sourceDataTypes)).when(transformer).getSourceDataTypes(); when(transformer.isSourceDataTypeSupported( Matchers.<DataType<?>>argThat(new SupportsSourceDataType()))) .thenReturn(true); } try { doReturn(value).when(transformer).transform(Mockito.any(Object.class)); } catch (TransformerException e) { // Not going to happen during mock setup } return transformer; }
public void doTestBadReturnType(Transformer tran, Object src) throws Exception { tran.setReturnClass(InvalidSatsuma.class); try { tran.transform(src); fail("Should throw exception for bad return type"); } catch (TransformerException e) { // expected } }
public void testRoundtripTransform() throws Exception { Transformer roundTripTransformer = this.getRoundTripTransformer(); if (roundTripTransformer != null) { Object result = roundTripTransformer.transform(this.getResultData()); assertNotNull(result); assertTrue(this.compareRoundtripResults(this.getTestData(), result)); } }
public Transformer getTransformer() throws Exception { Transformer trans = createObject(DomDocumentToXml.class); trans.setReturnClass(String.class); EndpointBuilder builder = new EndpointURIEndpointBuilder("test://test", muleContext); builder.setEncoding("US-ASCII"); ImmutableEndpoint endpoint = muleContext.getRegistry().lookupEndpointFactory().getInboundEndpoint(builder); trans.setEndpoint(endpoint); return trans; }
public void testTransform() throws Exception { Transformer trans = this.getTransformer(); Object result = trans.transform(getTestData()); assertNotNull(result); Object expectedResult = this.getResultData(); assertNotNull(expectedResult); assertTrue( "Trasnformation result does not match expected result", this.compareResults(expectedResult, result)); }
protected void applyAllTransformers(List transformers) throws TransformerException { if (!transformers.isEmpty()) { for (Object transformer1 : transformers) { Transformer transformer = (Transformer) transformer1; if (getPayload() == null) { if (transformer.isAcceptNull()) { setPayload(NullPayload.getInstance()); } else { if (logger.isDebugEnabled()) { logger.debug( "Transformer " + transformer + " doesn't support the null payload, exiting from transformer chain."); } break; } } Class srcCls = getPayload().getClass(); if (transformer.isSourceTypeSupported(srcCls)) { Object result = transformer.transform(this); if (originalAdapter == null && MuleServer.getMuleContext().getConfiguration().isCacheMessageOriginalPayload()) { originalAdapter = adapter; } if (result instanceof MuleMessage) { synchronized (this) { adapter = ((MuleMessage) result).getAdapter(); } } else { setPayload(result); } } else { if (logger.isDebugEnabled()) { logger.debug( "Transformer " + transformer + " doesn't support the source payload: " + srcCls); } if (!transformer.isIgnoreBadInput()) { if (logger.isDebugEnabled()) { logger.debug("Exiting from transformer chain (ignoreBadInput = false)"); } break; } } } } }
// TODO this encoding param is never used? protected Object getPayload(Class outputType, String encoding) throws TransformerException { // Handle null by ignoring the request if (outputType == null) { return getPayload(); } Class inputCls = getPayload().getClass(); // Special case where proxies are used for testing if (Proxy.isProxyClass(inputCls)) { inputCls = inputCls.getInterfaces()[0]; } // If no conversion is necessary, just return the payload as-is if (outputType.isAssignableFrom(inputCls)) { return getPayload(); } // Grab a list of transformers that batch out input/output requirements // List transformers = RegistryContext.getRegistry().lookupTransformers(inputCls, outputType); // The transformer to execute on this message Transformer transformer; transformer = MuleServer.getMuleContext().getRegistry().lookupTransformer(inputCls, outputType); // no transformers found if (transformer == null) { throw new TransformerException( CoreMessages.noTransformerFoundForMessage(inputCls, outputType)); } // Pass in the adapter itself, so we respect the encoding Object result = transformer.transform(this); // TODO Unless we disallow Object.class as a valid return type we need to do this extra check if (!outputType.isAssignableFrom(result.getClass())) { throw new TransformerException( CoreMessages.transformOnObjectNotOfSpecifiedType( outputType.getName(), result.getClass())); } // If the payload is a stream and we've consumed it, then we should // set the payload on the message // This is the only time this method will alter the payload on the message if (isPayloadConsumed(inputCls)) { setPayload(result); } return result; }
@Override public boolean compareResults(Object expected, Object result) { // MULE-4879 field ordering is not guaranteed by the JVM so we cannot compare result strings if (expected instanceof String || expected instanceof byte[]) { try { Transformer toObject = getRoundTripTransformer(); expected = toObject.transform(expected); result = toObject.transform(result); } catch (Exception e) { fail(e.getMessage()); return false; } } return super.compareResults(expected, result); }
public Object read(InputStream in) throws MuleException { if (inboundTransformer == null) { throw new IllegalArgumentException( CoreMessages.objectIsNull("inboundTransformer").getMessage()); } if (inboundTransformer.isSourceTypeSupported(InputStream.class)) { return inboundTransformer.transform(in); } else { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(in, baos); return inboundTransformer.transform(baos.toByteArray()); } catch (IOException e) { throw new DefaultMuleException(CoreMessages.failedToReadPayload(), e); } } }
// @Override public void testTransformerConfig() { // first of all test generic transformer configuration super.testTransformerConfig(); Transformer t = muleContext.getRegistry().lookupTransformer("TestCompressionTransformer"); assertNotNull(t); assertTrue(t instanceof TestCompressionTransformer); // This will only work with the MuleXml Builder other implementations // will have to set this proerty manually or mimic Mules behaviour assertEquals( "this was set from the manager properties!", ((TestCompressionTransformer) t).getBeanProperty1()); assertEquals(12, ((TestCompressionTransformer) t).getBeanProperty2()); assertEquals(t.getReturnClass(), java.lang.String.class); t = muleContext.getRegistry().lookupTransformer("TestTransformer"); assertNotNull(t); assertEquals(t.getReturnClass(), byte[].class); }
public void write(OutputStream out, Object o, String encoding) throws MuleException { if (outboundTransformer == null) { throw new IllegalArgumentException( CoreMessages.objectIsNull("outboundTransformer").getMessage()); } try { Class returnClass = outboundTransformer.getReturnClass(); if (returnClass == null) { logger.warn( "No return class was set on transformer: " + outboundTransformer + ". Attempting to work out how to treat the result transformation"); Object result = outboundTransformer.transform(o); byte[] bytes; if (result instanceof byte[]) { bytes = (byte[]) result; } else { bytes = result.toString().getBytes(encoding); } out.write(bytes); } else if (returnClass.equals(byte[].class)) { byte[] b = (byte[]) outboundTransformer.transform(o); out.write(b); } else if (returnClass.equals(String.class)) { String s = (String) outboundTransformer.transform(o); out.write(s.getBytes(encoding)); } else { throw new TransformerException(CoreMessages.transformFailedFrom(o.getClass())); } } catch (IOException e) { throw new TransformerException(CoreMessages.transformFailedFrom(o.getClass()), e); } }
@Override public void processReplyTo(MuleEvent event, MuleMessage returnMessage, Object replyTo) throws MuleException { Destination replyToDestination = null; MessageProducer replyToProducer = null; Session session = null; try { // now we need to send the response if (replyTo instanceof Destination) { replyToDestination = (Destination) replyTo; } if (replyToDestination == null) { super.processReplyTo(event, returnMessage, replyTo); return; } // This is a work around for JmsTransformers where the current endpoint needs // to be set on the transformer so that a JMSMessage can be created correctly (the transformer // needs a Session) Class srcType = returnMessage.getPayload().getClass(); for (Iterator iterator = getTransformers().iterator(); iterator.hasNext(); ) { Transformer t = (Transformer) iterator.next(); if (t.isSourceDataTypeSupported(DataTypeFactory.create(srcType))) { if (t.getEndpoint() == null) { t.setEndpoint(getEndpoint(event, "jms://temporary")); break; } } } returnMessage.applyTransformers(getTransformers()); Object payload = returnMessage.getPayload(); if (replyToDestination instanceof Topic && replyToDestination instanceof Queue && connector.getJmsSupport() instanceof Jms102bSupport) { logger.error( StringMessageUtils.getBoilerPlate( "ReplyTo destination implements both Queue and Topic " + "while complying with JMS 1.0.2b specification. " + "Please report your application server or JMS vendor name and version " + "to dev<_at_>mule.codehaus.org or http://mule.mulesource.org/jira")); } final boolean topic = connector.getTopicResolver().isTopic(replyToDestination); session = connector.getSession(false, topic); Message replyToMessage = JmsMessageUtils.toMessage(payload, session); processMessage(replyToMessage, event); if (logger.isDebugEnabled()) { logger.debug( "Sending jms reply to: " + replyToDestination + "(" + replyToDestination.getClass().getName() + ")"); } replyToProducer = connector.getJmsSupport().createProducer(session, replyToDestination, topic); // QoS support MuleMessage eventMsg = event.getMessage(); String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY); String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY); String persistentDeliveryString = (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY); String correlationIDString = replyToMessage.getJMSCorrelationID(); if (StringUtils.isBlank(correlationIDString)) { correlationIDString = (String) eventMsg.getProperty(JmsConstants.JMS_MESSAGE_ID); replyToMessage.setJMSCorrelationID(correlationIDString); } event.getService().getStatistics().incSentReplyToEvent(); final ImmutableEndpoint endpoint = event.getEndpoint(); if (ttlString == null && priorityString == null && persistentDeliveryString == null) { connector.getJmsSupport().send(replyToProducer, replyToMessage, topic, endpoint); } else { long ttl = Message.DEFAULT_TIME_TO_LIVE; int priority = Message.DEFAULT_PRIORITY; if (ttlString != null) { ttl = Long.parseLong(ttlString); } if (priorityString != null) { priority = Integer.parseInt(priorityString); } boolean persistent = StringUtils.isNotBlank(persistentDeliveryString) ? Boolean.valueOf(persistentDeliveryString) : connector.isPersistentDelivery(); connector .getJmsSupport() .send(replyToProducer, replyToMessage, persistent, priority, ttl, topic, endpoint); } logger.info( "Reply Message sent to: " + replyToDestination + " with correlationID:" + correlationIDString); } catch (Exception e) { throw new DispatchException( JmsMessages.failedToCreateAndDispatchResponse(replyToDestination), returnMessage, null, e); } finally { connector.closeQuietly(replyToProducer); final Transaction transaction = TransactionCoordination.getInstance().getTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) { logger.debug("Closing non-TX replyTo session: " + session); } connector.closeQuietly(session); } else if (logger.isDebugEnabled()) { logger.debug("Not closing TX replyTo session: " + session); } } }