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.example.bookstore.transformers;
8   
9   import org.mule.api.MuleMessage;
10  import org.mule.api.transformer.TransformerException;
11  import org.mule.example.bookstore.Book;
12  import org.mule.example.bookstore.BookstoreAdminMessages;
13  import org.mule.transformer.AbstractMessageTransformer;
14  import org.mule.transformer.types.DataTypeFactory;
15  import org.mule.util.StringUtils;
16  
17  /**
18   * Transforms a Map of HttpRequest parameters into a Book object.
19   * The request parameters are always strings (they come from the HTML form),
20   * so we need to parse and convert them to their appropriate types.
21   */
22  public class HttpRequestToBook extends AbstractMessageTransformer
23  {
24      public HttpRequestToBook()
25      {
26          super();
27          registerSourceType(DataTypeFactory.OBJECT);
28          setReturnDataType(DataTypeFactory.create(Book.class));
29      }
30  
31      @Override
32      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
33      {
34          String author = message.getInboundProperty("author");
35          String title = message.getInboundProperty("title");
36          String price = message.getInboundProperty("price");
37  
38          if (StringUtils.isBlank(author))
39          {
40              throw new TransformerException(BookstoreAdminMessages.missingAuthor(), this);
41          }
42          if (StringUtils.isBlank(title))
43          {
44              throw new TransformerException(BookstoreAdminMessages.missingTitle(), this);
45          }
46          if (StringUtils.isBlank(price))
47          {
48              throw new TransformerException(BookstoreAdminMessages.missingPrice(), this);
49          }
50  
51          return new Book(author, title, Double.parseDouble(price));
52      }
53  }