1
2
3
4
5
6
7
8
9
10
11 package org.mule.example.hello;
12
13 import org.mule.api.transformer.TransformerException;
14 import org.mule.transformer.AbstractTransformer;
15 import org.mule.util.IOUtils;
16
17 import java.io.InputStream;
18 import java.io.UnsupportedEncodingException;
19 import java.net.URLDecoder;
20
21 public class HttpRequestToNameString extends AbstractTransformer
22 {
23 private static final String NAME_REQUEST_PARAMETER = "name=";
24
25 public HttpRequestToNameString()
26 {
27 super();
28 this.registerSourceType(String.class);
29 this.registerSourceType(byte[].class);
30 this.registerSourceType(InputStream.class);
31 this.setReturnClass(NameString.class);
32 }
33
34 public Object doTransform(Object src, String encoding) throws TransformerException
35 {
36 return new NameString(extractNameValue(extractRequestQuery(convertRequestToString(src, encoding))));
37 }
38
39 private String convertRequestToString(Object src, String encoding)
40 {
41 String srcAsString = null;
42
43 if (src instanceof byte[])
44 {
45 if (encoding != null)
46 {
47 try
48 {
49 srcAsString = new String((byte[])src, encoding);
50 }
51 catch (UnsupportedEncodingException ex)
52 {
53 srcAsString = new String((byte[])src);
54 }
55 }
56 else
57 {
58 srcAsString = new String((byte[])src);
59 }
60 }
61 else if (src instanceof InputStream)
62 {
63 InputStream input = (InputStream) src;
64 try
65 {
66 srcAsString = IOUtils.toString(input);
67 }
68 finally
69 {
70 IOUtils.closeQuietly(input);
71 }
72 }
73 else
74 {
75 srcAsString = src.toString();
76 }
77
78 return srcAsString;
79 }
80
81 private String extractRequestQuery(String request)
82 {
83 String requestQuery = null;
84
85 if (request != null && request.length() > 0 && request.indexOf('?') != -1)
86 {
87 requestQuery = request.substring(request.indexOf('?') + 1).trim();
88 }
89
90 return requestQuery;
91 }
92
93 private String extractNameValue(String requestQuery) throws TransformerException
94 {
95 String nameValue = null;
96
97 if (requestQuery != null && requestQuery.length() > 0)
98 {
99 int nameParameterPos = requestQuery.indexOf(NAME_REQUEST_PARAMETER);
100 if (nameParameterPos != -1)
101 {
102 int nextParameterValuePos = requestQuery.indexOf('&');
103 if (nextParameterValuePos == -1 || nextParameterValuePos < nameParameterPos)
104 {
105 nextParameterValuePos = requestQuery.length();
106 }
107
108 nameValue = requestQuery.substring(nameParameterPos + NAME_REQUEST_PARAMETER.length(), nextParameterValuePos);
109 }
110
111 if (nameValue != null && nameValue.length() > 0)
112 {
113 try
114 {
115 nameValue = URLDecoder.decode(nameValue, "UTF-8");
116 }
117 catch (UnsupportedEncodingException uee)
118 {
119 logger.error(uee.getMessage());
120 }
121 }
122 }
123
124 if (nameValue == null)
125 {
126 nameValue = "";
127 }
128
129 return nameValue;
130 }
131 }