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