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 org.onap.dmaap.dmf.mr.utils;
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;
30 import javax.servlet.http.HttpServletResponse;
34 * class is used to create response object which is given to user
36 * @author nilanjana.maity
40 public class DMaaPResponseBuilder {
43 private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPResponseBuilder.class);
44 protected static final int kBufferLength = 4096;
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");
54 * static method is used to create response object associated with
59 * @throws JSONException
62 public static void respondOk(DMaaPContext ctx, JSONObject result) throws JSONException, IOException {
64 respondOkWithStream(ctx, "application/json", new ByteArrayInputStream(result.toString(4).getBytes()));
69 * method used to set staus to 204
73 public static void respondOkNoContent(DMaaPContext ctx) {
75 ctx.getResponse().setStatus(204);
76 } catch (Exception excp) {
77 log.error(excp.getMessage(), excp);
82 * static method is used to create response object associated with html
87 public static void respondOkWithHtml(DMaaPContext ctx, String html) {
89 respondOkWithStream(ctx, "text/html", new ByteArrayInputStream(html.toString().getBytes()));
90 } catch (Exception excp) {
91 log.error(excp.getMessage(), excp);
96 * method used to create response object associated with InputStream
101 * @throws IOException
103 public static void respondOkWithStream(DMaaPContext ctx, String mediaType, final InputStream is)
106 * creates response object associated with streamwriter
108 respondOkWithStream(ctx, mediaType, new StreamWriter() {
110 public void write(OutputStream os) throws IOException {
122 * @throws IOException
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)) {
134 * static method to create error objects
140 public static void respondWithError(DMaaPContext ctx, int errCode, String msg) {
142 ctx.getResponse().sendError(errCode, msg);
143 } catch (IOException excp) {
144 log.error(excp.getMessage(), excp);
149 * method to create error objects
155 public static void respondWithError(DMaaPContext ctx, int errCode, JSONObject body) {
157 sendErrorAndBody(ctx, errCode, body.toString(4), "application/json");
158 } catch (Exception excp) {
159 log.error(excp.getMessage(), excp);
164 * static method creates error object in JSON
170 public static void respondWithErrorInJson(DMaaPContext ctx, int errCode, String msg) {
172 JSONObject o = new JSONObject();
173 o.put("status", errCode);
174 o.put("message", msg);
175 respondWithError(ctx, errCode, o);
177 } catch (Exception excp) {
178 log.error(excp.getMessage(), excp);
183 * static method used to copy the stream with the help of another method
188 * @throws IOException
190 public static void copyStream(InputStream in, OutputStream out) throws IOException {
191 copyStream(in, out, 4096);
195 * static method to copy the streams
200 * @throws IOException
202 public static void copyStream(InputStream in, OutputStream out, int bufferSize) throws IOException {
203 byte[] buffer = new byte[bufferSize];
205 while ((len = in.read(buffer)) != -1) {
206 out.write(buffer, 0, len);
212 * interface used to define write method for outputStream
214 public abstract static interface StreamWriter {
216 * abstract method used to write the response
218 * @param paramOutputStream
219 * @throws IOException
221 public abstract void write(OutputStream paramOutputStream) throws IOException;
225 * static method returns stream for binary response
229 * @throws IOException
231 public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx) throws IOException {
232 return getStreamForBinaryResponse(ctx, "application/octet-stream");
236 * static method returns stream for binaryResponses
241 * @throws IOException
243 public static OutputStream getStreamForBinaryResponse(DMaaPContext ctx, String contentType) throws IOException {
244 ctx.getResponse().setContentType(contentType);
247 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
249 if (fResponseEntityAllowed) {
250 try(OutputStream os = ctx.getResponse().getOutputStream()){
252 }catch (Exception e){
253 log.error("Exception in getStreamForBinaryResponse",e);
254 throw new IOException();
257 try(OutputStream os = new NullStream()){
259 }catch (Exception e){
260 log.error("Exception in getStreamForBinaryResponse",e);
261 throw new IOException();
268 * @author anowarul.islam
271 private static class NullStream extends OutputStream {
276 public void write(int b) {
280 private static class NullWriter extends Writer {
287 public void write(char[] cbuf, int off, int len) {
293 public void flush() {
299 public void close() {
304 * sttaic method fetch stream for text
311 public static void sendErrorAndBody(DMaaPContext ctx, int err, String content, String mimeType) {
314 getStreamForTextResponse(ctx, mimeType).println(content);
315 } catch (IOException e) {
316 log.error(new StringBuilder().append("Error sending error response: ").append(e.getMessage()).toString(),
322 * method to set the code
327 public static void setStatus(DMaaPContext ctx, int code) {
328 ctx.getResponse().setStatus(code);
332 * static method returns stream for text response
336 * @throws IOException
338 public static PrintWriter getStreamForTextResponse(DMaaPContext ctx) throws IOException {
339 return getStreamForTextResponse(ctx, "text/html");
343 * static method returns stream for text response
348 * @throws IOException
350 public static PrintWriter getStreamForTextResponse(DMaaPContext ctx, String contentType) throws IOException {
351 ctx.getResponse().setContentType(contentType);
353 PrintWriter pw = null;
354 boolean fResponseEntityAllowed = (!(ctx.getRequest().getMethod().equalsIgnoreCase("HEAD")));
356 if (fResponseEntityAllowed) {
357 pw = ctx.getResponse().getWriter();
359 pw = new PrintWriter(new NullWriter());