Merge "Remove unused test resources in Apex Editor"
diff --git a/gui-clamp/ui-react/src/components/dialogs/Policy/PolicyDeploymentEditor.js b/gui-clamp/ui-react/src/components/dialogs/Policy/PolicyDeploymentEditor.js
index de29947..27eed22 100644
--- a/gui-clamp/ui-react/src/components/dialogs/Policy/PolicyDeploymentEditor.js
+++ b/gui-clamp/ui-react/src/components/dialogs/Policy/PolicyDeploymentEditor.js
@@ -72,6 +72,7 @@
}
createPdpGroupOperations(initialStates, newStates) {
+ console.log('createPdpGroupOperations called');
let commandsArray = [];
initialStates.forEach(initElem => {
let newStateFound = newStates.find(newElement => newElement.name === initElem.name);
@@ -89,6 +90,7 @@
}
handleUpdatePdpDeployment() {
+ console.log('handleUpdatePdpDeployment called');
let operationsList = this.createPdpGroupOperations(this.state.checkboxesInitialState,
this.state.checkboxesState);
if (typeof (operationsList) !== "undefined") {
diff --git a/gui-clamp/ui-react/src/components/dialogs/Policy/PolicyDeploymentEditor.test.js b/gui-clamp/ui-react/src/components/dialogs/Policy/PolicyDeploymentEditor.test.js
new file mode 100644
index 0000000..1ae73a2
--- /dev/null
+++ b/gui-clamp/ui-react/src/components/dialogs/Policy/PolicyDeploymentEditor.test.js
@@ -0,0 +1,93 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2022 Nordix Foundation.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+import {shallow} from "enzyme";
+import toJson from "enzyme-to-json";
+import React from "react";
+import PolicyDeploymentEditor from "./PolicyDeploymentEditor";
+import fs from "fs";
+import LoopService from "../../../api/LoopService";
+
+describe('Verify PolicyDeploymentEditor', () => {
+ const toscaPolicyDeploymentEditor = fs.readFileSync('src/components/dialogs/Policy/toscaPolicyDeploymentEditor.test.json', {
+ encoding: 'utf8',
+ flag: 'r'
+ });
+
+ const toscaPolicyDeploymentEditorArray = JSON.parse(toscaPolicyDeploymentEditor);
+
+ const initialStateTrue = [
+ {
+ "name": "monitoring/xacml",
+ "value": true
+ }
+ ];
+
+ const initialStateFalse = [
+ {
+ "name": "monitoring/xacml",
+ "value": false
+ }
+ ];
+
+ const logSpy = jest.spyOn(console, 'log');
+
+ it("renders correctly", () => {
+ const component = shallow(<PolicyDeploymentEditor policyData={toscaPolicyDeploymentEditorArray}/>);
+ expect(toJson(component)).toMatchSnapshot();
+ });
+
+ it('Test createPdpGroupOperations', () => {
+ const component = shallow(<PolicyDeploymentEditor policyData={toscaPolicyDeploymentEditorArray} />);
+
+ const instance = component.instance();
+
+ instance.createPdpGroupOperations(initialStateTrue, initialStateTrue);
+
+ component.update();
+
+ expect(logSpy).toHaveBeenCalledWith('createPdpGroupOperations called');
+ });
+
+ it('Test handleUpdatePdpDeployment', () => {
+ LoopService.updatePdpDeployment = jest.fn().mockImplementation(() => {
+ return Promise.resolve(undefined);
+ });
+
+ const component = shallow(<PolicyDeploymentEditor policyData={toscaPolicyDeploymentEditorArray} />);
+ component.setState({checkboxesInitialState: initialStateTrue});
+ component.setState({checkboxesState: initialStateFalse});
+
+ const instance = component.instance();
+ instance.handleUpdatePdpDeployment();
+
+ expect(component.state('showFailAlert')).toEqual(false);
+ expect(component.state('showMessage')).toEqual(undefined);
+
+ component.update();
+
+ component.setState({showFailAlert: true});
+ component.setState({showMessage: 'Pdp Deployment update Failure'});
+
+ expect(logSpy).toHaveBeenCalledWith('handleUpdatePdpDeployment called');
+ expect(component.state('showFailAlert')).toEqual(true);
+ expect(component.state('showMessage')).toEqual('Pdp Deployment update Failure');
+ });
+
+});
\ No newline at end of file
diff --git a/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js b/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js
index 0aed5f4..8f8bd51 100644
--- a/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js
+++ b/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js
@@ -203,6 +203,8 @@
}
generateAdditionalPolicyColumns(policiesData) {
+ console.log('generateAdditionalPolicyColumns called');
+
policiesData.forEach(policy => {
let supportedPdpGroupsString = "";
if (typeof policy.supportedPdpGroups !== "undefined") {
diff --git a/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.test.js b/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.test.js
index d4a3fd9..c2ce731 100644
--- a/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.test.js
+++ b/gui-clamp/ui-react/src/components/dialogs/Policy/ViewAllPolicies.test.js
@@ -23,7 +23,6 @@
import fs from "fs";
import PolicyToscaService from "../../../api/PolicyToscaService";
import PolicyService from "../../../api/PolicyService";
-import CreateLoopModal from "../Loop/CreateLoopModal";
import toJson from "enzyme-to-json";
describe('Verify ViewAllPolicies', () => {
@@ -36,6 +35,12 @@
flag: 'r'
});
+ const toscaPolicyModelsArray = JSON.parse(toscaPolicyModels);
+
+ const toscaPoliciesListArray = JSON.parse(toscaPoliciesList);
+
+ const logSpy = jest.spyOn(console, 'log');
+
it("renders correctly", () => {
const component = shallow(<ViewAllPolicies />);
expect(toJson(component)).toMatchSnapshot();
@@ -127,15 +132,33 @@
});
const event = { target: {value: 'event'}}
- const component = shallow(<CreateLoopModal/>);
+ const renderPoliciesTab = jest.spyOn(ViewAllPolicies.prototype, 'renderPoliciesTab');
+
+ const component = shallow(<ViewAllPolicies />);
component.setState({showSuccessAlert: true});
component.setState({showMessage: 'Policy successfully Deleted'});
+ component.setState({policiesListDataFiltered: toscaPolicyModelsArray});
- component.find('input').simulate('click', event, rowData);
component.update();
+ const instance = component.instance();
+
+ instance.handleDeletePolicy(event, rowData);
+
+ expect(renderPoliciesTab).toHaveBeenCalledTimes(4);
expect(component.state('showSuccessAlert')).toEqual(true);
expect(component.state('showMessage')).toEqual('Policy successfully Deleted');
});
+
+ it('Test generateAdditionalPolicyColumns policiesData', async () => {
+ const component = shallow(<ViewAllPolicies />);
+
+ const instance = component.instance();
+ instance.generateAdditionalPolicyColumns(toscaPoliciesListArray.policies);
+
+ component.update();
+
+ expect(logSpy).toHaveBeenCalledWith('generateAdditionalPolicyColumns called');
+ });
});
diff --git a/gui-clamp/ui-react/src/components/dialogs/Policy/__snapshots__/PolicyDeploymentEditor.test.js.snap b/gui-clamp/ui-react/src/components/dialogs/Policy/__snapshots__/PolicyDeploymentEditor.test.js.snap
new file mode 100644
index 0000000..7bf297a
--- /dev/null
+++ b/gui-clamp/ui-react/src/components/dialogs/Policy/__snapshots__/PolicyDeploymentEditor.test.js.snap
@@ -0,0 +1,71 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Verify PolicyDeploymentEditor renders correctly 1`] = `
+<styled.div>
+ <Alert
+ closeLabel="Close alert"
+ dismissible={true}
+ onClose={[Function]}
+ show={false}
+ transition={
+ Object {
+ "$$typeof": Symbol(react.forward_ref),
+ "defaultProps": Object {
+ "appear": false,
+ "in": false,
+ "mountOnEnter": false,
+ "timeout": 300,
+ "unmountOnExit": false,
+ },
+ "render": [Function],
+ }
+ }
+ variant="success"
+ >
+ <styled.div />
+ </Alert>
+ <Alert
+ closeLabel="Close alert"
+ dismissible={true}
+ onClose={[Function]}
+ show={false}
+ transition={
+ Object {
+ "$$typeof": Symbol(react.forward_ref),
+ "defaultProps": Object {
+ "appear": false,
+ "in": false,
+ "mountOnEnter": false,
+ "timeout": 300,
+ "unmountOnExit": false,
+ },
+ "render": [Function],
+ }
+ }
+ variant="danger"
+ >
+ <styled.div />
+ </Alert>
+ <Button
+ active={false}
+ disabled={false}
+ onClick={[Function]}
+ title="Update the policy to the specified PDP Groups/Subgroups"
+ variant="secondary"
+ >
+ Update PDP
+ </Button>
+ <WithStyles(ForwardRef(FormGroup))>
+ <WithStyles(ForwardRef(FormControlLabel))
+ control={
+ <WithStyles(ForwardRef(Checkbox))
+ checked={true}
+ name="monitoring/xacml"
+ onChange={[Function]}
+ />
+ }
+ label="monitoring/xacml"
+ />
+ </WithStyles(ForwardRef(FormGroup))>
+</styled.div>
+`;
diff --git a/gui-clamp/ui-react/src/components/dialogs/Policy/toscaPolicyDeploymentEditor.test.json b/gui-clamp/ui-react/src/components/dialogs/Policy/toscaPolicyDeploymentEditor.test.json
new file mode 100644
index 0000000..f6907e5
--- /dev/null
+++ b/gui-clamp/ui-react/src/components/dialogs/Policy/toscaPolicyDeploymentEditor.test.json
@@ -0,0 +1,90 @@
+{
+ "type": "onap.policies.monitoring.tcagen2",
+ "type_version": "1.0.0",
+ "properties": {
+ "tca.policy": {
+ "domain": "measurementsForVfScaling",
+ "metricsPerEventName": [
+ {
+ "policyScope": "DCAE",
+ "thresholds": [
+ {
+ "version": "1.0.2",
+ "severity": "MAJOR",
+ "thresholdValue": 200,
+ "closedLoopEventStatus": "ONSET",
+ "closedLoopControlName": "LOOP_test",
+ "direction": "LESS_OR_EQUAL",
+ "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta"
+ }
+ ],
+ "eventName": "vLoadBalancer",
+ "policyVersion": "v0.0.1",
+ "controlLoopSchemaType": "VM",
+ "policyName": "DCAE.Config_tca-hi-lo"
+ }
+ ]
+ }
+ },
+ "name": "MICROSERVICE_vLoadBalancerMS_v1_0_tcagen2_1_0_0_AV0",
+ "version": "1.0.0",
+ "metadata": {
+ "policy-id": "MICROSERVICE_vLoadBalancerMS_v1_0_tcagen2_1_0_0_AV0",
+ "policy-version": "1.0.0"
+ },
+ "pdpGroupInfo": [
+ {
+ "monitoring": {
+ "name": "monitoring",
+ "description": "This group should be used for managing all monitoring related policies and pdps",
+ "pdpGroupState": "ACTIVE",
+ "properties": {},
+ "pdpSubgroups": [
+ {
+ "pdpType": "xacml",
+ "supportedPolicyTypes": [
+ {
+ "name": "onap.policies.monitoring.*",
+ "version": "1.0.0"
+ },
+ {
+ "name": "onap.policies.Naming",
+ "version": "1.0.0"
+ }
+ ],
+ "policies": [
+ {
+ "name": "MICROSERVICE_vLoadBalancerMS_v1_0_tcagen2_1_0_0_AV0",
+ "version": "1.0.0"
+ }
+ ],
+ "currentInstanceCount": 0,
+ "desiredInstanceCount": 1,
+ "properties": {},
+ "pdpInstances": [
+ {
+ "instanceId": "monitoring-f8287777-5f3e-4f0f-b21b-d8829c93f57b",
+ "pdpState": "ACTIVE",
+ "healthy": "HEALTHY",
+ "message": "Pdp Heartbeat",
+ "lastUpdate": "2021-09-29T02:51:21Z"
+ }
+ ]
+ }
+ ]
+ }
+ }
+ ],
+ "supportedPdpGroups": [
+ {
+ "monitoring": [
+ "xacml"
+ ]
+ }
+ ],
+ "supportedPdpGroupsString": "monitoring/xacml\r\n",
+ "pdpGroupInfoString": "monitoring/xacml (ACTIVE)\r\n",
+ "tableData": {
+ "id": 0
+ }
+}
\ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/pom.xml b/gui-editors/gui-editor-apex/pom.xml
index 3a49df7..1095e14 100644
--- a/gui-editors/gui-editor-apex/pom.xml
+++ b/gui-editors/gui-editor-apex/pom.xml
@@ -1,7 +1,7 @@
<!--
============LICENSE_START=======================================================
Copyright (C) 2018 Ericsson. All rights reserved.
- Modifications Copyright (C) 2019-2021 Nordix Foundation.
+ Modifications Copyright (C) 2019-2022 Nordix Foundation.
Modifications Copyright (C) 2020 Bell Canada.
Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
================================================================================
@@ -35,6 +35,8 @@
<properties>
<policy.apex-pdp.version>2.4.0</policy.apex-pdp.version>
+ <policy.common.version>1.10.1-SNAPSHOT</policy.common.version>
+ <policy.models.version>2.6.1-SNAPSHOT</policy.models.version>
<webapp.dir>src/main/resources/webapp</webapp.dir>
<sonar.nodejs.executable>${project.basedir}/src/main/resources/webapp/node/node</sonar.nodejs.executable>
<sonar.sources>${project.basedir}/src/main/java,${project.basedir}/src/main/resources/webapp/js</sonar.sources>
@@ -44,25 +46,8 @@
<dependencies>
<dependency>
<groupId>org.onap.policy.common</groupId>
- <artifactId>policy-endpoints</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.onap.aaf.authz</groupId>
- <artifactId>aaf-cadi-aaf</artifactId>
- </exclusion>
- <exclusion>
- <groupId>com.att.nsa</groupId>
- <artifactId>cambriaClient</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId>
- <artifactId>dmaapClient</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
<artifactId>utils</artifactId>
+ <version>${policy.common.version}</version>
<exclusions>
<exclusion>
<groupId>com.worldturner.medeia</groupId>
@@ -104,19 +89,6 @@
<artifactId>commons-cli</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-text</artifactId>
- <version>1.9</version>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.apex-pdp.client</groupId>
- <artifactId>apex-client-common</artifactId>
- <version>${policy.apex-pdp.version}</version>
- <classifier>resources</classifier>
- <type>zip</type>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
@@ -126,11 +98,6 @@
<version>3.10.0</version>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- </dependency>
-
</dependencies>
<build>
diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java
index 0b777b6..b86df28 100644
--- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java
+++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2022 Nordix Foundation.
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
@@ -34,11 +34,9 @@
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
-import org.apache.commons.lang3.StringUtils;
import org.onap.policy.apex.model.modelapi.ApexApiResult;
import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
import org.onap.policy.common.utils.resources.TextFileUtils;
-import org.onap.policy.gui.editors.apex.rest.ApexEditorMain;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
@@ -233,16 +231,14 @@
/**
* Uploads a TOSCA Policy Model to a configured endpoint.
*
- * @param userid the userid to use for upload
+ * @param userId the userId to use for upload. If blank, the commandline
+ * parameter "upload-userid" is used.
* @return an ApexAPIResult that contains the operation status and success/error messages
*/
@GET
@Path("Model/Upload")
- public ApexApiResult uploadModel(@QueryParam("userId") final String userid) {
- if (!StringUtils.isBlank(userid)) {
- ApexEditorMain.getParameters().setUploadUserid(userid);
- }
- return processRestCommand(RestCommandType.MODEL, RestCommand.UPLOAD);
+ public ApexApiResult uploadModel(@QueryParam("userId") final String userId) {
+ return processRestCommand(RestCommandType.MODEL, RestCommand.UPLOAD, userId);
}
/**
diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java
index 38c7fec..18dc227 100644
--- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java
+++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2022 Nordix Foundation.
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
@@ -76,8 +76,6 @@
return listModel(session);
case DOWNLOAD:
return downloadModel(session);
- case UPLOAD:
- return uploadModel(session);
case DELETE:
return deleteModel(session);
default:
@@ -102,6 +100,8 @@
return createModel(session, jsonString);
case UPDATE:
return updateModel(session, jsonString);
+ case UPLOAD:
+ return uploadModel(session, jsonString);
default:
return getUnsupportedCommandResultMessage(session, commandType, command);
}
@@ -276,12 +276,14 @@
* Upload the model for this session to the configured URL.
*
* @param session the Apex model editing session
+ * @param userId the userId to use for upload. If blank, the commandline
+ * parameter "upload-userid" is used.
* @return a result indicating if the upload was successful or not
*/
- private ApexApiResult uploadModel(final RestSession session) {
+ private ApexApiResult uploadModel(final RestSession session, String userId) {
LOGGER.entry();
- ApexApiResult result = session.uploadModel();
+ ApexApiResult result = session.uploadModel(userId);
LOGGER.exit("Model/Download" + (result != null && result.isOk() ? OK : NOT_OK));
return result;
diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java
index 662c634..c41513f 100644
--- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java
+++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2022 Nordix Foundation.
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
@@ -200,9 +200,11 @@
/**
* Upload the apex model as a TOSCA service template YAML string to the configured URL.
*
+ * @param userId the userId to use for upload. If blank, the commandline
+ * parameter "upload-userid" is used.
* @return a result indicating if the upload was successful or not
*/
- public ApexApiResult uploadModel() {
+ public ApexApiResult uploadModel(final String userId) {
// Get the model in TOSCA format
ApexApiResult result = downloadModel();
if (result.isNok()) {
@@ -215,7 +217,7 @@
var policyModelUUid = apexModelBeingUploaded.getPolicyModel().getKeyInformation().get(policyModelKey)
.getUuid().toString();
- return new PolicyUploadHandler().doUpload(result.getMessage(), policyModelKey, policyModelUUid);
+ return new PolicyUploadHandler().doUpload(result.getMessage(), policyModelKey, policyModelUUid, userId);
}
/**
diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java
index ebbe3db..1766831 100644
--- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java
+++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java
@@ -1,6 +1,6 @@
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2020 Nordix Foundation
+ * Copyright (C) 2020-2022 Nordix Foundation
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
* ================================================================================
@@ -49,45 +49,50 @@
* @param toscaServiceTemplate the TOSCA service template
* @param policyModelKey the key of the policy model
* @param policyModelUuid the UUID of the policy model
+ * @param uploadUserId the userId to use for upload. If blank, the commandline
+ * parameter "upload-userid" is used.
* @return the result of the upload process
*/
public ApexApiResult doUpload(final String toscaServiceTemplate, final AxArtifactKey policyModelKey,
- final String policyModelUuid) {
+ final String policyModelUuid, String uploadUserId) {
LOGGER.entry();
- if (StringUtils.isBlank(ApexEditorMain.getParameters().getUploadUrl())) {
+ final String uploadUrl = ApexEditorMain.getParameters().getUploadUrl();
+ if (StringUtils.isBlank(uploadUrl)) {
final var apexApiResult = new ApexApiResult(Result.FAILED);
apexApiResult.addMessage("Model upload is disabled, parameter upload-url is not set on server");
LOGGER.exit(MODEL_UPLOAD_NOT_OK);
return apexApiResult;
+ }
+ if (StringUtils.isBlank(uploadUserId)) {
+ uploadUserId = ApexEditorMain.getParameters().getUploadUserid();
}
final var uploadPolicyRequestDto = new UploadPolicyRequestDto();
- uploadPolicyRequestDto.setUserId(ApexEditorMain.getParameters().getUploadUserid());
+ uploadPolicyRequestDto.setUserId(uploadUserId);
uploadPolicyRequestDto
.setFileData(Base64.getEncoder().encodeToString(toscaServiceTemplate.getBytes(StandardCharsets.UTF_8)));
uploadPolicyRequestDto.setFilename(
String.format("%s.%s.%s", policyModelUuid, policyModelKey.getName(), policyModelKey.getVersion()));
try {
- final var response = ClientBuilder.newClient().target(ApexEditorMain.getParameters().getUploadUrl())
+ final var response = ClientBuilder.newClient().target(uploadUrl)
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(uploadPolicyRequestDto, MediaType.APPLICATION_JSON));
if (response.getStatus() == 201) {
final var apexApiResult = new ApexApiResult(Result.SUCCESS);
- String.format("uploading Policy '%s' to URL '%s' with userId '%s' was successful",
- policyModelKey.getId(), ApexEditorMain.getParameters().getUploadUrl(),
- ApexEditorMain.getParameters().getUploadUserid());
+ apexApiResult.addMessage(
+ String.format("uploading Policy '%s' to URL '%s' with userId '%s' was successful",
+ policyModelKey.getId(), uploadUrl, uploadUserId));
LOGGER.exit("Model/Upload: OK");
return apexApiResult;
} else {
final var apexApiResult = new ApexApiResult(Result.FAILED);
apexApiResult.addMessage(
String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with status %s",
- policyModelKey.getId(), ApexEditorMain.getParameters().getUploadUrl(),
- ApexEditorMain.getParameters().getUploadUserid(), response.getStatus()));
+ policyModelKey.getId(), uploadUrl, uploadUserId, response.getStatus()));
LOGGER.exit(MODEL_UPLOAD_NOT_OK);
return apexApiResult;
}
@@ -95,8 +100,7 @@
final var apexApiResult = new ApexApiResult(Result.FAILED);
apexApiResult
.addMessage(String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with error %s",
- policyModelKey.getId(), ApexEditorMain.getParameters().getUploadUrl(),
- ApexEditorMain.getParameters().getUploadUserid(), e.getMessage()));
+ policyModelKey.getId(), uploadUrl, uploadUserId, e.getMessage()));
LOGGER.exit(MODEL_UPLOAD_NOT_OK);
return apexApiResult;
}
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionTest.java
index b2158ce..121faa0 100644
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionTest.java
+++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionTest.java
@@ -1,6 +1,6 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021-2022 Nordix Foundation.
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -139,7 +139,7 @@
final var toscaPath = Path.of("src/test/resources/models/PolicyModel.yaml");
final var toscaString = Files.readString(toscaPath);
restSession.loadFromString(toscaString);
- final var apexApiResult = restSession.uploadModel();
+ final var apexApiResult = restSession.uploadModel("");
assertThat(apexApiResult.isNok()).isTrue();
assertThat(apexApiResult.getMessage()).contains("Model upload is disabled");
}
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandlerTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandlerTest.java
index 0b4e863..4525f42 100644
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandlerTest.java
+++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandlerTest.java
@@ -29,6 +29,7 @@
import java.nio.file.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.ResponseProcessingException;
import javax.ws.rs.client.WebTarget;
@@ -38,6 +39,7 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
@@ -46,10 +48,12 @@
public class PolicyUploadHandlerTest {
+ private static final String CMDLINE_UPLOAD_USERID = "MyUser";
private PolicyUploadHandler uploadHandler;
private AxArtifactKey axArtifactKey;
private String toscaServiceTemplate;
private MockedStatic<ClientBuilder> clientBuilderMockedStatic;
+ private ArgumentCaptor<Entity<UploadPolicyRequestDto>> dtoEntityCaptor;
/**
* Prepares test environment.
@@ -78,12 +82,12 @@
@Test
public void testDoUploadNoUrl() {
- final String[] args = {"--upload-userid", "MyUser"};
+ final String[] args = {"--upload-userid", CMDLINE_UPLOAD_USERID};
final var outBaStream = new ByteArrayOutputStream();
final var outStream = new PrintStream(outBaStream);
new ApexEditorMain(args, outStream);
- final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "");
+ final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "", "");
assertThat(result.isNok()).isTrue();
assertThat(result.getMessage()).contains("Model upload is disable");
}
@@ -96,7 +100,7 @@
prepareApexEditorMain();
- final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "");
+ final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "", "");
assertThat(result.isNok()).isTrue();
assertThat(result.getMessage()).contains("failed with error");
@@ -111,7 +115,7 @@
prepareApexEditorMain();
- final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "");
+ final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "", "");
assertThat(result.isOk()).isTrue();
}
@@ -125,12 +129,41 @@
prepareApexEditorMain();
- final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "");
+ final var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "", "");
assertThat(result.isNok()).isTrue();
assertThat(result.getMessage()).contains("failed with status 500");
}
+ @Test
+ public void testDoUploadUserId() {
+ final var response = Mockito.mock(Response.class);
+ mockRsHttpClient(response);
+
+ Mockito.doReturn(201).when(response).getStatus();
+
+ prepareApexEditorMain();
+
+ // If uploadUserId is specified, that value should be in DTO.
+ var result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "",
+ "OverrideUser");
+ assertThat(result.isOk()).isTrue();
+ var dto = dtoEntityCaptor.getValue().getEntity();
+ assertThat(dto.getUserId()).isEqualTo("OverrideUser");
+
+ // If uploadUserId is blank, the value from command line parameter 'upload-userid' is used.
+ result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "", "");
+ assertThat(result.isOk()).isTrue();
+ dto = dtoEntityCaptor.getValue().getEntity();
+ assertThat(dto.getUserId()).isEqualTo(CMDLINE_UPLOAD_USERID);
+
+ // If uploadUserId is null, the value from command line parameter 'upload-userid' is used.
+ result = uploadHandler.doUpload(toscaServiceTemplate, axArtifactKey, "", null);
+ assertThat(result.isOk()).isTrue();
+ dto = dtoEntityCaptor.getValue().getEntity();
+ assertThat(dto.getUserId()).isEqualTo(CMDLINE_UPLOAD_USERID);
+ }
+
private void mockRsHttpClient(Response response) {
final var webTarget = Mockito.mock(WebTarget.class);
final var client = Mockito.mock(Client.class);
@@ -139,15 +172,17 @@
clientBuilderMockedStatic = Mockito.mockStatic(ClientBuilder.class);
+ dtoEntityCaptor = ArgumentCaptor.forClass(Entity.class);
+
Mockito.when(ClientBuilder.newClient()).thenReturn(client);
Mockito.when(client.target(ArgumentMatchers.anyString())).thenReturn(webTarget);
Mockito.when(webTarget.request(MediaType.APPLICATION_JSON)).thenReturn(invocationBuilder);
Mockito.when(webTarget.request(MediaType.APPLICATION_JSON)).thenReturn(invocationBuilder);
- Mockito.when(invocationBuilder.post(ArgumentMatchers.any())).thenReturn(response);
+ Mockito.when(invocationBuilder.post(dtoEntityCaptor.capture())).thenReturn(response);
}
private void prepareApexEditorMain() {
- final String[] args = {"--upload-userid", "MyUser", "--upload-url", "http://127.0.0.1"};
+ final String[] args = {"--upload-userid", CMDLINE_UPLOAD_USERID, "--upload-url", "http://127.0.0.1"};
final var outBaStream = new ByteArrayOutputStream();
final var outStream = new PrintStream(outBaStream);
new ApexEditorMain(args, outStream);
diff --git a/gui-editors/pom.xml b/gui-editors/pom.xml
index 7deee2d..3810af5 100644
--- a/gui-editors/pom.xml
+++ b/gui-editors/pom.xml
@@ -1,6 +1,6 @@
<!--
============LICENSE_START=======================================================
- Copyright (C) 2020 Nordix Foundation.
+ Copyright (C) 2020-2022 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -32,11 +32,6 @@
<name>${project.artifactId}</name>
<description>Web Client editors for PDP policies</description>
- <properties>
- <sonar.sources>${project.basedir}/src/main</sonar.sources>
- <sonar.exclusions>src/main/resources/webapp/js/edit_area/**/*,src/main/resources/webapp/js/jquery/**/*,src/main/resources/webapp/js/jquery-ui-1.12.1/**/*,src/main/resources/webapp/js/lib/**/*</sonar.exclusions>
- </properties>
-
<modules>
<module>gui-editor-apex</module>
</modules>
diff --git a/pom.xml b/pom.xml
index 4be0a92..d1f833c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy GUI
================================================================================
Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2020-2021 Nordix Foundation.
+ Modifications Copyright (C) 2020-2022 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -20,7 +20,7 @@
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@@ -40,8 +40,6 @@
<description>Code for all the Policy GUI's.</description>
<properties>
- <policy.common.version>1.10.1-SNAPSHOT</policy.common.version>
- <policy.models.version>2.6.1-SNAPSHOT</policy.models.version>
<jacoco.dataFile>${project.basedir}/../../target/code-coverage/jacoco-ut.exec</jacoco.dataFile>
<sonar.javascript.lcov.reportPaths>${project.basedir}/target/code-coverage/lcov.info</sonar.javascript.lcov.reportPaths>
</properties>
@@ -78,21 +76,6 @@
</site>
</distributionManagement>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>utils</artifactId>
- <version>${policy.common.version}</version>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>policy-endpoints</artifactId>
- <version>${policy.common.version}</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
<profiles>
<profile>
<!--This profile is used to store Eclipse m2e settings only. It has no