a24dd6bdffef0c87a4d08677f2483b329db60095
[dmaap/messagerouter/msgrtr.git] / src / main / java / org / onap / dmaap / messagerouter / msgrtr / nsa / cambria / utils / DMaaPResponseBuilder.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *  
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *  ============LICENSE_END=========================================================
18  *
19  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  *  
21  *******************************************************************************/
22 package org.onap.dmaap.messagerouter.msgrtr.nsa.cambria.utils;
23
24 import java.io.ByteArrayInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.io.PrintWriter;
29 import java.io.Writer;
30
31 import javax.servlet.http.HttpServletResponse;
32 import com.att.eelf.configuration.EELFLogger;
33 import com.att.eelf.configuration.EELFManager;
34 import org.json.JSONException;
35 import org.json.JSONObject;
36 import org.onap.dmaap.messagerouter.msgrtr.nsa.cambria.beans.DMaaPContext;
37
38 /**
39  * class is used to create response object which is given to user
40  * 
41  * @author author
42  *
43  */
44
45 public class DMaaPResponseBuilder {
46
47         //private static Logger log = Logger.getLogger(DMaaPResponseBuilder.class);
48         private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPResponseBuilder.class);
49         protected static final int kBufferLength = 4096;
50
51         public static void setNoCacheHeadings(DMaaPContext ctx) {
52                 HttpServletResponse response = ctx.getResponse();
53                 response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
54                 response.addHeader("Pragma", "no-cache");
55                 response.addHeader("Expires", "0");
56         }
57
58         /**
59          * static method is used to create response object associated with
60          * JSONObject
61          * 
62          * @param ctx
63          * @param result
64          * @throws JSONException
65          * @throws IOException
66          */
67         public static void respondOk(DMaaPContext ctx, JSONObject result) throws JSONException, IOException {
68
69                 respondOkWithStream(ctx, "application/json", new ByteArrayInputStream(result.toString(4).getBytes()));
70
71         }
72
73         /**
74          * method used to set staus to 204
75          * 
76          * @param ctx
77          */
78         public static void respondOkNoContent(DMaaPContext ctx) {
79                 try {
80                         ctx.getResponse().setStatus(204);
81                 } catch (Exception excp) {
82                         log.error(excp.getMessage(), excp);
83                 }
84         }
85
86         /**
87          * static method is used to create response object associated with html
88          * 
89          * @param ctx
90          * @param html
91          */
92         public static void respondOkWithHtml(DMaaPContext ctx, String html) {
93                 try {
94                         respondOkWithStream(ctx, "text/html", new ByteArrayInputStream(html.toString().getBytes()));
95                 } catch (Exception excp) {
96                         log.error(excp.getMessage(), excp);
97                 }
98         }
99
100         /**
101          * method used to create response object associated with InputStream
102          * 
103          * @param ctx
104          * @param mediaType
105          * @param is
106          * @throws IOException
107          */
108         public static void respondOkWithStream(DMaaPContext ctx, String mediaType, final InputStream is)
109                         throws IOException {
110                 /*
111                  * creates response object associated with streamwriter
112                  */
113                 respondOkWithStream(ctx, mediaType, new StreamWriter() {
114
115                         public void write(OutputStream os) throws IOException {
116                                 copyStream(is, os);
117                         }
118                 });
119
120         }
121
122         /**
123          * 
124          * @param ctx
125          * @param mediaType
126          * @param writer
127          * @throws IOException
128          */
129         public static void respondOkWithStream(DMaaPContext ctx, String mediaType, StreamWriter writer) throws IOException {
130
131                 ctx.getResponse().setStatus(200);
132                 OutputStream os = getStreamForBinaryResponse(ctx, mediaType);
133                 writer.write(os);
134
135         }
136
137         /**
138          * static method to create error objects
139          * 
140          * @param ctx
141          * @param errCode
142          * @param msg
143          */
144         public static void respondWithError(DMaaPContext ctx, int errCode, String msg) {
145                 try {
146                         ctx.getResponse().sendError(errCode, msg);
147                 } catch (IOException excp) {
148                         log.error(excp.getMessage(), excp);
149                 }
150         }
151
152         /**
153          * method to create error objects
154          * 
155          * @param ctx
156          * @param errCode
157          * @param body
158          */
159         public static void respondWithError(DMaaPContext ctx, int errCode, JSONObject body) {
160                 try {
161                         sendErrorAndBody(ctx, errCode, body.toString(4), "application/json");
162                 } catch (Exception excp) {
163                         log.error(excp.getMessage(), excp);
164                 }
165         }
166
167         /**
168          * static method creates error object in JSON
169          * 
170          * @param ctx
171          * @param errCode
172          * @param msg
173          */
174         public static void respondWithErrorInJson(DMaaPContext ctx, int errCode, String msg) {
175                 try {
176                         JSONObject o = new JSONObject();
177                         o.put("status", errCode);
178                         o.put("message", msg);
179                         respondWithError(ctx, errCode, o);
180
181                 } catch (Exception excp) {
182                         log.error(excp.getMessage(), excp);
183                 }
184         }
185
186         /**
187          * static method used to copy the stream with the help of another method
188          * copystream
189          * 
190          * @param in
191          * @param out
192          * @throws IOException
193          */
194         public static void copyStream(InputStream in, OutputStream out) throws IOException {
195                 copyStream(in, out, 4096);
196         }
197
198         /**
199          * static method to copy the streams
200          * 
201          * @param in
202          * @param out
203          * @param bufferSize
204          * @throws IOException
205          */
206         public static void copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException {
207                 byte[] buffer = new byte[bufferSize];
208                 int len;
209                 while ((len = in.read(buffer)) != -1) {
210                         out.write(buffer, 0, len);
211                 }
212                 out.close();
213         }
214
215         /**
216          * interface used to define write method for outputStream
217          */
218         public static abstract interface StreamWriter {
219                 /**
220                  * abstract method used to write the response
221                  * 
222                  * @param paramOutputStream
223                  * @throws IOException
224                  */
225                 public abstract void write(OutputStream paramOutputStream) throws IOException;
226         }
227
228         /**
229          * static method returns stream for binary response
230          * 
231          * @param ctx
232          * @return
233          * @throws IOException
234          */
235         public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx) throws IOException {
236                 return getStreamForBinaryResponse(ctx, "application/octet-stream");
237         }
238
239         /**
240          * static method returns stream for binaryResponses
241          * 
242          * @param ctx
243          * @param contentType
244          * @return
245          * @throws IOException
246          */
247         public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx, String contentType) throws IOException {
248                 ctx.getResponse().setContentType(contentType);
249
250                 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
251
252                 OutputStream os = null;
253                 if (fResponseEntityAllowed) {
254                         os = ctx.getResponse().getOutputStream();
255                 } else {
256                         os = new NullStream();
257                 }
258                 return os;
259         }
260
261         /**
262          * 
263          * @author author
264          *
265          */
266         private static class NullStream extends OutputStream {
267                 /**
268                  * @param b
269                  *            integer
270                  */
271                 public void write(int b) {
272                 }
273         }
274
275         private static class NullWriter extends Writer {
276                 /**
277                  * write method
278                  * @param cbuf
279                  * @param off
280                  * @param len
281                  */
282                 public void write(char[] cbuf, int off, int len) {
283                 }
284
285                 /**
286                  * flush method
287                  */
288                 public void flush() {
289                 }
290
291                 /**
292                  * close method
293                  */
294                 public void close() {
295                 }
296         }
297
298         /**
299          * sttaic method fetch stream for text
300          * 
301          * @param ctx
302          * @param err
303          * @param content
304          * @param mimeType
305          */
306         public static void sendErrorAndBody(DMaaPContext ctx, int err, String content, String mimeType) {
307                 try {
308                         setStatus(ctx, err);
309                         getStreamForTextResponse(ctx, mimeType).println(content);
310                 } catch (IOException e) {
311                         log.error(new StringBuilder().append("Error sending error response: ").append(e.getMessage()).toString(),
312                                         e);
313                 }
314         }
315
316         /**
317          * method to set the code
318          * 
319          * @param ctx
320          * @param code
321          */
322         public static void setStatus(DMaaPContext ctx, int code) {
323                 ctx.getResponse().setStatus(code);
324         }
325
326         /**
327          * static method returns stream for text response
328          * 
329          * @param ctx
330          * @return
331          * @throws IOException
332          */
333         public static PrintWriter getStreamForTextResponse(DMaaPContext ctx) throws IOException {
334                 return getStreamForTextResponse(ctx, "text/html");
335         }
336
337         /**
338          * static method returns stream for text response
339          * 
340          * @param ctx
341          * @param contentType
342          * @return
343          * @throws IOException
344          */
345         public static PrintWriter getStreamForTextResponse(DMaaPContext ctx, String contentType) throws IOException {
346                 ctx.getResponse().setContentType(contentType);
347
348                 PrintWriter pw = null;
349                 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
350
351                 if (fResponseEntityAllowed) {
352                         pw = ctx.getResponse().getWriter();
353                 } else {
354                         pw = new PrintWriter(new NullWriter());
355                 }
356                 return pw;
357         }
358 }