0583368c20f97e7601dbbf0c0b37f720116636b2
[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
9 package org.opendaylight.controller.sample.kitchen.impl;
10
11 import com.google.common.collect.ImmutableList;
12 import com.google.common.collect.ImmutableList.Builder;
13 import com.google.common.util.concurrent.AsyncFunction;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.JdkFutureAdapters;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.ListeningExecutorService;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.util.List;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.Future;
23 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
24 import org.opendaylight.controller.sample.kitchen.api.EggsType;
25 import org.opendaylight.controller.sample.kitchen.api.KitchenService;
26 import org.opendaylight.controller.sample.kitchen.api.KitchenServiceRuntimeMXBean;
27 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
28 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInputBuilder;
29 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToastType;
30 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterListener;
31 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBread;
32 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
33 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
34 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.WheatBread;
35 import org.opendaylight.yangtools.yang.common.RpcError;
36 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class KitchenServiceImpl extends AbstractMXBean
43         implements KitchenService, KitchenServiceRuntimeMXBean, ToasterListener {
44
45     private static final Logger LOG = LoggerFactory.getLogger(KitchenServiceImpl.class);
46
47     private final ToasterService toaster;
48
49     private final ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
50
51     private volatile boolean toasterOutOfBread;
52
53     public KitchenServiceImpl(ToasterService toaster) {
54         super("KitchenService", "toaster-consumer", null);
55         this.toaster = toaster;
56     }
57
58     @Override
59     public Future<RpcResult<Void>> makeBreakfast(EggsType eggsType, Class<? extends ToastType> toastType,
60             int toastDoneness) {
61         // Call makeToast and use JdkFutureAdapters to convert the Future to a ListenableFuture, The
62         // OpendaylightToaster impl already returns a ListenableFuture so the conversion is actually a no-op.
63
64         ListenableFuture<RpcResult<Void>> makeToastFuture = JdkFutureAdapters
65                 .listenInPoolThread(makeToast(toastType, toastDoneness), executor);
66
67         ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs(eggsType);
68
69         // Combine the 2 ListenableFutures into 1 containing a list RpcResults.
70
71         ListenableFuture<List<RpcResult<Void>>> combinedFutures = Futures
72                 .allAsList(ImmutableList.of(makeToastFuture, makeEggsFuture));
73
74         // Then transform the RpcResults into 1.
75
76         return Futures.transform(combinedFutures,
77             (AsyncFunction<List<RpcResult<Void>>, RpcResult<Void>>) results -> {
78                 boolean atLeastOneSucceeded = false;
79                 Builder<RpcError> errorList = ImmutableList.builder();
80                 for (RpcResult<Void> result : results) {
81                     if (result.isSuccessful()) {
82                         atLeastOneSucceeded = true;
83                     }
84
85                     if (result.getErrors() != null) {
86                         errorList.addAll(result.getErrors());
87                     }
88                 }
89
90                 return Futures.immediateFuture(RpcResultBuilder.<Void>status(atLeastOneSucceeded)
91                         .withRpcErrors(errorList.build()).build());
92             });
93     }
94
95     private ListenableFuture<RpcResult<Void>> makeEggs(EggsType eggsType) {
96         return executor.submit(() -> RpcResultBuilder.<Void>success().build());
97     }
98
99     private Future<RpcResult<Void>> makeToast(Class<? extends ToastType> toastType, int toastDoneness) {
100
101         if (toasterOutOfBread) {
102             LOG.info("We're out of toast but we can make eggs");
103             return Futures.immediateFuture(RpcResultBuilder.<Void>success().withWarning(ErrorType.APPLICATION,
104                     "partial-operation", "Toaster is out of bread but we can make you eggs").build());
105         }
106
107         // Access the ToasterService to make the toast.
108
109         MakeToastInput toastInput = new MakeToastInputBuilder().setToasterDoneness((long) toastDoneness)
110                 .setToasterToastType(toastType).build();
111
112         return toaster.makeToast(toastInput);
113     }
114
115     @Override
116     public Boolean makeScrambledWithWheat() {
117         try {
118             // This call has to block since we must return a result to the JMX client.
119             RpcResult<Void> result = makeBreakfast(EggsType.SCRAMBLED, WheatBread.class, 2).get();
120             if (result.isSuccessful()) {
121                 LOG.info("makeBreakfast succeeded");
122             } else {
123                 LOG.warn("makeBreakfast failed: " + result.getErrors());
124             }
125
126             return result.isSuccessful();
127
128         } catch (InterruptedException | ExecutionException e) {
129             LOG.warn("An error occurred while maing breakfast: " + e);
130         }
131
132         return Boolean.FALSE;
133     }
134
135     /**
136      * Implemented from the ToasterListener interface.
137      */
138     @Override
139     public void onToasterOutOfBread(ToasterOutOfBread notification) {
140         LOG.info("ToasterOutOfBread notification");
141         toasterOutOfBread = true;
142     }
143
144     /**
145      * Implemented from the ToasterListener interface.
146      */
147     @Override
148     public void onToasterRestocked(ToasterRestocked notification) {
149         LOG.info("ToasterRestocked notification - amountOfBread: " + notification.getAmountOfBread());
150         toasterOutOfBread = false;
151     }
152 }