001    package com.khubla.pragmatach.plugin.jackson;
002    
003    import java.io.ByteArrayOutputStream;
004    
005    import org.codehaus.jackson.JsonEncoding;
006    import org.codehaus.jackson.JsonFactory;
007    import org.codehaus.jackson.JsonGenerator;
008    import org.codehaus.jackson.map.ObjectMapper;
009    import org.codehaus.jackson.node.ObjectNode;
010    
011    import com.khubla.pragmatach.framework.api.PragmatachException;
012    import com.khubla.pragmatach.framework.api.Response;
013    import com.khubla.pragmatach.framework.controller.impl.AbstractController;
014    import com.khubla.pragmatach.framework.controller.impl.trivial.TrivialResponse;
015    
016    /**
017     * @author tome
018     */
019    public class JacksonController extends AbstractController {
020       /**
021        * factory
022        */
023       private final JsonFactory jsonFactory;
024       /**
025        * mapper
026        */
027       private final ObjectMapper objectMapper;
028    
029       /**
030        * ctor
031        */
032       public JacksonController() {
033          jsonFactory = new JsonFactory();
034          objectMapper = new ObjectMapper(jsonFactory);
035       }
036    
037       public ObjectNode createNode() {
038          return objectMapper.createObjectNode();
039       }
040    
041       public JsonFactory getJsonFactory() {
042          return jsonFactory;
043       }
044    
045       public ObjectMapper getObjectMapper() {
046          return objectMapper;
047       }
048    
049       /**
050        * render
051        */
052       public Response render(ObjectNode objectNode) throws PragmatachException {
053          try {
054             /*
055              * render json to text
056              */
057             final ByteArrayOutputStream baos = new ByteArrayOutputStream();
058             final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(baos, JsonEncoding.UTF8);
059             jsonGenerator.writeTree(objectNode);
060             jsonGenerator.close();
061             /*
062              * done
063              */
064             return new TrivialResponse(null, baos.toString(), 200);
065          } catch (final Exception e) {
066             throw new PragmatachException("Exception in render", e);
067          }
068       }
069    }