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