summaryrefslogtreecommitdiffstats
path: root/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java
blob: 9c65c0b32d8e019f952b39a9e88bf9e3042d83f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.service.parameters;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.onap.policy.apex.context.parameters.ContextParameters;
import org.onap.policy.apex.model.basicmodel.service.AbstractParameters;
import org.onap.policy.apex.model.basicmodel.service.ParameterService;
import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;

/**
 * The main container parameter class for an Apex service.
 * 
 * <p>The following parameters are defined:
 * <ol>
 * <li>engineServiceParameters: The parameters for the Apex engine service itself, such as the
 * number of engine threads to run and the deployment port number to use.
 * <li>eventOutputParameters: A map of parameters for event outputs that Apex will use to emit
 * events. Apex emits events on all outputs
 * <li>eventInputParameters: A map or parameters for event inputs from which Apex will consume
 * events. Apex reads events from all its event inputs.
 * <li>synchronousEventHandlerParameters: A map of parameters for synchronous event handlers That
 * Apex receives events from and replies immediately to those events.
 * </ol>
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 */
public class ApexParameters extends AbstractParameters implements ApexParameterValidator {
    /**
     * Constructor to create an apex parameters instance and register the instance with the
     * parameter service.
     */
    public ApexParameters() {
        super(ContextParameters.class.getCanonicalName());
        ParameterService.registerParameters(ApexParameters.class, this);
    }

    // Parameters for the engine service and the engine threads in the engine service
    private EngineServiceParameters engineServiceParameters;

    // Parameters for the event outputs that Apex will use to send events on its outputs
    private Map<String, EventHandlerParameters> eventOutputParameters = new LinkedHashMap<>();

    // Parameters for the event inputs that Apex will use to receive events on its inputs
    private Map<String, EventHandlerParameters> eventInputParameters = new LinkedHashMap<>();

    /**
     * Gets the parameters for the Apex engine service.
     *
     * @return the engine service parameters
     */
    public EngineServiceParameters getEngineServiceParameters() {
        return engineServiceParameters;
    }

    /**
     * Sets the engine service parameters.
     *
     * @param engineServiceParameters the engine service parameters
     */
    public void setEngineServiceParameters(final EngineServiceParameters engineServiceParameters) {
        this.engineServiceParameters = engineServiceParameters;
    }

    /**
     * Gets the event output parameter map.
     *
     * @return the parameters for all event outputs
     */
    public Map<String, EventHandlerParameters> getEventOutputParameters() {
        return eventOutputParameters;
    }

    /**
     * Sets the event output parameters.
     *
     * @param eventOutputParameters the event outputs parameters
     */
    public void setEventOutputParameters(final Map<String, EventHandlerParameters> eventOutputParameters) {
        this.eventOutputParameters = eventOutputParameters;
    }

    /**
     * Gets the event input parameter map.
     *
     * @return the parameters for all event inputs
     */
    public Map<String, EventHandlerParameters> getEventInputParameters() {
        return eventInputParameters;
    }

    /**
     * Sets the event input parameters.
     *
     * @param eventInputParameters the event input parameters
     */
    public void setEventInputParameters(final Map<String, EventHandlerParameters> eventInputParameters) {
        this.eventInputParameters = eventInputParameters;
    }

