Format Java code with respect to ONAP Code Style
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / hub / HubResource.java
1 /**
2  * Copyright (c) 2018 Orange
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14
15 package org.onap.nbi.apis.hub;
16
17 import java.util.LinkedHashMap;
18 import java.util.List;
19 import java.util.Optional;
20 import java.util.stream.Collectors;
21 import org.onap.nbi.OnapComponentsUrlPaths;
22 import org.onap.nbi.apis.hub.model.Subscriber;
23 import org.onap.nbi.apis.hub.model.Subscription;
24 import org.onap.nbi.apis.hub.service.dmaap.CheckDMaaPEventsManager;
25 import org.onap.nbi.apis.hub.service.SubscriptionService;
26 import org.onap.nbi.commons.EWInterfaceUtils;
27 import org.onap.nbi.commons.JsonRepresentation;
28 import org.onap.nbi.commons.MultiCriteriaRequestBuilder;
29 import org.onap.nbi.commons.ResourceManagement;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.beans.factory.annotation.Value;
34 import org.springframework.data.mongodb.core.MongoTemplate;
35 import org.springframework.data.mongodb.core.query.Query;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.http.MediaType;
39 import org.springframework.http.ResponseEntity;
40 import org.springframework.scheduling.annotation.EnableScheduling;
41 import org.springframework.util.MultiValueMap;
42 import org.springframework.web.bind.annotation.DeleteMapping;
43 import org.springframework.web.bind.annotation.GetMapping;
44 import org.springframework.web.bind.annotation.PathVariable;
45 import org.springframework.web.bind.annotation.PostMapping;
46 import org.springframework.web.bind.annotation.RequestBody;
47 import org.springframework.web.bind.annotation.RequestHeader;
48 import org.springframework.web.bind.annotation.RequestMapping;
49 import org.springframework.web.bind.annotation.RequestParam;
50 import org.springframework.web.bind.annotation.ResponseStatus;
51 import org.springframework.web.bind.annotation.RestController;
52
53 @RestController
54 @RequestMapping(OnapComponentsUrlPaths.HUB_PATH)
55 @EnableScheduling
56 public class HubResource extends ResourceManagement {
57
58     Logger logger = LoggerFactory.getLogger(HubResource.class);
59
60     @Autowired
61     MongoTemplate mongoTemplate;
62
63     @Autowired
64     SubscriptionService subscriptionService;
65
66     @Autowired
67     MultiCriteriaRequestBuilder multiCriteriaRequestBuilder;
68
69     @Autowired
70     CheckDMaaPEventsManager checkDMaaPEventMAnager;
71
72     @Autowired
73     EWInterfaceUtils ewInterfaceUtils;
74
75     @Value("${nbi.public.url}")
76     private String nbiPublicUrl;
77
78     @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
79     public ResponseEntity<Object> createEventSubscription(@RequestBody Subscription subscription,
80             @RequestParam MultiValueMap<String, String> params,
81             @RequestHeader(value = "Target", required = false) String targetUrl) {
82         logger.debug("POST request for subscription : {}", subscription);
83         if (targetUrl != null) {
84             targetUrl = targetUrl + OnapComponentsUrlPaths.HUB_PATH;
85             String originalCallback = subscription.getCallback();
86             subscription.setCallback(nbiPublicUrl + OnapComponentsUrlPaths.LISTENER_PATH);
87             ResponseEntity ewResponse = ewInterfaceUtils.callPostRequestTarget(subscription, targetUrl);
88             if (ewResponse.getStatusCode() == HttpStatus.CREATED) {
89                 subscription.setCallback(originalCallback);
90                 subscription.setEwHost(targetUrl);
91                 subscription.setEwId(((LinkedHashMap) ewResponse.getBody()).get("id").toString());
92             } else {
93                 return ewResponse;
94             }
95         }
96         Subscriber subscriber = subscriptionService.createSubscription(subscription);
97         JsonRepresentation filter = new JsonRepresentation(params);
98         return this.createResponse(Subscription.createFromSubscriber(subscriber), filter);
99
100     }
101
102     @GetMapping(value = "/{subscriptionId}", produces = MediaType.APPLICATION_JSON_VALUE)
103     public ResponseEntity<Subscription> getSubscription(@PathVariable String subscriptionId) {
104
105         Optional<Subscriber> optionalSubscriber = subscriptionService.findSubscriptionById(subscriptionId);
106         if (!optionalSubscriber.isPresent()) {
107             return ResponseEntity.notFound().build();
108         }
109         return ResponseEntity.ok(Subscription.createFromSubscriber(optionalSubscriber.get()));
110     }
111
112     @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
113     public ResponseEntity<Object> findSubscribers(@RequestParam MultiValueMap<String, String> params) {
114
115         Query query = multiCriteriaRequestBuilder.buildRequest(params);
116         List<Subscriber> subscribers = mongoTemplate.find(query, Subscriber.class);
117         JsonRepresentation filter = new JsonRepresentation(params);
118         long totalCount = subscriptionService.countSubscription();
119         HttpHeaders headers = new HttpHeaders();
120         headers.add("X-Total-Count", String.valueOf(totalCount));
121         headers.add("X-Result-Count", String.valueOf(subscribers.size()));
122         List<Subscription> subscriptions =
123                 subscribers.stream().map(Subscription::createFromSubscriber).collect(Collectors.toList());
124
125         return this.findResponse(subscriptions, filter, headers);
126
127     }
128
129     /*
130      * Resource to test for DMaaP Integration for subscribing to AAI-EVENTs
131      */
132     @GetMapping("/testaaievents")
133     @ResponseStatus(HttpStatus.OK)
134     public void testAAIEventListener() {
135         checkDMaaPEventMAnager.checkForDMaaPAAIEvents();
136     }
137
138     @DeleteMapping("/{subscriptionId}")
139     @ResponseStatus(HttpStatus.NO_CONTENT)
140     public void deleteSubscription(@PathVariable String subscriptionId) {
141         logger.debug("DELETE request for subscription id #{}", subscriptionId);
142         Optional<Subscriber> optionalSubscriber = subscriptionService.findSubscriptionById(subscriptionId);
143         subscriptionService.deleteSubscription(subscriptionId);
144         String ewHost = optionalSubscriber.get().getEwHost();
145         String ewId = optionalSubscriber.get().getEwId();
146         logger.info("POST delete for ewHost : {}", ewHost);
147         logger.info("POST delete for ewId : {}", ewId);
148         if (ewHost != null && ewId != null) {
149             logger.info("POST deleteIF for ewHost : {}", ewHost);
150             String targetUrl = ewHost + "/" + ewId;
151             ewInterfaceUtils.callDeleteRequestTarget(targetUrl);
152             logger.info("POST deleteIF for ewHost is : {}", targetUrl);
153         }
154     }
155
156 }