Changes for checkstyle 8.32
[policy/apex-pdp.git] / client / client-editor / src / main / java / org / onap / policy / apex / client / editor / rest / ApexEditorMain.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.editor.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 ApexEditorMain {
33     // Logger for this class
34     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorMain.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 ApexEditor apexEditor = null;
60
61     // The parameters for the editor
62     private ApexEditorParameters 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 ApexEditorMain(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 ApexEditorParameterParser parser = new ApexEditorParameterParser();
79
80         try {
81             // Get and check the parameters
82             parameters = parser.parse(args);
83         } catch (final ApexEditorParameterException e) {
84             throw new ApexEditorParameterException(REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, "
85                             + e.getMessage() + '\n' + parser.getHelp(ApexEditorMain.class.getName()), e);
86         }
87
88         if (parameters.isHelpSet()) {
89             throw new ApexEditorParameterException(parser.getHelp(ApexEditorMain.class.getName()));
90         }
91
92         // Validate the parameters
93         final String validationMessage = parameters.validate();
94         if (validationMessage.length() > 0) {
95             throw new ApexEditorParameterException(REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, "
96                             + validationMessage + '\n' + parser.getHelp(ApexEditorMain.class.getName()));
97         }
98
99         state = EditorState.READY;
100     }
101
102     /**
103      * Initialize the Apex editor.
104      */
105     public void init() {
106         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + parameters.getBaseUri().toString()
107                         + " . . .");
108
109         try {
110             state = EditorState.INITIALIZING;
111
112             // Start the editor
113             apexEditor = new ApexEditor(parameters);
114
115             // Add a shutdown hook to shut down the editor when the process is exiting
116             Runtime.getRuntime().addShutdownHook(new Thread(new ApexEditorShutdownHook()));
117
118             state = EditorState.RUNNING;
119
120             if (parameters.getTimeToLive() == ApexEditorParameters.INFINITY_TIME_TO_LIVE) {
121                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at "
122                                 + parameters.getBaseUri().toString());
123             } else {
124                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started");
125             }
126
127             // Find out how long is left to wait
128             long timeRemaining = parameters.getTimeToLive();
129             while (timeRemaining == ApexEditorParameters.INFINITY_TIME_TO_LIVE || timeRemaining > 0) {
130                 // decrement the time to live in the non-infinity case
131                 if (timeRemaining > 0) {
132                     timeRemaining--;
133                 }
134
135                 // Wait for a second
136                 Thread.sleep(EDITOR_RNNING_CHECK_TIMEOUT);
137             }
138         } catch (final Exception e) {
139             String message = REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage();
140             outStream.println(message);
141             LOGGER.warn(message, e);
142         } finally {
143             if (apexEditor != null) {
144                 apexEditor.shutdown();
145                 apexEditor = null;
146             }
147             state = EditorState.STOPPED;
148         }
149     }
150
151     /**
152      * Get the editor state.
153      *
154      * @return the state
155      */
156     public EditorState getState() {
157         return state;
158     }
159
160     /**
161      * {@inheritDoc}.
162      */
163     @Override
164     public String toString() {
165         final StringBuilder ret = new StringBuilder();
166         ret.append(this.getClass().getSimpleName()).append(": Config=[").append(parameters).append("], State=")
167                         .append(this.getState());
168         return ret.toString();
169     }
170
171     /**
172      * Explicitly shut down the editor.
173      */
174     public void shutdown() {
175         if (apexEditor != null) {
176             outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down");
177             apexEditor.shutdown();
178         }
179         state = EditorState.STOPPED;
180         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down");
181     }
182
183     /**
184      * This class is a shutdown hook for the Apex editor command.
185      */
186     private class ApexEditorShutdownHook implements Runnable {
187         /**
188          * {@inheritDoc}.
189          */
190         @Override
191         public void run() {
192             if (apexEditor != null) {
193                 apexEditor.shutdown();
194             }
195         }
196     }
197
198     /**
199      * Main method, main entry point for command.
200      *
201      * @param args The command line arguments for the editor
202      */
203     public static void main(final String[] args) {
204         try {
205             final ApexEditorMain editorMain = new ApexEditorMain(args, System.out);
206             editorMain.init();
207         } catch (final Exception e) {
208             LOGGER.error("start failed", e);
209         }
210     }
211 }