cdaa6a76a53e50a7d3cd717f5a6aa0b2cba16b46
[aaf/authz.git] / auth / auth-hello / src / main / java / org / onap / aaf / auth / hello / API_Hello.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 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  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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====================================================
19  *
20  */
21
22 package org.onap.aaf.auth.hello;
23
24 import java.io.BufferedReader;
25 import java.io.InputStreamReader;
26
27 import javax.servlet.ServletOutputStream;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31 import org.onap.aaf.auth.env.AuthzTrans;
32 import org.onap.aaf.auth.hello.AAF_Hello.API;
33 import org.onap.aaf.auth.rserv.HttpCode;
34 import org.onap.aaf.auth.rserv.HttpMethods;
35 import org.onap.aaf.misc.env.Env;
36 import org.onap.aaf.misc.env.TimeTaken;
37
38 import org.owasp.encoder.Encode;
39
40 /**
41  * API Apis
42  * @author Jonathan
43  *
44  */
45 public class API_Hello {
46
47
48     private static final String APPLICATION_JSON = "application/json";
49     protected static final byte[] NOT_JSON = "Data does not look like JSON".getBytes();
50
51     // Hide Public Constructor
52     private API_Hello() {}
53
54     /**
55      * Normal Init level APIs
56      *
57      * @param oauthHello
58      * @param facade
59      * @throws Exception
60      */
61     public static void init(final AAF_Hello oauthHello){
62         ////////
63         // Simple "GET" API
64         ///////
65
66         oauthHello.route(HttpMethods.GET,"/hello/:perm*",API.TOKEN,new HttpCode<AuthzTrans, AAF_Hello>(oauthHello,"Hello OAuth"){
67             @Override
68             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
69                 resp.setStatus(200 /* OK */);
70                 ServletOutputStream os = resp.getOutputStream();
71                 os.print("Hello AAF ");
72                 String perm = pathParam(req, "perm");
73                 if (perm!=null && perm.length()>0) {
74                     os.print('(');
75                     os.print(Encode.forJava(req.getUserPrincipal().getName()));
76                     TimeTaken tt = trans.start("Authorize perm", Env.REMOTE);
77                     try {
78                         if (req.isUserInRole(perm)) {
79                             os.print(" has ");
80                         } else {
81                             os.print(" does not have ");
82                         }
83                     } finally {
84                         tt.done();
85                     }
86                     os.print("Permission: ");
87                     os.print(Encode.forJava(perm));
88                     os.print(')');
89                 }
90                 os.println();
91
92                 trans.info().printf("Said 'Hello' to %s, Authentication type: %s",trans.getUserPrincipal().getName(),trans.getUserPrincipal().getClass().getSimpleName());
93             }
94         });
95
96 ////////////////
97 // REST APIs
98 ////////////////
99
100         ////////////////
101         // CREATE/POST
102         ////////////////
103         oauthHello.route(oauthHello.env,HttpMethods.POST,"/resthello/:id",new HttpCode<AuthzTrans, AAF_Hello>(oauthHello,"REST Hello Create") {
104             @Override
105             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
106                 BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
107                 StringBuilder sb = new StringBuilder();
108                 while (br.ready()) {
109                     sb.append(br.readLine());
110                 }
111                 String content = sb.toString();
112                 trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content);
113                 if (content.startsWith("{") && content.endsWith("}")) {
114                     resp.setStatus(201 /* OK */);
115                 } else {
116                     resp.getOutputStream().write(NOT_JSON);
117                     resp.setStatus(406);
118                 }
119             }
120         },APPLICATION_JSON);
121
122
123         ////////////////
124         // READ/GET
125         ////////////////
126         oauthHello.route(oauthHello.env,HttpMethods.GET,"/resthello/:id",new HttpCode<AuthzTrans, AAF_Hello>(oauthHello,"REST Hello Read") {
127             @Override
128             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
129                 resp.setStatus(200 /* OK */);
130                 StringBuilder sb = new StringBuilder("{\"resp\": \"Hello REST AAF\",\"principal\": \"");
131                 sb.append(req.getUserPrincipal().getName());
132                 sb.append('"');
133                 String perm = pathParam(req, "perm");
134                 trans.info().printf("Read request from %s: %s\n", pathParam(req, ":id"),perm);
135                 if (perm!=null && perm.length()>0) {
136                     TimeTaken tt = trans.start("Authorize perm", Env.REMOTE);
137                     try {
138                         sb.append(",\"validation\": { \"permission\" : \"");
139                         sb.append(perm);
140                         sb.append("\",\"has\" : \"");
141                         sb.append(req.isUserInRole(perm));
142                         sb.append("\"}");
143                     } finally {
144                         tt.done();
145                     }
146                 }
147                 sb.append("}");
148                 ServletOutputStream os = resp.getOutputStream();
149                 os.println(Encode.forJava(sb.toString()));
150                 trans.info().printf("Said 'RESTful Hello' to %s, Authentication type: %s",trans.getUserPrincipal().getName(),trans.getUserPrincipal().getClass().getSimpleName());
151             }
152         },APPLICATION_JSON);
153
154         ////////////////
155         // UPDATE/PUT
156         ////////////////
157         oauthHello.route(oauthHello.env,HttpMethods.PUT,"/resthello/:id",new HttpCode<AuthzTrans, AAF_Hello>(oauthHello,"REST Hello Update") {
158             @Override
159             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
160                 BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
161                 StringBuilder sb = new StringBuilder();
162                 while (br.ready()) {
163                     sb.append(br.readLine());
164                 }
165                 String content = sb.toString();
166                 trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content);
167                 if (content.startsWith("{") && content.endsWith("}")) {
168                     resp.setStatus(200 /* OK */);
169                     resp.getOutputStream().print(Encode.forJava(content));
170                 } else {
171                     resp.getOutputStream().write(NOT_JSON);
172                     resp.setStatus(406);
173                 }
174             }
175         },APPLICATION_JSON);
176
177
178         ////////////////
179         // DELETE
180         ////////////////
181         oauthHello.route(oauthHello.env,HttpMethods.DELETE,"/resthello/:id",new HttpCode<AuthzTrans, AAF_Hello>(oauthHello,"REST Hello Delete") {
182             @Override
183             public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
184                 trans.info().printf("Delete requested on %s\n", pathParam(req, ":id"));
185                 resp.setStatus(200 /* OK */);
186             }
187         },APPLICATION_JSON);
188
189     }
190 }