2 * Copyright (c) 2018 Orange
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 * the License. You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 * specific language governing permissions and limitations under the License.
13 package org.onap.nbi.apis.hub.service;
15 import com.google.common.collect.Lists;
16 import java.text.MessageFormat;
17 import java.util.List;
18 import java.util.Optional;
19 import org.onap.nbi.apis.hub.model.Subscriber;
20 import org.onap.nbi.apis.hub.model.Subscription;
21 import org.onap.nbi.apis.hub.repository.SubscriberRepository;
22 import org.onap.nbi.exceptions.ValidationException;
23 import org.springframework.beans.factory.annotation.Autowired;
24 import org.springframework.data.domain.Example;
25 import org.springframework.stereotype.Service;
26 import org.springframework.validation.ObjectError;
29 public class SubscriptionService {
32 SubscriberRepository subscriberRepository;
34 public Optional<Subscriber> findSubscriptionById(String subscriptionId) {
35 return subscriberRepository.findById(subscriptionId);
38 public Subscriber createSubscription(Subscription subscription) {
39 subscription.setId(null);
40 Subscriber subscriber = Subscriber.createFromSubscription(subscription);
41 if (isSubscriberAlreadyExisting(subscriber)) {
42 String message = MessageFormat
43 .format("subscription with callback {0} and query {1} already exists", subscription.getCallback(),
44 subscription.getQuery());
45 ObjectError error = new ObjectError("subscription", message);
46 List<ObjectError> errors = Lists.newArrayList(error);
47 throw new ValidationException(errors);
49 return subscriberRepository.save(subscriber);
53 private boolean isSubscriberAlreadyExisting(Subscriber subscriber) {
54 Example<Subscriber> subscriberExample = Example.of(subscriber);
55 Optional<Subscriber> subscriberAlreadyExisting = subscriberRepository.findOne(subscriberExample);
56 return subscriberAlreadyExisting.isPresent();
59 public void deleteSubscription(String subscriptionId) {
60 subscriberRepository.deleteById(subscriptionId);
63 public void deleteAll() {
64 subscriberRepository.deleteAll();
67 public long countSubscription() {
68 return subscriberRepository.count();