bump the version
[dmaap/messagerouter/msgrtr.git] / src / main / java / org / onap / dmaap / dmf / mr / 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.dmf.mr.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
33 import org.json.JSONException;
34 import org.json.JSONObject;
35
36 import org.onap.dmaap.dmf.mr.beans.DMaaPContext;
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
39
40 /**
41  * class is used to create response object which is given to user
42  * 
43  * @author nilanjana.maity
44  *
45  */
46
47 public class DMaaPResponseBuilder {
48
49         
50         private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPResponseBuilder.class);
51         protected static final int kBufferLength = 4096;
52
53         public static void setNoCacheHeadings(DMaaPContext ctx) {
54                 HttpServletResponse response = ctx.getResponse();
55                 response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
56                 response.addHeader("Pragma", "no-cache");
57                 response.addHeader("Expires", "0");
58         }
59
60         /**
61          * static method is used to create response object associated with
62          * JSONObject
63          * 
64          * @param ctx
65          * @param result
66          * @throws JSONException
67          * @throws IOException
68          */
69         public static void respondOk(DMaaPContext ctx, JSONObject result) throws JSONException, IOException {
70
71                 respondOkWithStream(ctx, "application/json", new ByteArrayInputStream(result.toString(4).getBytes()));
72
73         }
74
75         /**
76          * method used to set staus to 204
77          * 
78          * @param ctx
79          */
80         public static void respondOkNoContent(DMaaPContext ctx) {
81                 try {
82                         ctx.getResponse().setStatus(204);
83                 } catch (Exception excp) {
84                         log.error(excp.getMessage(), excp);
85                 }
86         }
87
88         /**
89          * static method is used to create response object associated with html
90          * 
91          * @param ctx
92          * @param html
93          */
94         public static void respondOkWithHtml(DMaaPContext ctx, String html) {
95                 try {
96                         respondOkWithStream(ctx, "text/html", new ByteArrayInputStream(html.toString().getBytes()));
97                 } catch (Exception excp) {
98                         log.error(excp.getMessage(), excp);
99                 }
100         }
101
102         /**
103          * method used to create response object associated with InputStream
104          * 
105          * @param ctx
106          * @param mediaType
107          * @param is
108          * @throws IOException
109          */
110         public static void respondOkWithStream(DMaaPContext ctx, String mediaType, final InputStream is)
111                         throws IOException {
112                 /*
113                  * creates response object associated with streamwriter
114                  */
115                 respondOkWithStream(ctx, mediaType, new StreamWriter() {
116
117                         public void write(OutputStream os) throws IOException {
118                                 copyStream(is, os);
119                         }
120                 });
121
122         }
123
124         /**
125          * 
126          * @param ctx
127          * @param mediaType
128          * @param writer
129          * @throws IOException
130          */
131         public static void respondOkWithStream(DMaaPContext ctx, String mediaType, StreamWriter writer) throws IOException {
132                 ctx.getResponse().setStatus(200);
133                 try(OutputStream os = getStreamForBinaryResponse(ctx, mediaType)) {
134                         writer.write(os);
135                 }
136
137                 
138         }
139
140         /**
141          * static method to create error objects
142          * 
143          * @param ctx
144          * @param errCode
145          * @param msg
146          */
147         public static void respondWithError(DMaaPContext ctx, int errCode, String msg) {
148                 try {
149                         ctx.getResponse().sendError(errCode, msg);
150                 } catch (IOException excp) {
151                         log.error(excp.getMessage(), excp);
152                 }
153         }
154
155         /**
156          * method to create error objects
157          * 
158          * @param ctx
159          * @param errCode
160          * @param body
161          */
162         public static void respondWithError(DMaaPContext ctx, int errCode, JSONObject body) {
163                 try {
164                         sendErrorAndBody(ctx, errCode, body.toString(4), "application/json");
165                 } catch (Exception excp) {
166                         log.error(excp.getMessage(), excp);
167                 }
168         }
169
170         /**
171          * static method creates error object in JSON
172          * 
173          * @param ctx
174          * @param errCode
175          * @param msg
176          */
177         public static void respondWithErrorInJson(DMaaPContext ctx, int errCode, String msg) {
178                 try {
179                         JSONObject o = new JSONObject();
180                         o.put("status", errCode);
181                         o.put("message", msg);
182                         respondWithError(ctx, errCode, o);
183
184                 } catch (Exception excp) {
185                         log.error(excp.getMessage(), excp);
186                 }
187         }
188
189         /**
190          * static method used to copy the stream with the help of another method
191          * copystream
192          * 
193          * @param in
194          * @param out
195          * @throws IOException
196          */
197         public static void copyStream(InputStream in, OutputStream out) throws IOException {
198                 copyStream(in, out, 4096);
199         }
200
201         /**
202          * static method to copy the streams
203          * 
204          * @param in
205          * @param out
206          * @param bufferSize
207          * @throws IOException
208          */
209         public static void copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException {
210                 byte[] buffer = new byte[bufferSize];
211                 int len;
212                 while ((len = in.read(buffer)) != -1) {
213                         out.write(buffer, 0, len);
214                 }
215                 out.close();
216         }
217
218         /**
219          * interface used to define write method for outputStream
220          */
221         public abstract static interface StreamWriter {
222                 /**
223                  * abstract method used to write the response
224                  * 
225                  * @param paramOutputStream
226                  * @throws IOException
227                  */
228                 public abstract void write(OutputStream paramOutputStream) throws IOException;
229         }
230
231         /**
232          * static method returns stream for binary response
233          * 
234          * @param ctx
235          * @return
236          * @throws IOException
237          */
238         public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx) throws IOException {
239                 return getStreamForBinaryResponse(ctx, "application/octet-stream");
240         }
241
242         /**
243          * static method returns stream for binaryResponses
244          * 
245          * @param ctx
246          * @param contentType
247          * @return
248          * @throws IOException
249          */
250         public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx, String contentType) throws IOException {
251                 ctx.getResponse().setContentType(contentType);
252                 
253
254                 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
255                 
256                 if (fResponseEntityAllowed) {
257                         try(OutputStream os = ctx.getResponse().getOutputStream()){
258                                 return os;
259                         }catch (Exception e){
260                                 log.error("Exception in getStreamForBinaryResponse",e);
261                                 throw new IOException();
262                         }
263                 } else {
264                         try(OutputStream os = new NullStream()){
265                                 return os;
266                         }catch (Exception e){
267                                 log.error("Exception in getStreamForBinaryResponse",e);
268                                 throw new IOException();
269                         }
270                 }
271         }
272
273         /**
274          * 
275          * @author anowarul.islam
276          *
277          */
278         private static class NullStream extends OutputStream {
279                 /**
280                  * @param b
281                  *            integer
282                  */
283                 public void write(int b) {
284                 }
285         }
286
287         private static class NullWriter extends Writer {
288                 /**
289                  * write method
290                  * @param cbuf
291                  * @param off
292                  * @param len
293                  */
294                 public void write(char[] cbuf, int off, int len) {
295                 }
296
297                 /**
298                  * flush method
299                  */
300                 public void flush() {
301                 }
302
303                 /**
304                  * close method
305                  */
306                 public void close() {
307                 }
308         }
309
310         /**
311          * sttaic method fetch stream for text
312          * 
313          * @param ctx
314          * @param err
315          * @param content
316          * @param mimeType
317          */
318         public static void sendErrorAndBody(DMaaPContext ctx, int err, String content, String mimeType) {
319                 try {
320                         setStatus(ctx, err);
321                         getStreamForTextResponse(ctx, mimeType).println(content);
322                 } catch (IOException e) {
323                         log.error(new StringBuilder().append("Error sending error response: ").append(e.getMessage()).toString(),
324                                         e);
325                 }
326         }
327
328         /**
329          * method to set the code
330          * 
331          * @param ctx
332          * @param code
333          */
334         public static void setStatus(DMaaPContext ctx, int code) {
335                 ctx.getResponse().setStatus(code);
336         }
337
338         /**
339          * static method returns stream for text response
340          * 
341          * @param ctx
342          * @return
343          * @throws IOException
344          */
345         public static PrintWriter getStreamForTextResponse(DMaaPContext ctx) throws IOException {
346                 return getStreamForTextResponse(ctx, "text/html");
347         }
348
349         /**
350          * static method returns stream for text response
351          * 
352          * @param ctx
353          * @param contentType
354          * @return
355          * @throws IOException
356          */
357         public static PrintWriter getStreamForTextResponse(DMaaPContext ctx, String contentType) throws IOException {
358                 ctx.getResponse().setContentType(contentType);
359
360                 PrintWriter pw = null;
361                 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
362
363                 if (fResponseEntityAllowed) {
364                         pw = ctx.getResponse().getWriter();
365                 } else {
366                         pw = new PrintWriter(new NullWriter());
367                 }
368                 return pw;
369         }
370 }