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