View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.json.transformers;
8   
9   import org.mule.DefaultMuleMessage;
10  import org.mule.api.MuleMessage;
11  import org.mule.api.transformer.DataType;
12  import org.mule.module.json.JsonData;
13  import org.mule.tck.junit4.AbstractMuleContextTestCase;
14  import org.mule.tck.testmodels.fruit.Apple;
15  import org.mule.transformer.types.DataTypeFactory;
16  
17  import org.codehaus.jackson.map.ObjectMapper;
18  import org.junit.Test;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertFalse;
22  import static org.junit.Assert.assertNotNull;
23  import static org.junit.Assert.assertTrue;
24  
25  //TODO: IBEANS-141. No support for Mixin resolution yet
26  public class JsonAutoTransformerWithMixinsTestCase extends AbstractMuleContextTestCase
27  {
28      public static final String APPLE_JSON = "{\"washed\":false,\"bitten\":true}";
29  
30  
31      @Override
32      protected void doSetUp() throws Exception
33      {
34          //We don't register a custom transformer, instead we register a 'global' mapper that will
35          //be used for Json transforms
36          ObjectMapper mapper = new ObjectMapper();
37          mapper.getSerializationConfig().addMixInAnnotations(Apple.class, AppleMixin.class);
38          mapper.getDeserializationConfig().addMixInAnnotations(Apple.class, AppleMixin.class);
39          muleContext.getRegistry().registerObject("mapper", mapper);
40      }
41  
42      @Test
43      public void testCustomTransform() throws Exception
44      {
45          //Though the data is simple we are testing two things -
46          //1) Mixins are recognised by the Transformer resolver
47          //2) that we successfully marshal and marshal an object that is not annotated directly
48          MuleMessage message = new DefaultMuleMessage(APPLE_JSON, muleContext);
49          Apple apple = (Apple) message.getPayload(DataTypeFactory.create(Apple.class));
50          assertNotNull(apple);
51          assertFalse(apple.isWashed());
52          assertTrue(apple.isBitten());
53  
54          message = new DefaultMuleMessage(apple, muleContext);
55          String json = message.getPayload(DataType.STRING_DATA_TYPE);
56          assertNotNull(json);
57          JsonData data = new JsonData(json);
58          assertEquals("true", data.get("bitten"));
59          assertEquals("false", data.get("washed"));
60      }
61  }