2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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 * ========================LICENSE_END===================================
20 import { animate, state, style, transition, trigger } from '@angular/animations';
21 import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
22 import { MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
23 import { MatMenuTrigger } from '@angular/material/menu';
24 import { JsonPointer } from 'angular6-json-schema-form';
25 import * as uuid from 'uuid';
26 import { PolicyInstance, PolicyType } from '../interfaces/policy.types';
27 import { PolicyService } from '../services/policy/policy.service';
28 import { ErrorDialogService } from '../services/ui/error-dialog.service';
29 import { NotificationService } from './../services/ui/notification.service';
30 import { UiService } from '../services/ui/ui.service';
31 import { HttpErrorResponse } from '@angular/common/http';
35 selector: 'rd-policy-instance-dialog',
36 templateUrl: './policy-instance-dialog.component.html',
37 styleUrls: ['./policy-instance-dialog.component.scss'],
39 trigger('expandSection', [
40 state('in', style({ height: '*' })),
41 transition(':enter', [
42 style({ height: 0 }), animate(100),
44 transition(':leave', [
45 style({ height: '*' }),
46 animate(100, style({ height: 0 })),
51 export class PolicyInstanceDialogComponent implements OnInit, AfterViewInit {
60 jsonFormStatusMessage = 'Loading form...';
61 jsonSchemaObject: any = {};
65 jsonFormOptions: any = {
66 addSubmit: false, // Add a submit button if layout does not have one
67 debug: false, // Don't show inline debugging information
68 loadExternalAssets: true, // Load external css and JavaScript for frameworks
69 returnEmptyFields: false, // Don't return values for empty input fields
70 setSchemaDefaults: true, // Always use schema defaults for empty fields
71 defautWidgetOptions: { feedback: true }, // Show inline feedback icons
74 liveFormData: any = {};
75 formValidationErrors: any;
78 @ViewChild(MatMenuTrigger, { static: true }) menuTrigger: MatMenuTrigger;
80 policyInstanceId: string; // null if not yet created
81 policyTypeName: string;
87 console.log('fetchRics ' + this.policyTypeName);
88 const self: PolicyInstanceDialogComponent = this;
89 this.dataService.getRics(this.policyTypeName).subscribe(
95 error(error: HttpErrorResponse) {
96 self.errorService.displayError('Fetching of rics failed: ' + error.message);
103 private dataService: PolicyService,
104 private errorService: ErrorDialogService,
105 private notificationService: NotificationService,
106 @Inject(MAT_DIALOG_DATA) private data,
107 private dialogRef: MatDialogRef<PolicyInstanceDialogComponent>,
108 private ui: UiService) {
109 this.formActive = false;
110 this.policyInstanceId = data.instanceId;
111 this.policyTypeName = data.name;
112 this.jsonSchemaObject = data.createSchema;
113 this.jsonObject = this.parseJson(data.instanceJson);
118 this.jsonFormStatusMessage = 'Init';
119 this.formActive = true;
120 this.ui.darkModeState.subscribe((isDark) => {
121 this.darkMode = isDark;
123 if (!this.policyInstanceId) {
132 if (this.policyInstanceId == null) {
133 this.policyInstanceId = uuid.v4();
135 const policyJson: string = this.prettyLiveFormData;
136 const self: PolicyInstanceDialogComponent = this;
137 this.dataService.putPolicy(this.policyTypeName, this.policyInstanceId, policyJson, this.ric).subscribe(
140 self.notificationService.success('Policy ' + self.policyTypeName + ':' + self.policyInstanceId + ' submitted');
142 error(error: HttpErrorResponse) {
143 self.errorService.displayError('Submit failed: ' + error.error);
150 this.dialogRef.close();
153 public onChanges(formData: any) {
154 this.liveFormData = formData;
157 get prettyLiveFormData() {
158 return JSON.stringify(this.liveFormData, null, 2);
161 get schemaAsString() {
162 return JSON.stringify(this.jsonSchemaObject, null, 2);
166 return JSON.stringify(this.jsonObject, null, 2);
169 isValid(isValid: boolean): void {
170 this.formIsValid = isValid;
173 validationErrors(validationErrors: any): void {
174 this.formValidationErrors = validationErrors;
177 get prettyValidationErrors() {
178 if (!this.formValidationErrors) { return null; }
179 const errorArray = [];
180 for (const error of this.formValidationErrors) {
181 const message = error.message;
182 const dataPathArray = JsonPointer.parse(error.dataPath);
183 if (dataPathArray.length) {
184 let field = dataPathArray[0];
185 for (let i = 1; i < dataPathArray.length; i++) {
186 const key = dataPathArray[i];
187 field += /^\d+$/.test(key) ? `[${key}]` : `.${key}`;
189 errorArray.push(`${field}: ${message}`);
191 errorArray.push(message);
194 return errorArray.join('<br>');
197 private parseJson(str: string): string {
200 return JSON.parse(str);
202 } catch (jsonError) {
203 this.jsonFormStatusMessage =
205 'parser returned:\n\n' + jsonError;
210 public toggleVisible(item: string) {
211 this.isVisible[item] = !this.isVisible[item];
215 export function getPolicyDialogProperties(policyType: PolicyType, instance: PolicyInstance, darkMode: boolean): MatDialogConfig {
216 const createSchema = policyType.schemaObject;
217 const instanceId = instance ? instance.id : null;
218 const instanceJson = instance ? instance.json : null;
219 const name = policyType.name;
220 const ric = instance ? instance.ric : null;
227 panelClass: darkMode ? 'dark-theme' : '',