View Javadoc

1   /*
2    * $Id: HttpRequestToBook.java 19250 2010-08-30 16:53:14Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.example.bookstore.transformers;
12  
13  import org.mule.api.MuleMessage;
14  import org.mule.api.transformer.TransformerException;
15  import org.mule.example.bookstore.Book;
16  import org.mule.example.bookstore.BookstoreAdminMessages;
17  import org.mule.transformer.AbstractMessageTransformer;
18  import org.mule.transformer.types.DataTypeFactory;
19  import org.mule.util.StringUtils;
20  
21  /**
22   * Transforms a Map of HttpRequest parameters into a Book object.
23   * The request parameters are always strings (they come from the HTML form),
24   * so we need to parse and convert them to their appropriate types.
25   */
26  public class HttpRequestToBook extends AbstractMessageTransformer
27  {
28      public HttpRequestToBook()
29      {
30          super();
31          registerSourceType(DataTypeFactory.OBJECT);
32          setReturnDataType(DataTypeFactory.create(Book.class));
33      }
34  
35      @Override
36      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
37      {
38          String author = message.getInboundProperty("author");
39          String title = message.getInboundProperty("title");
40          String price = message.getInboundProperty("price");
41  
42          if (StringUtils.isBlank(author))
43          {
44              throw new TransformerException(BookstoreAdminMessages.missingAuthor(), this);
45          }
46          if (StringUtils.isBlank(title))
47          {
48              throw new TransformerException(BookstoreAdminMessages.missingTitle(), this);
49          }
50          if (StringUtils.isBlank(price))
51          {
52              throw new TransformerException(BookstoreAdminMessages.missingPrice(), this);
53          }
54  
55          return new Book(author, title, Double.parseDouble(price));
56      }
57  }