summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/att/dmf/mr/utils/DMaaPResponseBuilder.java
blob: 72db9de555ebd2a5dfa4023a5e80fa7c509425fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*******************************************************************************
 *  ============LICENSE_START=======================================================
 *  org.onap.dmaap
 *  ================================================================================
 *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 *  ================================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
*  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  ============LICENSE_END=========================================================
 *  
 *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
 *  
 *******************************************************************************/
package com.att.dmf.mr.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.att.dmf.mr.beans.DMaaPContext;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;

/**
 * class is used to create response object which is given to user
 * 
 * @author nilanjana.maity
 *
 */

public class DMaaPResponseBuilder {

	
	private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPResponseBuilder.class);
	protected static final int kBufferLength = 4096;

	public static void setNoCacheHeadings(DMaaPContext ctx) {
		HttpServletResponse response = ctx.getResponse();
		response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Pragma", "no-cache");
		response.addHeader("Expires", "0");
	}

	/**
	 * static method is used to create response object associated with
	 * JSONObject
	 * 
	 * @param ctx
	 * @param result
	 * @throws JSONException
	 * @throws IOException
	 */
	public static void respondOk(DMaaPContext ctx, JSONObject result) throws JSONException, IOException {

		respondOkWithStream(ctx, "application/json", new ByteArrayInputStream(result.toString(4).getBytes()));

	}

	/**
	 * method used to set staus to 204
	 * 
	 * @param ctx
	 */
	public static void respondOkNoContent(DMaaPContext ctx) {
		try {
			ctx.getResponse().setStatus(204);
		} catch (Exception excp) {
			log.error(excp.getMessage(), excp);
		}
	}

	/**
	 * static method is used to create response object associated with html
	 * 
	 * @param ctx
	 * @param html
	 */
	public static void respondOkWithHtml(DMaaPContext ctx, String html) {
		try {
			respondOkWithStream(ctx, "text/html", new ByteArrayInputStream(html.toString().getBytes()));
		} catch (Exception excp) {
			log.error(excp.getMessage(), excp);
		}
	}

	/**
	 * method used to create response object associated with InputStream
	 * 
	 * @param ctx
	 * @param mediaType
	 * @param is
	 * @throws IOException
	 */
	public static void respondOkWithStream(DMaaPContext ctx, String mediaType, final InputStream is)
			throws IOException {
		/*
		 * creates response object associated with streamwriter
		 */
		respondOkWithStream(ctx, mediaType, new StreamWriter() {

			public void write(OutputStream os) throws IOException {
				copyStream(is, os);
			}
		});

	}

	/**
	 * 
	 * @param ctx
	 * @param mediaType
	 * @param writer
	 * @throws IOException
	 */
	public static void respondOkWithStream(DMaaPContext ctx, String mediaType, StreamWriter writer) throws IOException {
		ctx.getResponse().setStatus(200);
		try(OutputStream os = getStreamForBinaryResponse(ctx, mediaType)) {
			writer.write(os);
		}

		
	}

	/**
	 * static method to create error objects
	 * 
	 * @param ctx
	 * @param errCode
	 * @param msg
	 */
	public static void respondWithError(DMaaPContext ctx, int errCode, String msg) {
		try {
			ctx.getResponse().sendError(errCode, msg);
		} catch (IOException excp) {
			log.error(excp.getMessage(), excp);
		}
	}

	/**
	 * method to create error objects
	 * 
	 * @param ctx
	 * @param errCode
	 * @param body
	 */
	public static void respondWithError(DMaaPContext ctx, int errCode, JSONObject body) {
		try {
			sendErrorAndBody(ctx, errCode, body.toString(4), "application/json");
		} catch (Exception excp) {
			log.error(excp.getMessage(), excp);
		}
	}

	/**
	 * static method creates error object in JSON
	 * 
	 * @param ctx
	 * @param errCode
	 * @param msg
	 */
	public static void respondWithErrorInJson(DMaaPContext ctx, int errCode, String msg) {
		try {
			JSONObject o = new JSONObject();
			o.put("status", errCode);
			o.put("message", msg);
			respondWithError(ctx, errCode, o);

		} catch (Exception excp) {
			log.error(excp.getMessage(), excp);
		}
	}

	/**
	 * static method used to copy the stream with the help of another method
	 * copystream
	 * 
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	public static void copyStream(InputStream in, OutputStream out) throws IOException {
		copyStream(in, out, 4096);
	}

	/**
	 * static method to copy the streams
	 * 
	 * @param in
	 * @param out
	 * @param bufferSize
	 * @throws IOException
	 */
	public static void copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException {
		byte[] buffer = new byte[bufferSize];
		int len;
		while ((len = in.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		out.close();
	}

	/**
	 * interface used to define write method for outputStream
	 */
	public abstract static interface StreamWriter {
		/**
		 * abstract method used to write the response
		 * 
		 * @param paramOutputStream
		 * @throws IOException
		 */
		public abstract void write(OutputStream paramOutputStream) throws IOException;
	}

	/**
	 * static method returns stream for binary response
	 * 
	 * @param ctx
	 * @return
	 * @throws IOException
	 */
	public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx) throws IOException {
		return getStreamForBinaryResponse(ctx, "application/octet-stream");
	}

	/**
	 * static method returns stream for binaryResponses
	 * 
	 * @param ctx
	 * @param contentType
	 * @return
	 * @throws IOException
	 */
	public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx, String contentType) throws IOException {
		ctx.getResponse().setContentType(contentType);
		

		boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
		
		if (fResponseEntityAllowed) {
			try(OutputStream os = ctx.getResponse().getOutputStream()){
				return os;
			}catch (Exception e){
				log.error("Exception in getStreamForBinaryResponse",e);
				throw new IOException();
			}
		} else {
			try(OutputStream os = new NullStream()){
				return os;
			}catch (Exception e){
				log.error("Exception in getStreamForBinaryResponse",e);
				throw new IOException();
			}
		}
	}

	/**
	 * 
	 * @author anowarul.islam
	 *
	 */
	private static class NullStream extends OutputStream {
		/**
		 * @param b
		 *            integer
		 */
		public void write(int b) {
		}
	}

	private static class NullWriter extends Writer {
		/**
		 * write method
		 * @param cbuf
		 * @param off
		 * @param len
		 */
		public void write(char[] cbuf, int off, int len) {
		}

		/**
		 * flush method
		 */
		public void flush() {
		}

		/**
		 * close method
		 */
		public void close() {
		}
	}

	/**
	 * sttaic method fetch stream for text
	 * 
	 * @param ctx
	 * @param err
	 * @param content
	 * @param mimeType
	 */
	public static void sendErrorAndBody(DMaaPContext ctx, int err, String content, String mimeType) {
		try {
			setStatus(ctx, err);
			getStreamForTextResponse(ctx, mimeType).println(content);
		} catch (IOException e) {
			log.error(new StringBuilder().append("Error sending error response: ").append(e.getMessage()).toString(),
					e);
		}
	}

	/**
	 * method to set the code
	 * 
	 * @param ctx
	 * @param code
	 */
	public static void setStatus(DMaaPContext ctx, int code) {
		ctx.getResponse().setStatus(code);
	}

	/**
	 * static method returns stream for text response
	 * 
	 * @param ctx
	 * @return
	 * @throws IOException
	 */
	public static PrintWriter getStreamForTextResponse(DMaaPContext ctx) throws IOException {
		return getStreamForTextResponse(ctx, "text/html");
	}

	/**
	 * static method returns stream for text response
	 * 
	 * @param ctx
	 * @param contentType
	 * @return
	 * @throws IOException
	 */
	public static PrintWriter getStreamForTextResponse(DMaaPContext ctx, String contentType) throws IOException {
		ctx.getResponse().setContentType(contentType);

		PrintWriter pw = null;
		boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));

		if (fResponseEntityAllowed) {
			pw = ctx.getResponse().getWriter();
		} else {
			pw = new PrintWriter(new NullWriter());
		}
		return pw;
	}
}