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