Create ResponseBuilder class
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / resources / DR_PubResource.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
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
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 package org.onap.dmaap.dbcapi.resources;
22
23 import io.swagger.annotations.Api;
24 import io.swagger.annotations.ApiOperation;
25 import io.swagger.annotations.ApiResponse;
26 import io.swagger.annotations.ApiResponses;
27
28 import java.util.ArrayList;
29 import java.util.Iterator;
30 import java.util.List;
31
32 import javax.ws.rs.Consumes;
33 import javax.ws.rs.DELETE;
34 import javax.ws.rs.GET;
35 import javax.ws.rs.POST;
36 import javax.ws.rs.PUT;
37 import javax.ws.rs.Path;
38 import javax.ws.rs.PathParam;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.core.GenericEntity;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.core.Response.Status;
44
45 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
46 import org.onap.dmaap.dbcapi.model.ApiError;
47 import org.onap.dmaap.dbcapi.model.DR_Pub;
48 import org.onap.dmaap.dbcapi.model.Feed;
49 import org.onap.dmaap.dbcapi.service.ApiService;
50 import org.onap.dmaap.dbcapi.service.DR_PubService;
51 import org.onap.dmaap.dbcapi.service.FeedService;
52
53
54 @Path("/dr_pubs")
55 @Api( value= "dr_pubs", description = "Endpoint for a Data Router client that implements a Publisher" )
56 @Consumes(MediaType.APPLICATION_JSON)
57 @Produces(MediaType.APPLICATION_JSON)
58 @Authorization
59 public class DR_PubResource extends BaseLoggingClass {
60
61         private DR_PubService dr_pubService = new DR_PubService();
62         private ResponseBuilder responseBuilder = new ResponseBuilder();
63         
64         @GET
65         @ApiOperation( value = "return DR_Pub details", 
66         notes = "Returns array of  `DR_Pub` objects.  Add filter for feedId.", 
67         response = DR_Pub.class)
68         @ApiResponses( value = {
69             @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
70             @ApiResponse( code = 400, message = "Error", response = ApiError.class )
71         })
72         public  Response getDr_Pubs() {
73                 logger.info( "Entry: GET /dr_pubs");
74                 List<DR_Pub> pubs = dr_pubService.getAllDr_Pubs();
75
76                 GenericEntity<List<DR_Pub>> list = new GenericEntity<List<DR_Pub>>(pubs) {
77         };
78         return responseBuilder.success(list);
79         }
80         
81         @POST
82         @ApiOperation( value = "return DR_Pub details", 
83         notes = "create a DR Publisher in the specified environment.", 
84         response = DR_Pub.class)
85         @ApiResponses( value = {
86             @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
87             @ApiResponse( code = 400, message = "Error", response = ApiError.class )
88         })
89         public Response addDr_Pub( 
90                         DR_Pub pub
91                         ) {
92                 ApiService resp = new ApiService();
93                 FeedService feeds = new FeedService();
94                 Feed fnew = null;
95
96                 logger.info( "Entry: POST /dr_pubs");
97
98                 try {
99                         resp.required( "feedId", pub.getFeedId(), "");
100                 } catch ( RequiredFieldException rfe ) {
101                         try {
102                                 resp.required( "feedName", pub.getFeedName(), "");
103                         }catch ( RequiredFieldException rfe2 ) {
104                                 logger.debug( resp.toString() );
105                                 return responseBuilder.error(resp.getErr());
106                         }
107                         // if we found a FeedName instead of a FeedId then try to look it up.
108                         List<Feed> nfeeds =  feeds.getAllFeeds( pub.getFeedName(), pub.getFeedVersion(), "equals");
109                         if ( nfeeds.size() != 1 ) {
110                                 logger.debug( "Attempt to match "+ pub.getFeedName() + " ver="+pub.getFeedVersion() + " matched " + nfeeds.size() );
111                                 return responseBuilder.error(resp.getErr());
112                         }
113                         fnew = nfeeds.get(0);
114                 }
115                 try {
116                         resp.required( "dcaeLocationName", pub.getDcaeLocationName(), "");
117                 } catch ( RequiredFieldException rfe ) {
118                         logger.debug( resp.getErr().toString() );
119                         return responseBuilder.error(resp.getErr());
120                 }
121
122
123                 // we may have fnew already if located by FeedName
124                 if ( fnew == null ) {
125                         fnew = feeds.getFeed( pub.getFeedId(), resp.getErr() );
126                 }
127                 if ( fnew == null ) {
128                         logger.info( "Specified feed " + pub.getFeedId() + " or " + pub.getFeedName() + " not known to Bus Controller");        
129                         return responseBuilder.error(resp.getErr());
130                 }
131
132                 ArrayList<DR_Pub> pubs = fnew.getPubs();
133                 logger.info( "num existing pubs before = " + pubs.size() );
134                 
135                 logger.info( "update feed");
136                 pub.setNextPubId();
137                 if ( pub.getUsername() == null ) {
138                         pub.setRandomUserName();
139                 }
140                 if ( pub.getUserpwd() == null ) {
141                         pub.setRandomPassword();
142                 }
143                 pubs.add( pub );
144                 fnew.setPubs(pubs);
145                 fnew = feeds.updateFeed( fnew, resp.getErr() ); 
146                 
147                 if ( ! resp.getErr().is2xx()) { 
148                         return responseBuilder.error(resp.getErr());
149                 }
150                 pubs = fnew.getPubs();
151                 logger.info( "num existing pubs after = " + pubs.size() );
152                 
153                 DR_Pub pnew = dr_pubService.getDr_Pub(pub.getPubId(), resp.getErr());
154                 return responseBuilder.success(Status.CREATED.getStatusCode(), pnew);
155         }
156         
157         @PUT
158         @ApiOperation( value = "return DR_Pub details", 
159         notes = "update a DR Publisher in the specified environment.  Update a `DR_Pub` object by pubId", 
160         response = DR_Pub.class)
161         @ApiResponses( value = {
162             @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
163             @ApiResponse( code = 400, message = "Error", response = ApiError.class )
164         })
165         @Path("/{pubId}")
166         public Response updateDr_Pub( 
167                         @PathParam("pubId") String name, 
168                         DR_Pub pub
169                         ) {
170                 logger.info( "Entry: PUT /dr_pubs");
171                 pub.setPubId(name);
172                 DR_Pub res = dr_pubService.updateDr_Pub(pub);
173                 return responseBuilder.success(res);
174         }
175         
176         @DELETE
177         @ApiOperation( value = "return DR_Pub details", 
178         notes = "delete a DR Publisher in the specified environment. Delete a `DR_Pub` object by pubId", 
179         response = DR_Pub.class)
180         @ApiResponses( value = {
181             @ApiResponse( code = 204, message = "Success", response = DR_Pub.class),
182             @ApiResponse( code = 400, message = "Error", response = ApiError.class )
183         })
184         @Path("/{pubId}")
185         public Response deleteDr_Pub( 
186                         @PathParam("pubId") String id
187                         ){
188
189                 ApiService resp = new ApiService();
190
191                 try {
192                         resp.required( "pubId", id, "");
193                 } catch ( RequiredFieldException rfe ) {
194                         return responseBuilder.error(resp.getErr());
195                 }
196
197                 DR_Pub pub =  dr_pubService.getDr_Pub( id, resp.getErr() );
198                 if ( ! resp.getErr().is2xx()) { 
199                         return responseBuilder.error(resp.getErr());
200                 }
201                 FeedService feeds = new FeedService();
202                 Feed fnew = feeds.getFeed( pub.getFeedId(), resp.getErr() );
203                 if ( fnew == null ) {
204                         logger.info( "Specified feed " + pub.getFeedId() + " not known to Bus Controller");     
205                         return responseBuilder.error(resp.getErr());
206                 }
207                 ArrayList<DR_Pub> pubs = fnew.getPubs();
208                 if ( pubs.size() == 1 ) {
209                         resp.setCode(Status.BAD_REQUEST.getStatusCode());
210                         resp.setMessage( "Can't delete the last publisher of a feed");
211                         return responseBuilder.error(resp.getErr());
212                 }
213                 
214                 for( Iterator<DR_Pub> i = pubs.iterator(); i.hasNext(); ) {
215                         DR_Pub listItem = i.next();
216                         if ( listItem.getPubId().equals(id)) {
217                                 i.remove();
218                         }
219                 }
220                 fnew.setPubs(pubs);
221                 fnew = feeds.updateFeed( fnew, resp.getErr() );
222                 if ( ! resp.getErr().is2xx()) { 
223                         return responseBuilder.error(resp.getErr());
224                 }
225                 
226                 dr_pubService.removeDr_Pub(id, resp.getErr() );
227                 if ( ! resp.getErr().is2xx()) { 
228                         return responseBuilder.error(resp.getErr());
229                 }
230                 return responseBuilder.success(Status.NO_CONTENT.getStatusCode(), null);
231         }
232
233         @GET
234         @ApiOperation( value = "return DR_Pub details", 
235         notes = "returns a DR Publisher in the specified environment. Gets a `DR_Pub` object by pubId", 
236         response = DR_Pub.class)
237         @ApiResponses( value = {
238             @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
239             @ApiResponse( code = 400, message = "Error", response = ApiError.class )
240         })
241         @Path("/{pubId}")
242         public Response get( 
243                         @PathParam("pubId") String id
244                         ) {
245                 ApiService resp = new ApiService();
246
247                 try {
248                         resp.required( "feedId", id, "");
249                 } catch ( RequiredFieldException rfe ) {
250                         return responseBuilder.error(resp.getErr());
251                 }
252
253                 DR_Pub pub =  dr_pubService.getDr_Pub( id, resp.getErr() );
254                 if ( ! resp.getErr().is2xx()) { 
255                         resp.getErr();                  
256                 }
257                 return responseBuilder.success(Status.OK.getStatusCode(), pub);
258         }
259 }