    /**
     * This method formats a validation result with a header if the result is not empty.
     *
     * @param validationResultMessage The incoming message
     * @param heading The heading to prepend on the message
     * @return the formatted message
     */
    private String validationResultFormatter(final String validationResultMessage, final String heading) {
        final StringBuilder errorMessageBuilder = new StringBuilder();

        if (validationResultMessage.length() > 0) {
            errorMessageBuilder.append(heading);
            errorMessageBuilder.append(validationResultMessage);
        }

        return errorMessageBuilder.toString();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate()
     */
    @Override
    public String validate() {
        final StringBuilder errorMessageBuilder = new StringBuilder();

        if (engineServiceParameters == null) {
            errorMessageBuilder.append(" engine service parameters are not specified\n");
        } else {
            errorMessageBuilder.append(validationResultFormatter(engineServiceParameters.validate(),
                    " engine service parameters invalid\n"));
        }

        // Sanity check, we must have an entry in both output and input maps
        if (eventOutputParameters.isEmpty() || eventInputParameters.isEmpty()) {
            errorMessageBuilder.append(" at least one event output and one event input must be specified\n");
        }

        // Validate that the values of all parameters are ok
        validateEventHandlerMap("event input", errorMessageBuilder, eventInputParameters);
        validateEventHandlerMap("event output", errorMessageBuilder, eventOutputParameters);

        // Only do peer mode validate if there are no other errors
        if (errorMessageBuilder.length() == 0) {
            for (final EventHandlerPeeredMode peeredMode : EventHandlerPeeredMode.values()) {
                validatePeeredMode(errorMessageBuilder, peeredMode);
            }
        }

        // Check if we have any errors
        if (errorMessageBuilder.length() > 0) {
            errorMessageBuilder.insert(0, "Apex parameters invalid\n");
        }

        return errorMessageBuilder.toString().trim();
    }

    /**
     * This method validates the parameters in an event handler map.
     * 
     * @param eventHandlerType the type of the event handler to use on error messages
     * @param errorMessageBuilder the builder to use to return validation messages
     * @param parsForValidation The event handler parameters to validate (input or output)
     */
    // CHECKSTYLE:OFF: checkstyle:finalParameter
    private void validateEventHandlerMap(final String eventHandlerType, final StringBuilder errorMessageBuilder,
            final Map<String, EventHandlerParameters> parsForValidation) {
        // CHECKSTYLE:ON: checkstyle:finalParameter
        for (final Entry<String, EventHandlerParameters> parameterEntry : parsForValidation.entrySet()) {
            if (parameterEntry.getKey() == null || parameterEntry.getKey().trim().isEmpty()) {
                errorMessageBuilder
                        .append(" invalid " + eventHandlerType + " name \"" + parameterEntry.getKey() + "\" \n");
            } else if (parameterEntry.getValue() == null) {
                errorMessageBuilder.append(" invalid/Null event input prameters specified for " + eventHandlerType
                        + " name \"" + parameterEntry.getKey() + "\" \n");
            } else {
                errorMessageBuilder.append(validationResultFormatter(parameterEntry.getValue().validate(),
                        " " + eventHandlerType + " (" + parameterEntry.getKey() + ") parameters invalid\n"));
            }

            parameterEntry.getValue().setName(parameterEntry.getKey());

            // Validate parameters for peered mode settings
            for (final EventHandlerPeeredMode peeredMode : EventHandlerPeeredMode.values()) {
                validatePeeredModeParameters(eventHandlerType, errorMessageBuilder, parameterEntry, peeredMode);
            }
        }
    }

    /**
     * Validate parameter values for event handlers in a peered mode.
     * 
     * @param eventHandlerType The event handler type we are checking
     * @param errorMessageBuilder The builder to which to append any error messages
     * @param parameterEntry The entry to check the peered mode on
     * @param peeredMode The mode to check
     */
    private void validatePeeredModeParameters(final String eventHandlerType, final StringBuilder errorMessageBuilder,
            final Entry<String, EventHandlerParameters> parameterEntry, final EventHandlerPeeredMode peeredMode) {
        final String messagePreamble = " specified peered mode \"" + peeredMode + "\"";
        final String peer = parameterEntry.getValue().getPeer(peeredMode);

        if (parameterEntry.getValue().isPeeredMode(peeredMode)) {
            if (peer == null || peer.trim().isEmpty()) {
                errorMessageBuilder.append(messagePreamble + " mandatory parameter not specified or is null on "
                        + eventHandlerType + " \"" + parameterEntry.getKey() + "\" \n");
            }
            if (parameterEntry.getValue().getPeerTimeout(peeredMode) < 0) {
                errorMessageBuilder.append(
                        messagePreamble + " timeout value \"" + parameterEntry.getValue().getPeerTimeout(peeredMode)
                                + "\" is illegal on " + eventHandlerType + " \"" + parameterEntry.getKey()
                                + "\", specify a non-negative timeout value in milliseconds\n");
            }
        } else {
            if (peer != null) {
                errorMessageBuilder.append(messagePreamble + " peer is illegal on non synchronous " + eventHandlerType
                        + " \"" + parameterEntry.getKey() + "\" \n");
            }
            if (parameterEntry.getValue().getPeerTimeout(peeredMode) != 0) {
                errorMessageBuilder.append(messagePreamble + " timeout is illegal on non synchronous "
                        + eventHandlerType + " \"" + parameterEntry.getKey() + "\" \n");
            }
        }
    }

    /**
     * This method validates that the settings are valid for the given peered mode.
     * 
     * @param errorMessageBuilder The builder to which to append any error messages
     * @param peeredMode The peered mode to check
     */
    private void validatePeeredMode(final StringBuilder errorMessageBuilder, final EventHandlerPeeredMode peeredMode) {
        // Find the input and output event handlers that use this peered mode
        final Map<String, EventHandlerParameters> inputParametersUsingMode = new HashMap<>();
        final Map<String, EventHandlerParameters> outputParametersUsingMode = new HashMap<>();

        // Find input and output parameters using this mode
        for (final Entry<String, EventHandlerParameters> inputParameterEntry : eventInputParameters.entrySet()) {
            if (inputParameterEntry.getValue().isPeeredMode(peeredMode)) {
                inputParametersUsingMode.put(inputParameterEntry.getKey(), inputParameterEntry.getValue());
            }
        }
        for (final Entry<String, EventHandlerParameters> outputParameterEntry : eventOutputParameters.entrySet()) {
            if (outputParameterEntry.getValue().isPeeredMode(peeredMode)) {
                outputParametersUsingMode.put(outputParameterEntry.getKey(), outputParameterEntry.getValue());
            }
        }

        // Validate the parameters for each side of the peered mode parameters
        validatePeeredModePeers(" event input for peered mode \"" + peeredMode + "\": ", errorMessageBuilder,
                peeredMode, inputParametersUsingMode, outputParametersUsingMode);
        validatePeeredModePeers(" event output for peered mode \"" + peeredMode + "\": ", errorMessageBuilder,
                peeredMode, outputParametersUsingMode, inputParametersUsingMode);
    }

    /**
     * This method validates that the settings are valid for the event handlers on one.
     * 
     * @param messagePreamble the preamble for messages indicating the peered mode side
     * @param errorMessageBuilder The builder to which to append any error messages
     * @param leftModeParameters The mode parameters being checked
     * @param rightModeParameters The mode parameters being referenced by the checked parameters
     */
    private void validatePeeredModePeers(final String messagePreamble, final StringBuilder errorMessageBuilder,
            final EventHandlerPeeredMode peeredMode, final Map<String, EventHandlerParameters> leftModeParameterMap,
            final Map<String, EventHandlerParameters> rightModeParameterMap) {

        // These sets are used to check for duplicate references on the both sides
        final Set<String> leftCheckDuplicateSet = new HashSet<>();
        final Set<String> rightCheckDuplicateSet = new HashSet<>();

        // Check for missing peers, all peers are set because we have checked them previously so no
        // need for null checks
        for (final Entry<String, EventHandlerParameters> leftModeParameterEntry : leftModeParameterMap.entrySet()) {
            final String leftSidePeer = leftModeParameterEntry.getValue().getPeer(peeredMode);

            final EventHandlerParameters leftModeParameters = leftModeParameterEntry.getValue();
            final EventHandlerParameters rightModeParameters = rightModeParameterMap.get(leftSidePeer);

            // Check that the peer reference is OK
            if (rightModeParameters == null) {
                errorMessageBuilder.append(messagePreamble + "peer \"" + leftModeParameters.getPeer(peeredMode)
                        + "\" for event handler \"" + leftModeParameterEntry.getKey()
                        + "\" does not exist or is not defined as being synchronous\n");
                continue;
            }

            // Now check that the right side peer is the left side event handler
            final String rightSidePeer = rightModeParameters.getPeer(peeredMode);
            if (!rightSidePeer.equals(leftModeParameterEntry.getKey())) {
                errorMessageBuilder
                        .append(messagePreamble + "peer value \"" + rightSidePeer + "\" on peer \"" + leftSidePeer
                                + "\" does not equal event handler \"" + leftModeParameterEntry.getKey() + "\"\n");
            } else {
                // Check for duplicates
                if (!leftCheckDuplicateSet.add(leftSidePeer)) {
                    errorMessageBuilder
                            .append(messagePreamble + "peer value \"" + leftSidePeer + "\" on event handler \""
                                    + leftModeParameterEntry.getKey() + "\" is used more than once\n");
                }
                if (!rightCheckDuplicateSet.add(rightSidePeer)) {
                    errorMessageBuilder.append(messagePreamble + "peer value \"" + rightSidePeer + "\" on peer \""
                            + leftSidePeer + "\" on event handler \"" + leftModeParameterEntry.getKey()
                            + "\" is used more than once\n");
                }
            }

            // Cross-set the timeouts if they are not specified
            if (leftModeParameters.getPeerTimeout(peeredMode) != 0) {
                if (rightModeParameters.getPeerTimeout(peeredMode) != 0) {
                    if (leftModeParameters.getPeerTimeout(peeredMode) != rightModeParameters
                            .getPeerTimeout(peeredMode)) {
                        errorMessageBuilder.append(messagePreamble + "timeout "
                                + leftModeParameters.getPeerTimeout(peeredMode) + "on event handler \""
                                + leftModeParameters.getName() + "\" does not equal timeout value "
                                + rightModeParameters.getPeerTimeout(peeredMode) + "on event handler \""
                                + rightModeParameters.getName() + "\"\n");
                    }
                } else {
                    rightModeParameters.setPeerTimeout(peeredMode, leftModeParameters.getPeerTimeout(peeredMode));
                }
            } else {
                if (rightModeParameters.getPeerTimeout(peeredMode) != 0) {
                    leftModeParameters.setPeerTimeout(peeredMode, rightModeParameters.getPeerTimeout(peeredMode));
                }
            }
        }

    }
}