Changes for checkstyle 8.32
[policy/apex-pdp.git] / client / client-full / src / main / java / org / onap / policy / apex / client / full / rest / ApexServicesRestMain.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.full.rest;
23
24 import java.io.PrintStream;
25 import org.slf4j.ext.XLogger;
26 import org.slf4j.ext.XLoggerFactory;
27
28 /**
29  * This class is the main class that is used to launch the Apex editor from the command line.
30  *
31  */
32 public class ApexServicesRestMain {
33     // Logger for this class
34     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServicesRestMain.class);
35
36     // Recurring string constants
37     private static final String REST_ENDPOINT_PREFIX = "Apex Editor REST endpoint (";
38
39     /**
40      * The Enum EditorState holds the current state of the editor.
41      */
42     // Editor state
43     public enum EditorState {
44         /** The editor is stopped. */
45         STOPPED,
46         /** The editor is ready to run. */
47         READY,
48         /** The editor is getting ready to run. */
49         INITIALIZING,
50         /** The editor is running. */
51         RUNNING
52     }
53
54     private static final int EDITOR_RNNING_CHECK_TIMEOUT = 1000;
55
56     private EditorState state = EditorState.STOPPED;
57
58     // The Apex editor this class is running
59     private ApexServicesRest apexServices = null;
60
61     // The parameters for the editor
62     private ApexServicesRestParameters parameters = null;
63
64     // Output and error streams for messages
65     private final PrintStream outStream;
66
67     /**
68      * Constructor, kicks off the editor.
69      *
70      * @param args The command line arguments for the editor
71      * @param outStream The stream for output messages
72      */
73     public ApexServicesRestMain(final String[] args, final PrintStream outStream) {
74         // Save the streams for output and error
75         this.outStream = outStream;
76
77         // Editor parameter parsing
78         final ApexServicesRestParameterParser parser = new ApexServicesRestParameterParser();
79
80         try {
81             // Get and check the parameters
82             parameters = parser.parse(args);
83         } catch (final ApexServicesRestParameterException e) {
84             throw new ApexServicesRestParameterException(REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, "
85                             + e.getMessage() + '\n' + parser.getHelp(ApexServicesRestMain.class.getName()), e);
86         }
87
88         if (parameters.isHelpSet()) {
89             throw new ApexServicesRestParameterException(parser.getHelp(ApexServicesRestMain.class.getName()));
90         }
91
92         // Validate the parameters
93         final String validationMessage = parameters.validate();
94         if (validationMessage.length() > 0) {
95             throw new ApexServicesRestParameterException(
96                             REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage + '\n'
97                                             + parser.getHelp(ApexServicesRestMain.class.getName()));
98         }
99
100         state = EditorState.READY;
101     }
102
103     /**
104      * Initialize the Apex editor.
105      */
106     public void init() {
107         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + parameters.getBaseUri().toString()
108                         + " . . .");
109
110         try {
111             state = EditorState.INITIALIZING;
112
113             // Start the editor
114             apexServices = new ApexServicesRest(parameters);
115
116             // Add a shutdown hook to shut down the editor when the process is exiting
117             Runtime.getRuntime().addShutdownHook(new Thread(new ApexServicesRestShutdownHook()));
118
119             state = EditorState.RUNNING;
120
121             if (parameters.getTimeToLive() == ApexServicesRestParameters.INFINITY_TIME_TO_LIVE) {
122                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at "
123                                 + parameters.getBaseUri().toString());
124             } else {
125                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started");
126             }
127
128             // Find out how long is left to wait
129             long timeRemaining = parameters.getTimeToLive();
130             while (timeRemaining == ApexServicesRestParameters.INFINITY_TIME_TO_LIVE || timeRemaining > 0) {
131                 // decrement the time to live in the non-infinity case
132                 if (timeRemaining > 0) {
133                     timeRemaining--;
134                 }
135
136                 // Wait for a second
137                 Thread.sleep(EDITOR_RNNING_CHECK_TIMEOUT);
138             }
139         } catch (final Exception e) {
140             String message = REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage();
141             outStream.println(message);
142             LOGGER.warn(message, e);
143         } finally {
144             if (apexServices != null) {
145                 apexServices.shutdown();
146                 apexServices = null;
147             }
148             state = EditorState.STOPPED;
149         }
150     }
151
152     /**
153      * Get the editor state.
154      *
155      * @return the state
156      */
157     public EditorState getState() {
158         return state;
159     }
160
161     /**
162      * {@inheritDoc}.
163      */
164     @Override
165     public String toString() {
166         final StringBuilder ret = new StringBuilder();
167         ret.append(this.getClass().getSimpleName()).append(": Config=[").append(parameters).append("], State=")
168                         .append(this.getState());
169         return ret.toString();
170     }
171
172     /**
173      * Explicitly shut down the editor.
174      */
175     public void shutdown() {
176         if (apexServices != null) {
177             outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down");
178             apexServices.shutdown();
179         }
180         state = EditorState.STOPPED;
181         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down");
182     }
183
184     /**
185      * This class is a shutdown hook for the Apex editor command.
186      */
187     private class ApexServicesRestShutdownHook implements Runnable {
188         /**
189          * {@inheritDoc}.
190          */
191         @Override
192         public void run() {
193             if (apexServices != null) {
194                 apexServices.shutdown();
195             }
196         }
197     }
198
199     /**
200      * Main method, main entry point for command.
201      *
202      * @param args The command line arguments for the editor
203      */
204     public static void main(final String[] args) {
205         try {
206             final ApexServicesRestMain editorMain = new ApexServicesRestMain(args, System.out);
207             editorMain.init();
208         } catch (final Exception e) {
209             LOGGER.error("error starting REST client", e);
210         }
211     }
212 }