Changes for checkstyle 8.32
[policy/apex-pdp.git] / client / client-monitoring / src / main / java / org / onap / policy / apex / client / monitoring / rest / ApexMonitoringRestMain.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.client.monitoring.rest;
23
24 import java.io.PrintStream;
25 import org.slf4j.ext.XLogger;
26 import org.slf4j.ext.XLoggerFactory;
27
28 /**
29  * The main class for Apex Restful Monitoring.
30  *
31  * @author Michael Watkins (michael.watkins@ericsson.com)
32  */
33 public class ApexMonitoringRestMain {
34     // Logger for this class
35     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexMonitoringRestMain.class);
36
37     // Recurring string constants
38     private static final String REST_ENDPOINT_PREFIX = "Apex Services REST endpoint (";
39
40     // Services state
41     public enum ServicesState {
42         STOPPED,
43         READY,
44         INITIALIZING,
45         RUNNING
46     }
47
48     private ServicesState state = ServicesState.STOPPED;
49
50     // The parameters for the client
51     private ApexMonitoringRestParameters parameters = null;
52
53     // Output and error streams for messages
54     private final PrintStream outStream;
55
56     // The Apex services client this class is running
57     private ApexMonitoringRest apexMonitoringRest = null;
58
59     /**
60      * Constructor, kicks off the rest service.
61      *
62      * @param args The command line arguments for the RESTful service
63      * @param outStream The stream for output messages
64      */
65     public ApexMonitoringRestMain(final String[] args, final PrintStream outStream) {
66         // Save the streams for output and error
67         this.outStream = outStream;
68
69         // Client parameter parsing
70         final ApexMonitoringRestParameterParser parser = new ApexMonitoringRestParameterParser();
71
72         try {
73             // Get and check the parameters
74             parameters = parser.parse(args);
75         } catch (final ApexMonitoringRestParameterException e) {
76             throw new ApexMonitoringRestParameterException(
77                             REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n'
78                                             + parser.getHelp(ApexMonitoringRestMain.class.getName()),
79                             e);
80         }
81
82         if (parameters.isHelpSet()) {
83             throw new ApexMonitoringRestParameterException(parser.getHelp(ApexMonitoringRestMain.class.getName()));
84         }
85
86         // Validate the parameters
87         final String validationMessage = parameters.validate();
88         if (validationMessage.length() > 0) {
89             throw new ApexMonitoringRestParameterException(
90                             REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage + '\n'
91                                             + parser.getHelp(ApexMonitoringRestMain.class.getName()));
92         }
93
94         state = ServicesState.READY;
95     }
96
97     /**
98      * Initialize the rest service.
99      */
100     public void init() {
101         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + parameters.getBaseUri().toString()
102                         + " . . .");
103
104         try {
105             state = ServicesState.INITIALIZING;
106
107             // Start the REST service
108             apexMonitoringRest = new ApexMonitoringRest(parameters);
109
110             // Add a shutdown hook to shut down the rest services when the process is exiting
111             Runtime.getRuntime().addShutdownHook(new Thread(new ApexServicesShutdownHook()));
112
113             state = ServicesState.RUNNING;
114
115             if (parameters.getTimeToLive() == ApexMonitoringRestParameters.INFINITY_TIME_TO_LIVE) {
116                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at "
117                                 + parameters.getBaseUri().toString());
118             } else {
119                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started");
120             }
121
122             // Find out how long is left to wait
123             long timeRemaining = parameters.getTimeToLive();
124             while (timeRemaining == ApexMonitoringRestParameters.INFINITY_TIME_TO_LIVE || timeRemaining > 0) {
125                 // decrement the time to live in the non-infinity case
126                 if (timeRemaining > 0) {
127                     timeRemaining--;
128                 }
129
130                 // Wait for a second
131                 Thread.sleep(1000);
132             }
133         } catch (final Exception e) {
134             String message = REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage();
135             outStream.println(message);
136             LOGGER.warn(message, e);
137         } finally {
138             if (apexMonitoringRest != null) {
139                 apexMonitoringRest.shutdown();
140                 apexMonitoringRest = null;
141             }
142             state = ServicesState.STOPPED;
143         }
144
145     }
146
147     /**
148      * Get services state.
149      *
150      * @return the service state
151      */
152     public ServicesState getState() {
153         return state;
154     }
155
156     @Override
157     public String toString() {
158         final StringBuilder ret = new StringBuilder();
159         ret.append(this.getClass().getSimpleName()).append(": Config=[").append(this.parameters).append("], State=")
160                         .append(this.getState());
161         return ret.toString();
162     }
163
164     /**
165      * Explicitly shut down the services.
166      */
167     public void shutdown() {
168         if (apexMonitoringRest != null) {
169             outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down");
170             apexMonitoringRest.shutdown();
171         }
172         state = ServicesState.STOPPED;
173         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down");
174     }
175
176     /**
177      * This class is a shutdown hook for the Apex services command.
178      */
179     private class ApexServicesShutdownHook implements Runnable {
180         /**
181          * {@inheritDoc}.
182          */
183         @Override
184         public void run() {
185             if (apexMonitoringRest != null) {
186                 apexMonitoringRest.shutdown();
187             }
188         }
189     }
190
191     /**
192      * Main method, main entry point for command.
193      *
194      * @param args The command line arguments for the client
195      */
196     public static void main(final String[] args) {
197         try {
198             final ApexMonitoringRestMain restMain = new ApexMonitoringRestMain(args, System.out);
199             restMain.init();
200         } catch (final Exception e) {
201             LOGGER.error("start failed", e);
202         }
203     }
204 }