a40fe5e9ffdc77cc8a7fc733a07f7c3aee341b7d
[controller.git] / opendaylight / md-sal / samples / toaster-consumer / src / main / java / org / opendaylight / controller / sample / kitchen / impl / KitchenServiceImpl.java
1 /*
2  * Copyright (c) 2014, 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.sample.kitchen.impl;
9
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableList.Builder;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.ListeningExecutorService;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import java.util.List;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.Executors;
19 import javax.annotation.PreDestroy;
20 import javax.inject.Inject;
21 import javax.inject.Singleton;
22 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
23 import org.opendaylight.controller.sample.kitchen.api.EggsType;
24 import org.opendaylight.controller.sample.kitchen.api.KitchenService;
25 import org.opendaylight.controller.sample.kitchen.api.KitchenServiceRuntimeMXBean;
26 import org.opendaylight.mdsal.binding.api.NotificationService;
27 import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
28 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
29 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInputBuilder;
30 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
31 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
32 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToastType;
33 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterListener;
34 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBread;
35 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
36 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
37 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.WheatBread;
38 import org.opendaylight.yangtools.concepts.Registration;
39 import org.opendaylight.yangtools.yang.common.ErrorTag;
40 import org.opendaylight.yangtools.yang.common.ErrorType;
41 import org.opendaylight.yangtools.yang.common.RpcError;
42 import org.opendaylight.yangtools.yang.common.RpcResult;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.opendaylight.yangtools.yang.common.Uint32;
45 import org.osgi.service.component.annotations.Activate;
46 import org.osgi.service.component.annotations.Component;
47 import org.osgi.service.component.annotations.Deactivate;
48 import org.osgi.service.component.annotations.Reference;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 @Singleton
53 @Component(service = KitchenService.class, immediate = true)
54 public final class KitchenServiceImpl extends AbstractMXBean
55         implements KitchenService, KitchenServiceRuntimeMXBean, ToasterListener {
56
57     private static final Logger LOG = LoggerFactory.getLogger(KitchenServiceImpl.class);
58     private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
59
60     private final ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
61     private final ToasterService toaster;
62     private final Registration reg;
63
64     private volatile boolean toasterOutOfBread;
65
66     @Inject
67     @Activate
68     public KitchenServiceImpl(@Reference final RpcConsumerRegistry rpcRegistry,
69             @Reference final NotificationService notifService) {
70         super("KitchenService", "toaster-consumer", null);
71         toaster = rpcRegistry.getRpcService(ToasterService.class);
72         reg = notifService.registerNotificationListener(this);
73         register();
74     }
75
76     @PreDestroy
77     @Deactivate
78     public void close() {
79         unregister();
80         reg.close();
81     }
82
83     @Override
84     public ListenableFuture<RpcResult<Void>> makeBreakfast(final EggsType eggsType, final ToastType toastType,
85             final int toastDoneness) {
86         // Call makeToast, The OpendaylightToaster impl already returns a ListenableFuture so the conversion is
87         // actually a no-op.
88
89         ListenableFuture<RpcResult<MakeToastOutput>> makeToastFuture = makeToast(toastType, toastDoneness);
90
91         ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs(eggsType);
92
93         // Combine the 2 ListenableFutures into 1 containing a list RpcResults.
94
95         ListenableFuture<List<RpcResult<? extends Object>>> combinedFutures = Futures
96                 .allAsList(ImmutableList.of(makeToastFuture, makeEggsFuture));
97
98         // Then transform the RpcResults into 1.
99
100         return Futures.transformAsync(combinedFutures, results -> {
101             boolean atLeastOneSucceeded = false;
102             Builder<RpcError> errorList = ImmutableList.builder();
103             for (RpcResult<? extends Object> result : results) {
104                 if (result.isSuccessful()) {
105                     atLeastOneSucceeded = true;
106                 }
107
108                 if (result.getErrors() != null) {
109                     errorList.addAll(result.getErrors());
110                 }
111             }
112
113             return RpcResultBuilder.<Void>status(atLeastOneSucceeded).withRpcErrors(errorList.build()).buildFuture();
114         }, MoreExecutors.directExecutor());
115     }
116
117     private ListenableFuture<RpcResult<Void>> makeEggs(final EggsType eggsType) {
118         return executor.submit(() -> RpcResultBuilder.<Void>success().build());
119     }
120
121     private ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final ToastType toastType, final int toastDoneness) {
122         if (toasterOutOfBread) {
123             LOG.info("We're out of toast but we can make eggs");
124             return RpcResultBuilder.success(EMPTY_MAKE_OUTPUT)
125                 .withWarning(ErrorType.APPLICATION, ErrorTag.PARTIAL_OPERATION,
126                     "Toaster is out of bread but we can make you eggs")
127                 .buildFuture();
128         }
129
130         // Access the ToasterService to make the toast.
131
132         MakeToastInput toastInput = new MakeToastInputBuilder().setToasterDoneness(Uint32.valueOf(toastDoneness))
133                 .setToasterToastType(toastType).build();
134
135         return toaster.makeToast(toastInput);
136     }
137
138     @Override
139     public Boolean makeScrambledWithWheat() {
140         try {
141             // This call has to block since we must return a result to the JMX client.
142             RpcResult<Void> result = makeBreakfast(EggsType.SCRAMBLED, WheatBread.VALUE, 2).get();
143             if (result.isSuccessful()) {
144                 LOG.info("makeBreakfast succeeded");
145             } else {
146                 LOG.warn("makeBreakfast failed: {}", result.getErrors());
147             }
148
149             return result.isSuccessful();
150         } catch (InterruptedException | ExecutionException e) {
151             LOG.warn("An error occurred while maing breakfast", e);
152         }
153
154         return Boolean.FALSE;
155     }
156
157     /**
158      * Implemented from the ToasterListener interface.
159      */
160     @Override
161     public void onToasterOutOfBread(final ToasterOutOfBread notification) {
162         LOG.info("ToasterOutOfBread notification");
163         toasterOutOfBread = true;
164     }
165
166     /**
167      * Implemented from the ToasterListener interface.
168      */
169     @Override
170     public void onToasterRestocked(final ToasterRestocked notification) {
171         LOG.info("ToasterRestocked notification - amountOfBread: {}", notification.getAmountOfBread());
172         toasterOutOfBread = false;
173     }
174 }