Fix sonarqube code Bug
[policy/gui.git] / gui-editors / gui-editor-apex / src / main / java / org / onap / policy / gui / editors / apex / rest / ApexEditorMain.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2021 Nordix Foundation.
5  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.gui.editors.apex.rest;
24
25 import java.io.PrintStream;
26 import java.util.concurrent.atomic.AtomicReference;
27 import org.slf4j.ext.XLogger;
28 import org.slf4j.ext.XLoggerFactory;
29
30 /**
31  * This class is the main class that is used to launch the Apex editor from the command line.
32  *
33  */
34 public class ApexEditorMain {
35     // Logger for this class
36     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorMain.class);
37
38     // Recurring string constants
39     private static final String REST_ENDPOINT_PREFIX = "Apex Editor REST endpoint (";
40
41     /**
42      * The Enum EditorState holds the current state of the editor.
43      */
44     // Editor state
45     public enum EditorState {
46         /** The editor is stopped. */
47         STOPPED,
48         /** The editor is ready to run. */
49         READY,
50         /** The editor is getting ready to run. */
51         INITIALIZING,
52         /** The editor is running. */
53         RUNNING
54     }
55
56     private static final int EDITOR_RNNING_CHECK_TIMEOUT = 1000;
57
58     private EditorState state = EditorState.STOPPED;
59
60     // The Apex editor this class is running
61     private ApexEditor apexEditor = null;
62
63     // The parameters for the editor
64     private static AtomicReference<ApexEditorParameters> parameters = new AtomicReference<>();
65
66     // Output and error streams for messages
67     private final PrintStream outStream;
68
69     /**
70      * Constructor, kicks off the editor.
71      *
72      * @param args      The command line arguments for the editor
73      * @param outStream The stream for output messages
74      */
75     public ApexEditorMain(final String[] args, final PrintStream outStream) {
76         // Save the streams for output and error
77         this.outStream = outStream;
78
79         // Editor parameter parsing
80         final ApexEditorParameterParser parser = new ApexEditorParameterParser();
81
82         try {
83             // Get and check the parameters
84             parameters.set(parser.parse(args));
85         } catch (final ApexEditorParameterException e) {
86             throw new ApexEditorParameterException(REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, "
87                 + e.getMessage() + '\n' + parser.getHelp(ApexEditorMain.class.getName()), e);
88         }
89         if (parameters.get().isHelp()) {
90             throw new ApexEditorParameterException(parser.getHelp(ApexEditorMain.class.getName()));
91         }
92
93         // Validate the parameters
94         final String validationMessage = parameters.get().validate();
95         if (validationMessage.length() > 0) {
96             throw new ApexEditorParameterException(REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, "
97                 + validationMessage + '\n' + parser.getHelp(ApexEditorMain.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 "
108                         + parameters.get().getBaseUri().toString() + " . . .");
109
110         try {
111             state = EditorState.INITIALIZING;
112
113             // Start the editor
114             apexEditor = new ApexEditor(parameters.get());
115
116             // Add a shutdown hook to shut down the editor when the process is exiting
117             Runtime.getRuntime().addShutdownHook(new Thread(new ApexEditorShutdownHook()));
118
119             state = EditorState.RUNNING;
120
121             if (parameters.get().getTimeToLive() == ApexEditorParameters.INFINITY_TIME_TO_LIVE) {
122                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at "
123                                 + parameters.get().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.get().getTimeToLive();
130             while (timeRemaining == ApexEditorParameters.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 (apexEditor != null) {
145                 apexEditor.shutdown();
146                 apexEditor = 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 (apexEditor != null) {
177             outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down");
178             apexEditor.shutdown();
179         }
180         state = EditorState.STOPPED;
181         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down");
182     }
183
184     /**
185      * Get the editor parameters.
186      *
187      * @return the parameters
188      */
189     public static ApexEditorParameters getParameters() {
190         return parameters.get();
191     }
192
193     /**
194      * This class is a shutdown hook for the Apex editor command.
195      */
196     private class ApexEditorShutdownHook implements Runnable {
197         /**
198          * {@inheritDoc}.
199          */
200         @Override
201         public void run() {
202             if (apexEditor != null) {
203                 apexEditor.shutdown();
204             }
205         }
206     }
207
208     /**
209      * Main method, main entry point for command.
210      *
211      * @param args The command line arguments for the editor
212      */
213     public static void main(final String[] args) {
214         try {
215             final ApexEditorMain editorMain = new ApexEditorMain(args, null);
216             editorMain.init();
217         } catch (final Exception e) {
218             LOGGER.error("start failed", e);
219         }
220     }
221 }