2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 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
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.common.util;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import fj.data.Either;
27 import javax.servlet.ServletInputStream;
28 import javax.servlet.http.HttpServletRequest;
29 import java.io.ByteArrayOutputStream;
30 import java.io.IOException;
32 public class HttpUtil {
33 public static Either<String, IOException> readJsonStringFromRequest(HttpServletRequest request) {
34 Either<String, IOException> eitherResult;
35 try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
36 ServletInputStream reader = request.getInputStream();
38 while ((value = reader.read()) != -1) {
41 eitherResult = Either.left(new String(stream.toByteArray()));
42 } catch (IOException e) {
43 eitherResult = Either.right(e);
50 * Builds an object from a JSON in the POST Body of the request.
52 public static <T> Either<T, Exception> getObjectFromJson(HttpServletRequest request, Class<T> classOfT) {
53 Either<T, Exception> eitherResult;
55 Either<String, IOException> eitherReadJson = readJsonStringFromRequest(request);
56 if (eitherReadJson.isLeft()) {
57 eitherResult = convertJsonStringToObject(eitherReadJson.left().value(), classOfT);
59 eitherResult = Either.right((Exception) eitherReadJson.right().value());
61 } catch (Exception e) {
62 eitherResult = Either.right(e);
68 public static <T> Either<T, Exception> convertJsonStringToObject(String sentJson, Class<T> classOfT) {
69 Either<T, Exception> eitherResult;
71 Gson gson = new GsonBuilder().setPrettyPrinting().create();
72 T object = gson.fromJson(sentJson, classOfT);
73 eitherResult = Either.left(object);
74 } catch (Exception e) {
75 eitherResult = Either.right(e);