1 /*******************************************************************************
2 * ============LICENSE_START=======================================================
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
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=========================================================
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
22 package com.att.dmf.mr.utils;
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;
31 import javax.servlet.http.HttpServletResponse;
33 import org.json.JSONException;
34 import org.json.JSONObject;
36 import com.att.dmf.mr.beans.DMaaPContext;
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
41 * class is used to create response object which is given to user
43 * @author nilanjana.maity
47 public class DMaaPResponseBuilder {
50 private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPResponseBuilder.class);
51 protected static final int kBufferLength = 4096;
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");
61 * static method is used to create response object associated with
66 * @throws JSONException
69 public static void respondOk(DMaaPContext ctx, JSONObject result) throws JSONException, IOException {
71 respondOkWithStream(ctx, "application/json", new ByteArrayInputStream(result.toString(4).getBytes()));
76 * method used to set staus to 204
80 public static void respondOkNoContent(DMaaPContext ctx) {
82 ctx.getResponse().setStatus(204);
83 } catch (Exception excp) {
84 log.error(excp.getMessage(), excp);
89 * static method is used to create response object associated with html
94 public static void respondOkWithHtml(DMaaPContext ctx, String html) {
96 respondOkWithStream(ctx, "text/html", new ByteArrayInputStream(html.toString().getBytes()));
97 } catch (Exception excp) {
98 log.error(excp.getMessage(), excp);
103 * method used to create response object associated with InputStream
108 * @throws IOException
110 public static void respondOkWithStream(DMaaPContext ctx, String mediaType, final InputStream is)
113 * creates response object associated with streamwriter
115 respondOkWithStream(ctx, mediaType, new StreamWriter() {
117 public void write(OutputStream os) throws IOException {
129 * @throws IOException
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)) {
141 * static method to create error objects
147 public static void respondWithError(DMaaPContext ctx, int errCode, String msg) {
149 ctx.getResponse().sendError(errCode, msg);
150 } catch (IOException excp) {
151 log.error(excp.getMessage(), excp);
156 * method to create error objects
162 public static void respondWithError(DMaaPContext ctx, int errCode, JSONObject body) {
164 sendErrorAndBody(ctx, errCode, body.toString(4), "application/json");
165 } catch (Exception excp) {
166 log.error(excp.getMessage(), excp);
171 * static method creates error object in JSON
177 public static void respondWithErrorInJson(DMaaPContext ctx, int errCode, String msg) {
179 JSONObject o = new JSONObject();
180 o.put("status", errCode);
181 o.put("message", msg);
182 respondWithError(ctx, errCode, o);
184 } catch (Exception excp) {
185 log.error(excp.getMessage(), excp);
190 * static method used to copy the stream with the help of another method
195 * @throws IOException
197 public static void copyStream(InputStream in, OutputStream out) throws IOException {
198 copyStream(in, out, 4096);
202 * static method to copy the streams
207 * @throws IOException
209 public static void copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException {
210 byte[] buffer = new byte[bufferSize];
212 while ((len = in.read(buffer)) != -1) {
213 out.write(buffer, 0, len);
219 * interface used to define write method for outputStream
221 public abstract static interface StreamWriter {
223 * abstract method used to write the response
225 * @param paramOutputStream
226 * @throws IOException
228 public abstract void write(OutputStream paramOutputStream) throws IOException;
232 * static method returns stream for binary response
236 * @throws IOException
238 public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx) throws IOException {
239 return getStreamForBinaryResponse(ctx, "application/octet-stream");
243 * static method returns stream for binaryResponses
248 * @throws IOException
250 public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx, String contentType) throws IOException {
251 ctx.getResponse().setContentType(contentType);
254 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
256 if (fResponseEntityAllowed) {
257 try(OutputStream os = ctx.getResponse().getOutputStream()){
259 }catch (Exception e){
260 log.error("Exception in getStreamForBinaryResponse",e);
261 throw new IOException();
264 try(OutputStream os = new NullStream()){
266 }catch (Exception e){
267 log.error("Exception in getStreamForBinaryResponse",e);
268 throw new IOException();
275 * @author anowarul.islam
278 private static class NullStream extends OutputStream {
283 public void write(int b) {
287 private static class NullWriter extends Writer {
294 public void write(char[] cbuf, int off, int len) {
300 public void flush() {
306 public void close() {
311 * sttaic method fetch stream for text
318 public static void sendErrorAndBody(DMaaPContext ctx, int err, String content, String mimeType) {
321 getStreamForTextResponse(ctx, mimeType).println(content);
322 } catch (IOException e) {
323 log.error(new StringBuilder().append("Error sending error response: ").append(e.getMessage()).toString(),
329 * method to set the code
334 public static void setStatus(DMaaPContext ctx, int code) {
335 ctx.getResponse().setStatus(code);
339 * static method returns stream for text response
343 * @throws IOException
345 public static PrintWriter getStreamForTextResponse(DMaaPContext ctx) throws IOException {
346 return getStreamForTextResponse(ctx, "text/html");
350 * static method returns stream for text response
355 * @throws IOException
357 public static PrintWriter getStreamForTextResponse(DMaaPContext ctx, String contentType) throws IOException {
358 ctx.getResponse().setContentType(contentType);
360 PrintWriter pw = null;
361 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
363 if (fResponseEntityAllowed) {
364 pw = ctx.getResponse().getWriter();
366 pw = new PrintWriter(new NullWriter());