aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-ui/src/nfvo-utils
diff options
context:
space:
mode:
authorEinav Weiss Keidar <einavw@amdocs.com>2018-03-20 14:45:40 +0200
committerAvi Gaffa <avi.gaffa@amdocs.com>2018-03-20 13:52:31 +0000
commit7fdf733a64670fceefc3ded35cfa581e1c458179 (patch)
treeb3623ac9a331473830cb0167c0b487f2a176427c /openecomp-ui/src/nfvo-utils
parentc7916a4e5955ccc5f0f5252307363b791ec5c7b9 (diff)
Adding Prettier and fixing up eslint version
Issue-ID: SDC-1094 Change-Id: Ie83ad95a03899345dd90235daf0323cbe3bc6afd Signed-off-by: Einav Weiss Keidar <einavw@amdocs.com>
Diffstat (limited to 'openecomp-ui/src/nfvo-utils')
-rw-r--r--openecomp-ui/src/nfvo-utils/DirectedGraph.js44
-rw-r--r--openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js103
-rw-r--r--openecomp-ui/src/nfvo-utils/KeyMirror.js43
-rw-r--r--openecomp-ui/src/nfvo-utils/RestAPIUtil.js231
-rw-r--r--openecomp-ui/src/nfvo-utils/ShowFileSaveDialog.js69
-rw-r--r--openecomp-ui/src/nfvo-utils/UUID.js60
-rw-r--r--openecomp-ui/src/nfvo-utils/Validator.js288
-rw-r--r--openecomp-ui/src/nfvo-utils/WebSocketUtil.js65
-rw-r--r--openecomp-ui/src/nfvo-utils/getValue.js54
-rw-r--r--openecomp-ui/src/nfvo-utils/i18n/i18n.js132
-rw-r--r--openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js64
-rw-r--r--openecomp-ui/src/nfvo-utils/json/JSONPointer.js79
-rw-r--r--openecomp-ui/src/nfvo-utils/json/JSONSchema.js489
-rw-r--r--openecomp-ui/src/nfvo-utils/sortByStringProperty.js4
14 files changed, 951 insertions, 774 deletions
diff --git a/openecomp-ui/src/nfvo-utils/DirectedGraph.js b/openecomp-ui/src/nfvo-utils/DirectedGraph.js
index 197625a013..bdaf08b995 100644
--- a/openecomp-ui/src/nfvo-utils/DirectedGraph.js
+++ b/openecomp-ui/src/nfvo-utils/DirectedGraph.js
@@ -15,31 +15,31 @@
*/
export default class Graph {
- constructor() {
- this.nodes = {};
- }
+ constructor() {
+ this.nodes = {};
+ }
- addNode(node) {
- this.nodes[node] = [];
- }
+ addNode(node) {
+ this.nodes[node] = [];
+ }
- hasNode(node) {
- return this.nodes.hasOwnProperty(node);
- }
+ hasNode(node) {
+ return this.nodes.hasOwnProperty(node);
+ }
- addEdge(firstNode, secondNode, payload) {
- if (!this.hasNode(firstNode)) {
- this.addNode(firstNode);
- }
+ addEdge(firstNode, secondNode, payload) {
+ if (!this.hasNode(firstNode)) {
+ this.addNode(firstNode);
+ }
- if (!this.hasNode(secondNode)) {
- this.addNode(secondNode);
- }
+ if (!this.hasNode(secondNode)) {
+ this.addNode(secondNode);
+ }
- this.nodes[firstNode].push({...payload, target: secondNode});
- }
+ this.nodes[firstNode].push({ ...payload, target: secondNode });
+ }
- getEdges(node) {
- return this.nodes[node];
- }
-} \ No newline at end of file
+ getEdges(node) {
+ return this.nodes[node];
+ }
+}
diff --git a/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js b/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js
index 13dfb1f0ab..5c55855027 100644
--- a/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js
+++ b/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js
@@ -15,62 +15,71 @@
*/
import store from 'sdc-app/AppStore.js';
import React from 'react';
-import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js';
+import { actionTypes as modalActionTypes } from 'nfvo-components/modal/GlobalModalConstants.js';
import i18n from 'nfvo-utils/i18n/i18n.js';
import SubmitErrorResponse from 'nfvo-components/SubmitErrorResponse.jsx';
function showVariablesInMessage(variables, msg) {
- let regex;
- variables.forEach((value, index) => {
- value = value.replace(';', ',');
- regex = new RegExp('\'\%' + (index + 1) + '\'');
- msg = msg.replace(regex, value);
- });
- return msg;
+ let regex;
+ variables.forEach((value, index) => {
+ value = value.replace(';', ',');
+ regex = new RegExp("'%" + (index + 1) + "'");
+ msg = msg.replace(regex, value);
+ });
+ return msg;
}
function parseCatalogExceptionObject(responseJSON) {
- let title, msg;
- if (responseJSON.requestError && responseJSON.requestError.policyException) {
- title = 'Error: ' + responseJSON.requestError.policyException.messageId;
- msg = responseJSON.requestError.policyException.text;
- }
- else if (responseJSON.requestError && responseJSON.requestError.serviceException) {
- title = 'Error: ' + responseJSON.requestError.serviceException.messageId;
- msg = responseJSON.requestError.serviceException.text;
- let {variables} = responseJSON.requestError.serviceException;
- if (variables) {
- msg = showVariablesInMessage(variables, msg);
- }
- }
- else if (responseJSON.uploadDataErrors) {
- title = i18n('Error: Upload Data Error');
- msg = (<SubmitErrorResponse validationResponse={{uploadDataErrors: responseJSON.uploadDataErrors}} />);
- }
- else {
- title = responseJSON.status;
- msg = responseJSON.message;
- }
- return {title, msg};
+ let title, msg;
+ if (
+ responseJSON.requestError &&
+ responseJSON.requestError.policyException
+ ) {
+ title = 'Error: ' + responseJSON.requestError.policyException.messageId;
+ msg = responseJSON.requestError.policyException.text;
+ } else if (
+ responseJSON.requestError &&
+ responseJSON.requestError.serviceException
+ ) {
+ title =
+ 'Error: ' + responseJSON.requestError.serviceException.messageId;
+ msg = responseJSON.requestError.serviceException.text;
+ let { variables } = responseJSON.requestError.serviceException;
+ if (variables) {
+ msg = showVariablesInMessage(variables, msg);
+ }
+ } else if (responseJSON.uploadDataErrors) {
+ title = i18n('Error: Upload Data Error');
+ msg = (
+ <SubmitErrorResponse
+ validationResponse={{
+ uploadDataErrors: responseJSON.uploadDataErrors
+ }}
+ />
+ );
+ } else {
+ title = responseJSON.status;
+ msg = responseJSON.message;
+ }
+ return { title, msg };
}
-var errorResponseHandler = (error) => {
- let errorData;
- if (error.data) {
- errorData = parseCatalogExceptionObject(error.data);
- }
- else {
- errorData = {
- title: error.statusText,
- msg: error.responseText ? error.responseText : i18n('GENERIC_ERROR'),
- };
- }
- store.dispatch({
- type: modalActionTypes.GLOBAL_MODAL_ERROR,
- data: {
- ...errorData
- }
- });
+var errorResponseHandler = error => {
+ let errorData;
+ if (error.data) {
+ errorData = parseCatalogExceptionObject(error.data);
+ } else {
+ errorData = {
+ title: error.statusText,
+ msg: error.responseText ? error.responseText : i18n('GENERIC_ERROR')
+ };
+ }
+ store.dispatch({
+ type: modalActionTypes.GLOBAL_MODAL_ERROR,
+ data: {
+ ...errorData
+ }
+ });
};
export default errorResponseHandler;
diff --git a/openecomp-ui/src/nfvo-utils/KeyMirror.js b/openecomp-ui/src/nfvo-utils/KeyMirror.js
index 220fe07430..dc351af57c 100644
--- a/openecomp-ui/src/nfvo-utils/KeyMirror.js
+++ b/openecomp-ui/src/nfvo-utils/KeyMirror.js
@@ -13,27 +13,26 @@
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
-var keyMirror = function (obj) {
- var ret = {};
- var key;
- var val;
- if (!(obj instanceof Object && !Array.isArray(obj))) {
- throw new Error('keyMirror(...): Argument must be an object.');
- }
- for (key in obj) {
- if (obj.hasOwnProperty(key)) {
- val = obj[key];
- if (val instanceof Object) {
- ret[key] = keyMirror(obj[key]);
- } else if(val !== null && val !== undefined){
- ret[key] = val;
- }
- else {
- ret[key] = Symbol(key);
- }
- }
- }
- return Object.freeze(ret);
+var keyMirror = function(obj) {
+ var ret = {};
+ var key;
+ var val;
+ if (!(obj instanceof Object && !Array.isArray(obj))) {
+ throw new Error('keyMirror(...): Argument must be an object.');
+ }
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ val = obj[key];
+ if (val instanceof Object) {
+ ret[key] = keyMirror(obj[key]);
+ } else if (val !== null && val !== undefined) {
+ ret[key] = val;
+ } else {
+ ret[key] = Symbol(key);
+ }
+ }
+ }
+ return Object.freeze(ret);
};
-export default keyMirror; \ No newline at end of file
+export default keyMirror;
diff --git a/openecomp-ui/src/nfvo-utils/RestAPIUtil.js b/openecomp-ui/src/nfvo-utils/RestAPIUtil.js
index 5b07986390..1a5817de66 100644
--- a/openecomp-ui/src/nfvo-utils/RestAPIUtil.js
+++ b/openecomp-ui/src/nfvo-utils/RestAPIUtil.js
@@ -18,7 +18,7 @@ import md5 from 'md5';
import axios from 'axios';
import store from 'sdc-app/AppStore.js';
-import {actionTypes as LoaderConstants} from 'nfvo-components/loader/LoaderConstants.js';
+import { actionTypes as LoaderConstants } from 'nfvo-components/loader/LoaderConstants.js';
import Configuration from 'sdc-app/config/Configuration.js';
import errorResponseHandler from './ErrorResponseHandler.js';
@@ -39,124 +39,133 @@ const STORAGE_AUTH_KEY = 'sdc-auth-token';
const REQUEST_ID_HEADER = 'X-ECOMP-RequestID';
const CONTENT_MD5_HEADER = 'Content-MD5';
-
function applySecurity(options, data) {
- let headers = options.headers || (options.headers = {});
-
- let authToken = localStorage.getItem(STORAGE_AUTH_KEY);
- if (authToken) {
- headers[AUTHORIZATION_HEADER] = authToken;
- }
-
- let catalogApiHeaders = Configuration.get('CatalogApiHeaders'),
- catalogUidHeader = catalogApiHeaders && catalogApiHeaders.userId;
- if (catalogUidHeader) {
- headers[catalogUidHeader.name] = catalogUidHeader.value;
- }
-
- headers[REQUEST_ID_HEADER] = uuid.create().toString();
- if (options.md5) {
- let headers = options.headers;
- headers[CONTENT_MD5_HEADER] = window.btoa(md5(JSON.stringify(data)).toLowerCase());
- }
+ let headers = options.headers || (options.headers = {});
+
+ let authToken = localStorage.getItem(STORAGE_AUTH_KEY);
+ if (authToken) {
+ headers[AUTHORIZATION_HEADER] = authToken;
+ }
+
+ let catalogApiHeaders = Configuration.get('CatalogApiHeaders'),
+ catalogUidHeader = catalogApiHeaders && catalogApiHeaders.userId;
+ if (catalogUidHeader) {
+ headers[catalogUidHeader.name] = catalogUidHeader.value;
+ }
+
+ headers[REQUEST_ID_HEADER] = uuid.create().toString();
+ if (options.md5) {
+ let headers = options.headers;
+ headers[CONTENT_MD5_HEADER] = window.btoa(
+ md5(JSON.stringify(data)).toLowerCase()
+ );
+ }
}
-
function handleSuccess(responseHeaders, requestHeaders) {
- let authToken = responseHeaders[AUTHORIZATION_HEADER];
- let prevToken = requestHeaders && requestHeaders[AUTHORIZATION_HEADER];
- if (authToken && authToken !== prevToken) {
- if (authToken === 'null') {
- localStorage.removeItem(STORAGE_AUTH_KEY);
- } else {
- localStorage.setItem(STORAGE_AUTH_KEY, authToken);
- }
- }
+ let authToken = responseHeaders[AUTHORIZATION_HEADER];
+ let prevToken = requestHeaders && requestHeaders[AUTHORIZATION_HEADER];
+ if (authToken && authToken !== prevToken) {
+ if (authToken === 'null') {
+ localStorage.removeItem(STORAGE_AUTH_KEY);
+ } else {
+ localStorage.setItem(STORAGE_AUTH_KEY, authToken);
+ }
+ }
}
-class RestAPIUtil {
- handleRequest(url, type, options = {}, data){
- if (DEBUG) {
- console.log('axios --> Making REST call (' + type + '): ' + url);
- }
-
- applySecurity(options, data);
-
- // TODO see ig necessary or in transformrequest funtion
- if (type === POST || type === PUT) {
- if (data instanceof FormData) {
- options.headers.contentType = MULTIPART_FORM_DATA;
- }
- else {
- options.headers.contentType = APPLICATION_JSON;
-// config.data = JSON.stringify(data);
- }
-
- } else {
- data = null;
- }
-
- let config = {
- method: type,
- url: url,
- headers : options.headers,
- data : data
- };
-
- store.dispatch({type: LoaderConstants.SEND_REQUEST, url: url});
- if (options.dataType === BINARY) {
- config.responseType = 'arraybuffer';
- return axios(config).
- then(result => {
- store.dispatch({type: LoaderConstants.RECEIVE_RESPONSE, url : result.config.url});
- return ({
- blob : new Blob([result.data] ),
- headers : result.headers
- });
- }).catch(error => {
- store.dispatch({type: LoaderConstants.RECEIVE_RESPONSE, url : error.config.url});
- errorResponseHandler(error.response); });
- } else {
- return axios(config).
- then(result => {
- store.dispatch({type: LoaderConstants.RECEIVE_RESPONSE, url : result.config.url});
- handleSuccess(result.headers, result.config.headers);
- return result.data;
- }).catch(error => {
- store.dispatch({type: LoaderConstants.RECEIVE_RESPONSE, url : error.config.url});
- errorResponseHandler(error.response);
- return Promise.reject({responseJSON: error.response.data});
- });
- }
-
- }
-
- fetch(url, options) {
- return this.handleRequest(url, GET, options);
- }
-
- get(url, options) {
- return this.fetch(url, options);
- }
-
- post(url, data, options) {
- return this.handleRequest(url, POST, options, data);
- }
-
- put(url, data, options) {
- return this.handleRequest(url, PUT, options, data);
- }
-
- destroy(url, options) {
- return this.handleRequest(url, DELETE, options);
- }
-
-
-
+class RestAPIUtil {
+ handleRequest(url, type, options = {}, data) {
+ if (DEBUG) {
+ console.log('axios --> Making REST call (' + type + '): ' + url);
+ }
+
+ applySecurity(options, data);
+
+ // TODO see ig necessary or in transformrequest funtion
+ if (type === POST || type === PUT) {
+ if (data instanceof FormData) {
+ options.headers.contentType = MULTIPART_FORM_DATA;
+ } else {
+ options.headers.contentType = APPLICATION_JSON;
+ // config.data = JSON.stringify(data);
+ }
+ } else {
+ data = null;
+ }
+
+ let config = {
+ method: type,
+ url: url,
+ headers: options.headers,
+ data: data
+ };
+
+ store.dispatch({ type: LoaderConstants.SEND_REQUEST, url: url });
+ if (options.dataType === BINARY) {
+ config.responseType = 'arraybuffer';
+ return axios(config)
+ .then(result => {
+ store.dispatch({
+ type: LoaderConstants.RECEIVE_RESPONSE,
+ url: result.config.url
+ });
+ return {
+ blob: new Blob([result.data]),
+ headers: result.headers
+ };
+ })
+ .catch(error => {
+ store.dispatch({
+ type: LoaderConstants.RECEIVE_RESPONSE,
+ url: error.config.url
+ });
+ errorResponseHandler(error.response);
+ });
+ } else {
+ return axios(config)
+ .then(result => {
+ store.dispatch({
+ type: LoaderConstants.RECEIVE_RESPONSE,
+ url: result.config.url
+ });
+ handleSuccess(result.headers, result.config.headers);
+ return result.data;
+ })
+ .catch(error => {
+ store.dispatch({
+ type: LoaderConstants.RECEIVE_RESPONSE,
+ url: error.config.url
+ });
+ errorResponseHandler(error.response);
+ return Promise.reject({
+ responseJSON: error.response.data
+ });
+ });
+ }
+ }
+
+ fetch(url, options) {
+ return this.handleRequest(url, GET, options);
+ }
+
+ get(url, options) {
+ return this.fetch(url, options);
+ }
+
+ post(url, data, options) {
+ return this.handleRequest(url, POST, options, data);
+ }
+
+ put(url, data, options) {
+ return this.handleRequest(url, PUT, options, data);
+ }
+
+ destroy(url, options) {
+ return this.handleRequest(url, DELETE, options);
+ }
}
const instance = new RestAPIUtil();
-
-
export default instance;
diff --git a/openecomp-ui/src/nfvo-utils/ShowFileSaveDialog.js b/openecomp-ui/src/nfvo-utils/ShowFileSaveDialog.js
index bddd49c700..990701c6f0 100644
--- a/openecomp-ui/src/nfvo-utils/ShowFileSaveDialog.js
+++ b/openecomp-ui/src/nfvo-utils/ShowFileSaveDialog.js
@@ -15,35 +15,48 @@
*/
function getTimestampString() {
- let date = new Date();
- let z = n => n < 10 ? '0' + n : n;
- return `${date.getFullYear()}-${z(date.getMonth())}-${z(date.getDate())}_${z(date.getHours())}-${z(date.getMinutes())}`;
+ let date = new Date();
+ let z = n => (n < 10 ? '0' + n : n);
+ return `${date.getFullYear()}-${z(date.getMonth())}-${z(
+ date.getDate()
+ )}_${z(date.getHours())}-${z(date.getMinutes())}`;
}
+export default function showFileSaveDialog({
+ blob,
+ headers,
+ defaultFilename,
+ addTimestamp
+}) {
+ let filename;
+ let contentDisposition = headers['content-disposition']
+ ? headers['content-disposition']
+ : '';
+ let match = contentDisposition
+ ? contentDisposition.match(/filename=(.*?)(;|$)/)
+ : false;
+ if (match) {
+ filename = match[1];
+ } else {
+ filename = defaultFilename;
+ }
-export default function showFileSaveDialog({blob, headers, defaultFilename, addTimestamp}) {
- let filename;
- let contentDisposition = headers['content-disposition'] ? headers['content-disposition'] : '';
- let match = contentDisposition ? contentDisposition.match(/filename=(.*?)(;|$)/) : false;
- if (match) {
- filename = match[1];
- } else {
- filename = defaultFilename;
- }
+ if (addTimestamp) {
+ filename = filename.replace(
+ /(^.*?)\.([^.]+$)/,
+ `$1_${getTimestampString()}.$2`
+ );
+ }
- if (addTimestamp) {
- filename = filename.replace(/(^.*?)\.([^.]+$)/, `$1_${getTimestampString()}.$2`);
- }
-
- let link = document.createElement('a');
- let url = URL.createObjectURL(blob);
- link.href = url;
- link.download = filename;
- link.style.display = 'none';
- document.body.appendChild(link);
- link.click();
- setTimeout(function(){
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
- }, 0);
-};
+ let link = document.createElement('a');
+ let url = URL.createObjectURL(blob);
+ link.href = url;
+ link.download = filename;
+ link.style.display = 'none';
+ document.body.appendChild(link);
+ link.click();
+ setTimeout(function() {
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+ }, 0);
+}
diff --git a/openecomp-ui/src/nfvo-utils/UUID.js b/openecomp-ui/src/nfvo-utils/UUID.js
index e1d4c54b1f..37de994201 100644
--- a/openecomp-ui/src/nfvo-utils/UUID.js
+++ b/openecomp-ui/src/nfvo-utils/UUID.js
@@ -15,39 +15,39 @@
*/
import UUID from 'uuid-js';
-let toCustomUUID = (uuid) => {
- return 'U' + uuid.replace(/-/g, '');
+let toCustomUUID = uuid => {
+ return 'U' + uuid.replace(/-/g, '');
};
let getUUID = function(num, isSync) {
- if (isSync) {
- let uuid;
- if (!num) {
- uuid = toCustomUUID(UUID.create().toString());
- } else {
- uuid = [];
- for (var i = 0; i < num; i++) {
- uuid[i] = toCustomUUID(UUID.create().toString());
- }
- }
- if (num === 1) {
- return uuid[0];
- } else {
- return uuid;
- }
- }
- return new Promise(resolve => {
- let uuid;
- if (!num) {
- uuid = toCustomUUID(UUID.create().toString());
- } else {
- uuid = [];
- for (var i = 0; i < num; i++) {
- uuid[i] = toCustomUUID(UUID.create().toString());
- }
- }
- setTimeout(() => resolve(uuid), 100);
- });
+ if (isSync) {
+ let uuid;
+ if (!num) {
+ uuid = toCustomUUID(UUID.create().toString());
+ } else {
+ uuid = [];
+ for (var i = 0; i < num; i++) {
+ uuid[i] = toCustomUUID(UUID.create().toString());
+ }
+ }
+ if (num === 1) {
+ return uuid[0];
+ } else {
+ return uuid;
+ }
+ }
+ return new Promise(resolve => {
+ let uuid;
+ if (!num) {
+ uuid = toCustomUUID(UUID.create().toString());
+ } else {
+ uuid = [];
+ for (var i = 0; i < num; i++) {
+ uuid[i] = toCustomUUID(UUID.create().toString());
+ }
+ }
+ setTimeout(() => resolve(uuid), 100);
+ });
};
export default getUUID;
diff --git a/openecomp-ui/src/nfvo-utils/Validator.js b/openecomp-ui/src/nfvo-utils/Validator.js
index 0cb1943d66..324198ef2e 100644
--- a/openecomp-ui/src/nfvo-utils/Validator.js
+++ b/openecomp-ui/src/nfvo-utils/Validator.js
@@ -18,119 +18,189 @@ import * as ValidatorJS from 'validator';
import i18n from 'nfvo-utils/i18n/i18n.js';
class Validator {
- static get globalValidationFunctions() {
- return {
- required: value => {
- return typeof value === 'string' ? value.replace(/\s+/g, '') !== '' : value !== '';
- },
- requiredChooseOption: value => value !== '',
- maxLength: (value, length) => ValidatorJS.isLength(value, {max: length}),
- minLength: (value, length) => ValidatorJS.isLength(value, {min: length}),
- pattern: (value, pattern) => ValidatorJS.matches(value, pattern),
- numeric: value => {
- if (value === '') {
- // to allow empty value which is not zero
- return true;
- }
- return ValidatorJS.isNumeric(value);
- },
- maximum: (value, maxValue) => {return (value === undefined) ? true : (value <= maxValue);},
- minimum: (value, minValue) => {return (value === undefined) ? true : (value >= minValue);},
- maximumExclusive: (value, maxValue) => {return (value === undefined) ? true : (value < maxValue);},
- minimumExclusive: (value, minValue) => {return (value === undefined) ? true : (value > minValue);},
- alphanumeric: value => ValidatorJS.isAlphanumeric(value),
- alphanumericWithSpaces: value => ValidatorJS.isAlphanumeric(value.replace(/ /g, '')),
- validateName: value => ValidatorJS.isAlphanumeric(value.replace(/\s|\.|\_|\-/g, ''), 'en-US'),
- validateVendorName: value => ValidatorJS.isAlphanumeric(value.replace(/[\x7F-\xFF]|\s/g, ''), 'en-US'),
- freeEnglishText: value => ValidatorJS.isAlphanumeric(value.replace(/\s|\.|\_|\-|\,|\(|\)|\?/g, ''), 'en-US'),
- email: value => ValidatorJS.isEmail(value),
- ip: value => ValidatorJS.isIP(value),
- url: value => ValidatorJS.isURL(value),
- alphanumericWithUnderscores: value => ValidatorJS.isAlphanumeric(value.replace(/_/g, '')),
- requiredChoiceWithOther: (value, otherValue) => {
- let chosen = value.choice;
- // if we have an empty multiple select we have a problem since it's required
- let validationFunc = this.globalValidationFunctions['required'];
- if (value.choices) {
- if (value.choices.length === 0) {
- return false;
- } else {
- // continuing validation with the first chosen value in case we have the 'Other' field
- chosen = value.choices[0];
- }
- }
- if (chosen !== otherValue) {
- return validationFunc(chosen, true);
- } else { // when 'Other' was chosen, validate other value
- return validationFunc(value.other, true);
- }
- }
- };
- }
+ static get globalValidationFunctions() {
+ return {
+ required: value => {
+ return typeof value === 'string'
+ ? value.replace(/\s+/g, '') !== ''
+ : value !== '';
+ },
+ requiredChooseOption: value => value !== '',
+ maxLength: (value, length) =>
+ ValidatorJS.isLength(value, { max: length }),
+ minLength: (value, length) =>
+ ValidatorJS.isLength(value, { min: length }),
+ pattern: (value, pattern) => ValidatorJS.matches(value, pattern),
+ numeric: value => {
+ if (value === '') {
+ // to allow empty value which is not zero
+ return true;
+ }
+ return ValidatorJS.isNumeric(value);
+ },
+ maximum: (value, maxValue) => {
+ return value === undefined ? true : value <= maxValue;
+ },
+ minimum: (value, minValue) => {
+ return value === undefined ? true : value >= minValue;
+ },
+ maximumExclusive: (value, maxValue) => {
+ return value === undefined ? true : value < maxValue;
+ },
+ minimumExclusive: (value, minValue) => {
+ return value === undefined ? true : value > minValue;
+ },
+ alphanumeric: value => ValidatorJS.isAlphanumeric(value),
+ alphanumericWithSpaces: value =>
+ ValidatorJS.isAlphanumeric(value.replace(/ /g, '')),
+ validateName: value =>
+ ValidatorJS.isAlphanumeric(
+ value.replace(/\s|\.|\_|\-/g, ''),
+ 'en-US'
+ ),
+ validateVendorName: value =>
+ ValidatorJS.isAlphanumeric(
+ value.replace(/[\x7F-\xFF]|\s/g, ''),
+ 'en-US'
+ ),
+ freeEnglishText: value =>
+ ValidatorJS.isAlphanumeric(
+ value.replace(/\s|\.|\_|\-|\,|\(|\)|\?/g, ''),
+ 'en-US'
+ ),
+ email: value => ValidatorJS.isEmail(value),
+ ip: value => ValidatorJS.isIP(value),
+ url: value => ValidatorJS.isURL(value),
+ alphanumericWithUnderscores: value =>
+ ValidatorJS.isAlphanumeric(value.replace(/_/g, '')),
+ requiredChoiceWithOther: (value, otherValue) => {
+ let chosen = value.choice;
+ // if we have an empty multiple select we have a problem since it's required
+ let validationFunc = this.globalValidationFunctions['required'];
+ if (value.choices) {
+ if (value.choices.length === 0) {
+ return false;
+ } else {
+ // continuing validation with the first chosen value in case we have the 'Other' field
+ chosen = value.choices[0];
+ }
+ }
+ if (chosen !== otherValue) {
+ return validationFunc(chosen, true);
+ } else {
+ // when 'Other' was chosen, validate other value
+ return validationFunc(value.other, true);
+ }
+ }
+ };
+ }
- static get globalValidationMessagingFunctions() {
- return {
- required: () => i18n('Field is required'),
- requiredChooseOption: () => i18n('Field should have one of these options'),
- requiredChoiceWithOther: () => i18n('Field is required'),
- maxLength: (value, maxLength) => i18n('Field value has exceeded it\'s limit, {maxLength}. current length: {length}', {
- length: value.length,
- maxLength
- }),
- minLength: (value, minLength) => i18n('Field value should contain at least {minLength} characters.', {minLength: minLength}),
- pattern: (value, pattern) => i18n('Field value should match the pattern: {pattern}.', {pattern: pattern}),
- numeric: () => i18n('Field value should contain numbers only.'),
- maximum: (value, maxValue) => i18n('Field value should be less or equal to: {maxValue}.', {maxValue: maxValue}),
- minimum: (value, minValue) => i18n('Field value should be at least: {minValue}.', {minValue: minValue.toString()}),
- maximumExclusive: (value, maxValue) => i18n('Field value should be less than: {maxValue}.', {maxValue: maxValue}),
- minimumExclusive: (value, minValue) => i18n('Field value should be more than: {minValue}.', {minValue: minValue.toString()}),
- alphanumeric: () => i18n('Field value should contain letters or digits only.'),
- alphanumericWithSpaces: () => i18n('Field value should contain letters, digits or spaces only.'),
- validateName: ()=> i18n('Field value should contain English letters, digits , spaces, underscores, dashes and dots only.'),
- validateVendorName: ()=> i18n('Field value should contain English letters digits and spaces only.'),
- freeEnglishText: ()=> i18n('Field value should contain English letters, digits , spaces, underscores, dashes and dots only.'),
- email: () => i18n('Field value should be a valid email address.'),
- ip: () => i18n('Field value should be a valid ip address.'),
- url: () => i18n('Field value should be a valid url address.'),
- general: () => i18n('Field value is invalid.'),
- alphanumericWithUnderscores: () => i18n('Field value should contain letters, digits or _ only.')
- };
- }
+ static get globalValidationMessagingFunctions() {
+ return {
+ required: () => i18n('Field is required'),
+ requiredChooseOption: () =>
+ i18n('Field should have one of these options'),
+ requiredChoiceWithOther: () => i18n('Field is required'),
+ maxLength: (value, maxLength) =>
+ i18n(
+ "Field value has exceeded it's limit, {maxLength}. current length: {length}",
+ {
+ length: value.length,
+ maxLength
+ }
+ ),
+ minLength: (value, minLength) =>
+ i18n(
+ 'Field value should contain at least {minLength} characters.',
+ {
+ minLength: minLength
+ }
+ ),
+ pattern: (value, pattern) =>
+ i18n('Field value should match the pattern: {pattern}.', {
+ pattern: pattern
+ }),
+ numeric: () => i18n('Field value should contain numbers only.'),
+ maximum: (value, maxValue) =>
+ i18n('Field value should be less or equal to: {maxValue}.', {
+ maxValue: maxValue
+ }),
+ minimum: (value, minValue) =>
+ i18n('Field value should be at least: {minValue}.', {
+ minValue: minValue.toString()
+ }),
+ maximumExclusive: (value, maxValue) =>
+ i18n('Field value should be less than: {maxValue}.', {
+ maxValue: maxValue
+ }),
+ minimumExclusive: (value, minValue) =>
+ i18n('Field value should be more than: {minValue}.', {
+ minValue: minValue.toString()
+ }),
+ alphanumeric: () =>
+ i18n('Field value should contain letters or digits only.'),
+ alphanumericWithSpaces: () =>
+ i18n(
+ 'Field value should contain letters, digits or spaces only.'
+ ),
+ validateName: () =>
+ i18n(
+ 'Field value should contain English letters, digits , spaces, underscores, dashes and dots only.'
+ ),
+ validateVendorName: () =>
+ i18n(
+ 'Field value should contain English letters digits and spaces only.'
+ ),
+ freeEnglishText: () =>
+ i18n(
+ 'Field value should contain English letters, digits , spaces, underscores, dashes and dots only.'
+ ),
+ email: () => i18n('Field value should be a valid email address.'),
+ ip: () => i18n('Field value should be a valid ip address.'),
+ url: () => i18n('Field value should be a valid url address.'),
+ general: () => i18n('Field value is invalid.'),
+ alphanumericWithUnderscores: () =>
+ i18n('Field value should contain letters, digits or _ only.')
+ };
+ }
- static validateItem(value, data, type) {
- let validationFunc = this.globalValidationFunctions[type];
- const isValid = validationFunc(value, data);
- let errorText = '';
- if (!isValid) {
- errorText = this.globalValidationMessagingFunctions[type](value, data);
- }
- return {
- isValid,
- errorText
- };
- }
+ static validateItem(value, data, type) {
+ let validationFunc = this.globalValidationFunctions[type];
+ const isValid = validationFunc(value, data);
+ let errorText = '';
+ if (!isValid) {
+ errorText = this.globalValidationMessagingFunctions[type](
+ value,
+ data
+ );
+ }
+ return {
+ isValid,
+ errorText
+ };
+ }
- static validate(fieldName, value, validations, state, customValidations) {
- let result = { isValid: true, errorText: '' };
- for (let validation of validations) {
- result = this.validateItem(value, validation.data, validation.type);
- if (!result.isValid) {
- return result;
- }
- }
- if (customValidations) {
- let validationFunc = customValidations[fieldName];
- if (validationFunc) {
- result = validationFunc(value, state);
- }
- }
- return result;
- }
+ static validate(fieldName, value, validations, state, customValidations) {
+ let result = { isValid: true, errorText: '' };
+ for (let validation of validations) {
+ result = this.validateItem(value, validation.data, validation.type);
+ if (!result.isValid) {
+ return result;
+ }
+ }
+ if (customValidations) {
+ let validationFunc = customValidations[fieldName];
+ if (validationFunc) {
+ result = validationFunc(value, state);
+ }
+ }
+ return result;
+ }
- static isItemNameAlreadyExistsInList({itemId, itemName, list}) {
- itemName = itemName.toLowerCase();
- return list[itemName] && list[itemName] !== itemId;
- }
+ static isItemNameAlreadyExistsInList({ itemId, itemName, list }) {
+ itemName = itemName.toLowerCase();
+ return list[itemName] && list[itemName] !== itemId;
+ }
}
export default Validator;
diff --git a/openecomp-ui/src/nfvo-utils/WebSocketUtil.js b/openecomp-ui/src/nfvo-utils/WebSocketUtil.js
index c9dd10f1af..69f44d4da5 100644
--- a/openecomp-ui/src/nfvo-utils/WebSocketUtil.js
+++ b/openecomp-ui/src/nfvo-utils/WebSocketUtil.js
@@ -16,41 +16,50 @@
import store from 'sdc-app/AppStore.js';
import Configuration from 'sdc-app/config/Configuration.js';
-import {actionTypes} from 'sdc-app/onboarding/userNotifications/UserNotificationsConstants.js';
+import { actionTypes } from 'sdc-app/onboarding/userNotifications/UserNotificationsConstants.js';
-
-export const websocketUrl = 'ws://' + window.location.hostname + ':' + Configuration.get('websocketPort')
- + '/' + Configuration.get('websocketPath');
+export const websocketUrl =
+ 'ws://' +
+ window.location.hostname +
+ ':' +
+ Configuration.get('websocketPort') +
+ '/' +
+ Configuration.get('websocketPath');
/***
* Websocket is treated like a singleton. only need one for the application.
*/
var websocket;
-
export default {
+ open(url, { lastScanned }) {
+ if (
+ websocket === undefined ||
+ websocket.readyState === websocket.CLOSED
+ ) {
+ websocket = new WebSocket(
+ `${url}?LAST_DELIVERED_EVENT_ID=${lastScanned}`
+ );
+ websocket.onmessage = event =>
+ store.dispatch({
+ type: actionTypes.NOTIFICATION,
+ data: JSON.parse(event.data)
+ });
+ websocket.onclose = event => {
+ if (event.code && event.code === 1001) {
+ // - Idle Timeout
+ const { lastScanned } = store.getState().notifications;
+ console.log('Reconnecting to Websocket');
+ this.open(websocketUrl, { lastScanned });
+ }
+ };
+ websocket.onerror = event => console.log(event);
+ }
+ },
- open(url, {lastScanned}) {
- if (websocket === undefined || websocket.readyState === websocket.CLOSED) {
- websocket = new WebSocket(`${url}?LAST_DELIVERED_EVENT_ID=${lastScanned}`);
- websocket.onmessage = event => store.dispatch({
- type: actionTypes.NOTIFICATION,
- data: JSON.parse(event.data)
- });
- websocket.onclose = event => {
- if(event.code && event.code === 1001) { // - Idle Timeout
- const {lastScanned} = store.getState().notifications;
- console.log('Reconnecting to Websocket');
- this.open(websocketUrl, {lastScanned});
- }
- };
- websocket.onerror = event => console.log(event);
- }
- },
-
- close() {
- if (websocket !== undefined) {
- websocket.close();
- }
- }
+ close() {
+ if (websocket !== undefined) {
+ websocket.close();
+ }
+ }
};
diff --git a/openecomp-ui/src/nfvo-utils/getValue.js b/openecomp-ui/src/nfvo-utils/getValue.js
index 5ab0c76d73..0cac3cd726 100644
--- a/openecomp-ui/src/nfvo-utils/getValue.js
+++ b/openecomp-ui/src/nfvo-utils/getValue.js
@@ -13,38 +13,50 @@
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
-import {other as optionInputOther} from 'nfvo-components/input/validation/InputOptions.jsx';
+import { other as optionInputOther } from 'nfvo-components/input/validation/InputOptions.jsx';
function getValueFromObject(element) {
- return element.choices && element.choices.length > 0 && element.choices[0] !== '' && element.choices[0] !== optionInputOther.OTHER ||
- element.other && element.choices[0] === optionInputOther.OTHER ?
- element : undefined;
+ return (element.choices &&
+ element.choices.length > 0 &&
+ element.choices[0] !== '' &&
+ element.choices[0] !== optionInputOther.OTHER) ||
+ (element.other && element.choices[0] === optionInputOther.OTHER)
+ ? element
+ : undefined;
}
function getValueFromVariable(variable) {
- return variable ? variable : undefined;
+ return variable ? variable : undefined;
}
function getArrayData(variable) {
- return variable.length ? variable : undefined;
+ return variable.length ? variable : undefined;
}
- let getValue = element => {
- return typeof element === 'object' ?
- element instanceof Array ? getArrayData(element) : getValueFromObject(element) :
- getValueFromVariable(element);
- };
+let getValue = element => {
+ return typeof element === 'object'
+ ? element instanceof Array
+ ? getArrayData(element)
+ : getValueFromObject(element)
+ : getValueFromVariable(element);
+};
export function getStrValue(choiceObject) {
- if (!choiceObject) {
- return undefined;
- }
- if (choiceObject.choice && choiceObject.choice !== '' && choiceObject.choice !== optionInputOther.OTHER) {
- return choiceObject.choice;
- }
- else if (choiceObject.other && choiceObject.choice === optionInputOther.OTHER) {
- return choiceObject.other;
- }
+ if (!choiceObject) {
+ return undefined;
+ }
+ if (
+ choiceObject.choice &&
+ choiceObject.choice !== '' &&
+ choiceObject.choice !== optionInputOther.OTHER
+ ) {
+ return choiceObject.choice;
+ } else if (
+ choiceObject.other &&
+ choiceObject.choice === optionInputOther.OTHER
+ ) {
+ return choiceObject.other;
+ }
}
- export default getValue;
+export default getValue;
diff --git a/openecomp-ui/src/nfvo-utils/i18n/i18n.js b/openecomp-ui/src/nfvo-utils/i18n/i18n.js
index ef97b8bab4..43a183def4 100644
--- a/openecomp-ui/src/nfvo-utils/i18n/i18n.js
+++ b/openecomp-ui/src/nfvo-utils/i18n/i18n.js
@@ -22,88 +22,94 @@ import i18nJson from 'i18nJson';
Intl libs are using out dated transpailer from ecmascript6.
* TODO: As soon as they fix it, remove this assignments!!!
* */
-var Intl = window.Intl || IntlObj.default,
- IntlMessageFormat = IntlMessageFormatObj.default,
- IntlRelativeFormat = IntlRelativeFormatObj.default,
- createFormatCache = createFormatCacheObj.default;
+var Intl = window.Intl || IntlObj.default,
+ IntlMessageFormat = IntlMessageFormatObj.default,
+ IntlRelativeFormat = IntlRelativeFormatObj.default,
+ createFormatCache = createFormatCacheObj.default;
/*extract locale*/
var _locale = window.localStorage && localStorage.getItem('user_locale');
-if(!_locale) {
- if(window.navigator) {
- _locale = navigator.language || navigator.userLanguage;
+if (!_locale) {
+ if (window.navigator) {
+ _locale = navigator.language || navigator.userLanguage;
- //For now removing the dashes from the language.
- let indexOfDash = _locale.indexOf('-');
- if(-1 !== indexOfDash) {
- _locale = _locale.substr(0, indexOfDash);
- }
- }
- if(!_locale) {
- _locale = 'en';
- }
+ //For now removing the dashes from the language.
+ let indexOfDash = _locale.indexOf('-');
+ if (-1 !== indexOfDash) {
+ _locale = _locale.substr(0, indexOfDash);
+ }
+ }
+ if (!_locale) {
+ _locale = 'en';
+ }
}
var _localeUpper = _locale.toUpperCase();
var i18n = {
+ _locale: _locale,
+ _localeUpper: _localeUpper,
+ _i18nData: i18nJson || {},
- _locale: _locale,
- _localeUpper: _localeUpper,
- _i18nData: i18nJson || {},
+ number(num) {
+ return createFormatCache(Intl.NumberFormat)(this._locale).format(num);
+ },
- number(num) {
- return createFormatCache(Intl.NumberFormat)(this._locale).format(num);
- },
+ date(date, options, relativeDates) {
+ if (undefined === relativeDates || relativeDates) {
+ return this.dateRelative(date, options);
+ } else {
+ return this.dateNormal(date, options);
+ }
+ },
- date(date, options, relativeDates) {
- if (undefined === relativeDates || relativeDates) {
- return this.dateRelative(date, options);
- } else {
- return this.dateNormal(date, options);
- }
- },
-
- dateNormal(date, options) {
- return createFormatCache(Intl.DateTimeFormat)(this._locale, options).format(date);
- },
-
- dateRelative(date, options) {
- return createFormatCache(IntlRelativeFormat)(this._locale, options).format(date);
- },
- message(messageId, options) {
- let messageTxt = null;
- if (i18nJson && i18nJson[messageId]) {
- messageTxt = i18nJson[messageId];
- } else {
- messageTxt = String(messageId);
- }
- return createFormatCache(IntlMessageFormat)(messageTxt, this._locale).format(options);
-
- },
- getLocale() {
- return this._locale;
- },
- getLocaleUpper() {
- return this._localeUpper;
- },
- setLocale(locale) {
- localStorage.setItem('user_locale', locale);
- window.location.reload();
- }
+ dateNormal(date, options) {
+ return createFormatCache(Intl.DateTimeFormat)(
+ this._locale,
+ options
+ ).format(date);
+ },
+ dateRelative(date, options) {
+ return createFormatCache(IntlRelativeFormat)(
+ this._locale,
+ options
+ ).format(date);
+ },
+ message(messageId, options) {
+ let messageTxt = null;
+ if (i18nJson && i18nJson[messageId]) {
+ messageTxt = i18nJson[messageId];
+ } else {
+ messageTxt = String(messageId);
+ }
+ return createFormatCache(IntlMessageFormat)(
+ messageTxt,
+ this._locale
+ ).format(options);
+ },
+ getLocale() {
+ return this._locale;
+ },
+ getLocaleUpper() {
+ return this._localeUpper;
+ },
+ setLocale(locale) {
+ localStorage.setItem('user_locale', locale);
+ window.location.reload();
+ }
};
function i18nWrapper() {
- return i18nWrapper.message.apply(i18nWrapper, arguments);
+ return i18nWrapper.message.apply(i18nWrapper, arguments);
}
/*replace with some kind of extend method*/
var prop, propKey;
for (propKey in i18n) {
- prop = i18n[propKey];
- if (typeof prop === 'function') {
- prop = prop.bind(i18nWrapper);
- }
- i18nWrapper[propKey] = prop;
+ prop = i18n[propKey];
+ if (typeof prop === 'function') {
+ prop = prop.bind(i18nWrapper);
+ }
+ i18nWrapper[propKey] = prop;
}
export default i18nWrapper;
diff --git a/openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js b/openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js
index 816915b1c9..79f95057a0 100644
--- a/openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js
+++ b/openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js
@@ -1,35 +1,51 @@
import React from 'react';
-import {storiesOf, action} from '@kadira/storybook';
-import {text, number} from '@kadira/storybook-addon-knobs';
-import {withKnobs} from '@kadira/storybook-addon-knobs';
+import { storiesOf } from '@kadira/storybook';
+import { withKnobs } from '@kadira/storybook-addon-knobs';
import i18n from 'nfvo-utils/i18n/i18n.js';
import i18nJson from 'nfvo-utils/i18n/en.json';
const stories = storiesOf('i18n', module);
stories.addDecorator(withKnobs);
-
i18nJson['added'] = 'this is my test';
i18nJson['added with {param}'] = 'this is my test with {param}';
-stories
- .add('i18n tests', () => {
- let keys = [
- 'I do not exist',
- 'Delete',
- 'OrchestrationTemplateCandidate/File Structure'
- ];
- let translations = [];
- let i=0;
- translations.push(<div id={i++}>KEY: VALUE</div>)
- keys.forEach((key) => {
- translations.push((<div id={i++}>{key} : {i18n(key)} </div>));
- });
- var param = 'param';
- translations.push((<div id={i++}>added : {i18n('added')} </div>));
- translations.push((<div id={i++}><font color="red"><b>WRONG</b></font> - added with ${param} in translation : {i18n(`added with ${param}`)} </div>));
- translations.push((<div id={i++}><font color="green"><b>RIGHT</b></font> - added with ${param} and options object {JSON.stringify({param:param})}: {i18n('added with {param}', {param: param})} </div>));
+stories.add('i18n tests', () => {
+ let keys = [
+ 'I do not exist',
+ 'Delete',
+ 'OrchestrationTemplateCandidate/File Structure'
+ ];
+ let translations = [];
+ let i = 0;
+ translations.push(<div id={i++}>KEY: VALUE</div>);
+ keys.forEach(key => {
+ translations.push(
+ <div id={i++}>
+ {key} : {i18n(key)}{' '}
+ </div>
+ );
+ });
+ var param = 'param';
+ translations.push(<div id={i++}>added : {i18n('added')} </div>);
+ translations.push(
+ <div id={i++}>
+ <font color="red">
+ <b>WRONG</b>
+ </font>{' '}
+ - added with ${param} in translation : {i18n(`added with ${param}`)}{' '}
+ </div>
+ );
+ translations.push(
+ <div id={i++}>
+ <font color="green">
+ <b>RIGHT</b>
+ </font>{' '}
+ - added with ${param} and options object{' '}
+ {JSON.stringify({ param: param })}:{' '}
+ {i18n('added with {param}', { param: param })}{' '}
+ </div>
+ );
- return (<div>{translations}</div>);
- })
-;
+ return <div>{translations}</div>;
+});
diff --git a/openecomp-ui/src/nfvo-utils/json/JSONPointer.js b/openecomp-ui/src/nfvo-utils/json/JSONPointer.js
index f4c0d4ed59..66c67dd234 100644
--- a/openecomp-ui/src/nfvo-utils/json/JSONPointer.js
+++ b/openecomp-ui/src/nfvo-utils/json/JSONPointer.js
@@ -14,44 +14,47 @@
* permissions and limitations under the License.
*/
const JSONPointer = {
-
- extractParentPointer(pointer) {
- return pointer.replace(/\/[^\/]+$/, '');
- },
-
- extractLastPart(pointer) {
- const [,lastPart] = pointer.match(/\/([^\/]+)$/) || [];
- return lastPart;
- },
-
- extractParts(pointer = '') {
- return pointer.split('/').slice(1)
- .map(part => part.replace(/~1/g, '/'))
- .map(part => part.replace(/~0/g, '~'));
- },
-
- getValue(object, pointer) {
- let parts = JSONPointer.extractParts(pointer);
- return parts.reduce((object, part) => object && object[part], object);
- },
-
- setValue(object, pointer, value) {
- let clone = obj => Array.isArray(obj) ? [...obj] : {...obj};
-
- let parts = JSONPointer.extractParts(pointer),
- newObject = clone(object),
- subObject = object,
- subNewObject = newObject;
-
- for(let i = 0, n = parts.length - 1; i < n; ++i) {
- let nextSubObject = subObject && subObject[parts[i]];
- subNewObject = subNewObject[parts[i]] = nextSubObject ? clone(nextSubObject) : {};
- subObject = nextSubObject;
- }
- subNewObject[parts[parts.length - 1]] = value;
-
- return newObject;
- }
+ extractParentPointer(pointer) {
+ return pointer.replace(/\/[^\/]+$/, '');
+ },
+
+ extractLastPart(pointer) {
+ const [, lastPart] = pointer.match(/\/([^\/]+)$/) || [];
+ return lastPart;
+ },
+
+ extractParts(pointer = '') {
+ return pointer
+ .split('/')
+ .slice(1)
+ .map(part => part.replace(/~1/g, '/'))
+ .map(part => part.replace(/~0/g, '~'));
+ },
+
+ getValue(object, pointer) {
+ let parts = JSONPointer.extractParts(pointer);
+ return parts.reduce((object, part) => object && object[part], object);
+ },
+
+ setValue(object, pointer, value) {
+ let clone = obj => (Array.isArray(obj) ? [...obj] : { ...obj });
+
+ let parts = JSONPointer.extractParts(pointer),
+ newObject = clone(object),
+ subObject = object,
+ subNewObject = newObject;
+
+ for (let i = 0, n = parts.length - 1; i < n; ++i) {
+ let nextSubObject = subObject && subObject[parts[i]];
+ subNewObject = subNewObject[parts[i]] = nextSubObject
+ ? clone(nextSubObject)
+ : {};
+ subObject = nextSubObject;
+ }
+ subNewObject[parts[parts.length - 1]] = value;
+
+ return newObject;
+ }
};
export default JSONPointer;
diff --git a/openecomp-ui/src/nfvo-utils/json/JSONSchema.js b/openecomp-ui/src/nfvo-utils/json/JSONSchema.js
index 3b3a9bf7b4..53d288f3ae 100644
--- a/openecomp-ui/src/nfvo-utils/json/JSONSchema.js
+++ b/openecomp-ui/src/nfvo-utils/json/JSONSchema.js
@@ -18,235 +18,264 @@ import cloneDeep from 'lodash/cloneDeep.js';
import JSONPointer from './JSONPointer.js';
export default class JSONSchema {
-
- setSchema(schema) {
- this._schema = schema;
- this._fragmentsCache = new Map();
- // this._ajv = new Ajv({
- // useDefaults: true,
- // coerceTypes: true
- // });
- // this._validate = this._ajv.compile(schema);
- }
-
- processData(data) {
- data = cloneDeep(data);
- // this._validate(data);
- return data;
- }
-
- // array of names of validation functions
- setSupportedValidationFunctions(supportedValidationFunctions) {
- this._supportedValidationFunctions = supportedValidationFunctions;
- }
-
- /* FYI - I was going to support "required" but then found out that server never sends it in its schema (it was a business decision. so leaving the code commented for now */
- flattenSchema(supportedValidationFunctions) {
- if (supportedValidationFunctions) { this.setSupportedValidationFunctions(supportedValidationFunctions); }
- let genericFieldInfo = {};
- if (this._schema && this._schema.properties) {
- this.travelProperties(this._schema.properties, genericFieldInfo/*, this._schema.required*/);
- }
- return {genericFieldInfo};
- }
-
- extractGenericFieldInfo(item) {
- let validationsArr = [];
- let additionalInfo = { isValid: true, errorText: ''};
- for (let value in item) {
- if (this._supportedValidationFunctions.includes(value)) {
- let validationItem = this.extractValidations(item, value);
- validationsArr[validationsArr.length] = validationItem;
- } else {
- let enumResult = this.extractEnum(item, value);
- if (enumResult !== null) {
- additionalInfo.enum = enumResult;
- }
- else {
- additionalInfo[value] = item[value];
- }
- /*if (required.includes (property)) {
+ setSchema(schema) {
+ this._schema = schema;
+ this._fragmentsCache = new Map();
+ // this._ajv = new Ajv({
+ // useDefaults: true,
+ // coerceTypes: true
+ // });
+ // this._validate = this._ajv.compile(schema);
+ }
+
+ processData(data) {
+ data = cloneDeep(data);
+ // this._validate(data);
+ return data;
+ }
+
+ // array of names of validation functions
+ setSupportedValidationFunctions(supportedValidationFunctions) {
+ this._supportedValidationFunctions = supportedValidationFunctions;
+ }
+
+ /* FYI - I was going to support "required" but then found out that server never sends it in its schema (it was a business decision. so leaving the code commented for now */
+ flattenSchema(supportedValidationFunctions) {
+ if (supportedValidationFunctions) {
+ this.setSupportedValidationFunctions(supportedValidationFunctions);
+ }
+ let genericFieldInfo = {};
+ if (this._schema && this._schema.properties) {
+ this.travelProperties(
+ this._schema.properties,
+ genericFieldInfo /*, this._schema.required*/
+ );
+ }
+ return { genericFieldInfo };
+ }
+
+ extractGenericFieldInfo(item) {
+ let validationsArr = [];
+ let additionalInfo = { isValid: true, errorText: '' };
+ for (let value in item) {
+ if (this._supportedValidationFunctions.includes(value)) {
+ let validationItem = this.extractValidations(item, value);
+ validationsArr[validationsArr.length] = validationItem;
+ } else {
+ let enumResult = this.extractEnum(item, value);
+ if (enumResult !== null) {
+ additionalInfo.enum = enumResult;
+ } else {
+ additionalInfo[value] = item[value];
+ }
+ /*if (required.includes (property)) {
additionalInfo[value].isRequired = true ;
}*/
- }
- }
-
- additionalInfo.validations = validationsArr;
- return additionalInfo;
- }
-
- extractValidations(item, value) {
- let validationItem;
- let data = item[value];
- if (value === 'maximum') {
- if (item.exclusiveMaximum) {
- value = 'maximumExclusive';
- }
- }
- if (value === 'minimum') {
- if (item.exclusiveMinimum) {
- value = 'minimumExclusive';
- }
- }
- validationItem = {type: value, data: data};
- return validationItem;
- }
-
- extractEnum(item, value) {
- let enumResult = null;
- if (value === 'type' && item[value] === 'array') {
- let items = item.items;
- if (items && items.enum && items.enum.length > 0) {
- let values = items.enum
- .filter(value => value)
- .map(value => ({enum: value, title: value}));
- enumResult = values;
- }
- }
- else if (value === 'enum') {
- let items = item[value];
- if (items && items.length > 0) {
- let values = items
- .filter(value => value)
- .map(value => ({enum: value, title: value}));
- enumResult = values;
- }
- }
- return enumResult;
- }
-
- travelProperties(properties, genericFieldDefs, /*required = [],*/ pointer = ''){
- let newPointer = pointer;
- for (let property in properties) {
- newPointer = newPointer ? newPointer + '/' + property : property;
- if (properties[property].properties) {
- this.travelProperties(properties[property].properties, genericFieldDefs /*, properties[property].required*/, newPointer);
- }
- else if (properties[property].$ref){
- let fragment = this._getSchemaFragmentByRef(properties[property].$ref);
- if (fragment.properties) {
- this.travelProperties(fragment.properties, genericFieldDefs /*, properties[property].required*/, newPointer);
- } else {
- genericFieldDefs[newPointer] = this.extractGenericFieldInfo(fragment.properties);
- }
- }
- else {
- genericFieldDefs[newPointer] = this.extractGenericFieldInfo(properties[property]);
- }
- newPointer = pointer;
- }
- }
-
- getTitle(pointer) {
- return this._getSchemaFragment(pointer).title;
- }
-
- exists(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return !!fragment;
- }
-
- getDefault(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.default;
- }
-
- getEnum(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && (fragment.type === 'array' ? fragment.items.enum : fragment.enum);
- }
-
- isRequired(pointer) {
- const parentPointer = JSONPointer.extractParentPointer(pointer);
- const lastPart = JSONPointer.extractLastPart(pointer);
- let parentFragment = this._getSchemaFragment(parentPointer);
- return parentFragment && parentFragment.required && parentFragment.required.includes(lastPart);
- }
-
- isNumber(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.type === 'number';
- }
-
- getMaxValue(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.exclusiveMaximum ? fragment.maximum - 1 : fragment.maximum;
- }
-
- getMinValue(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.exclusiveMinimum ? fragment.minimum : fragment.minimum;
- }
-
- isString(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.type === 'string';
- }
-
- getPattern(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.pattern;
- }
-
- getMaxLength(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.maxLength;
- }
-
- getMinLength(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.minLength;
- }
-
- isArray(pointer) {
- const fragment = this._getSchemaFragment(pointer);
- return fragment && fragment.type === 'array';
- }
-
- _getSchemaFragment(pointer) {
- if (this._fragmentsCache.has(pointer)) {
- return this._fragmentsCache.get(pointer);
- }
-
- let parts = JSONPointer.extractParts(pointer);
-
- let fragment = parts.reduce((fragment, part) => {
- if (fragment === undefined) {
- return undefined;
- }
-
- if (fragment.$ref) {
- fragment = this._getSchemaFragmentByRef(fragment.$ref);
- }
-
- switch (fragment.type) {
- case 'object':
- return fragment.properties && fragment.properties[part];
-
- case 'array':
- return fragment.enum && fragment.enum[part];
-
- default:
- // throw new Error(`Incorrect/unsupported JSONPointer "${pointer}" from "${part}"`);
- return undefined;
- }
- }, this._schema);
-
- while(fragment && fragment.$ref) {
- fragment = this._getSchemaFragmentByRef(fragment.$ref);
- }
-
- this._fragmentsCache.set(pointer, fragment);
- return fragment;
- }
-
- _getSchemaFragmentByRef($ref) {
- let pointer = $ref.substr(1);
- return JSONPointer.getValue(this._schema, pointer);
- // let fragmentAjv = new Ajv();
- // fragmentAjv.addSchema(this._schema);
- // let compiledFragment = fragmentAjv.compile({$ref});
- // let fragment = compiledFragment.refVal[compiledFragment.refs[$ref]];
- // return fragment;
- }
-};
+ }
+ }
+
+ additionalInfo.validations = validationsArr;
+ return additionalInfo;
+ }
+
+ extractValidations(item, value) {
+ let validationItem;
+ let data = item[value];
+ if (value === 'maximum') {
+ if (item.exclusiveMaximum) {
+ value = 'maximumExclusive';
+ }
+ }
+ if (value === 'minimum') {
+ if (item.exclusiveMinimum) {
+ value = 'minimumExclusive';
+ }
+ }
+ validationItem = { type: value, data: data };
+ return validationItem;
+ }
+
+ extractEnum(item, value) {
+ let enumResult = null;
+ if (value === 'type' && item[value] === 'array') {
+ let items = item.items;
+ if (items && items.enum && items.enum.length > 0) {
+ let values = items.enum
+ .filter(value => value)
+ .map(value => ({ enum: value, title: value }));
+ enumResult = values;
+ }
+ } else if (value === 'enum') {
+ let items = item[value];
+ if (items && items.length > 0) {
+ let values = items
+ .filter(value => value)
+ .map(value => ({ enum: value, title: value }));
+ enumResult = values;
+ }
+ }
+ return enumResult;
+ }
+
+ travelProperties(
+ properties,
+ genericFieldDefs,
+ /*required = [],*/ pointer = ''
+ ) {
+ let newPointer = pointer;
+ for (let property in properties) {
+ newPointer = newPointer ? newPointer + '/' + property : property;
+ if (properties[property].properties) {
+ this.travelProperties(
+ properties[property].properties,
+ genericFieldDefs /*, properties[property].required*/,
+ newPointer
+ );
+ } else if (properties[property].$ref) {
+ let fragment = this._getSchemaFragmentByRef(
+ properties[property].$ref
+ );
+ if (fragment.properties) {
+ this.travelProperties(
+ fragment.properties,
+ genericFieldDefs /*, properties[property].required*/,
+ newPointer
+ );
+ } else {
+ genericFieldDefs[newPointer] = this.extractGenericFieldInfo(
+ fragment.properties
+ );
+ }
+ } else {
+ genericFieldDefs[newPointer] = this.extractGenericFieldInfo(
+ properties[property]
+ );
+ }
+ newPointer = pointer;
+ }
+ }
+
+ getTitle(pointer) {
+ return this._getSchemaFragment(pointer).title;
+ }
+
+ exists(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return !!fragment;
+ }
+
+ getDefault(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.default;
+ }
+
+ getEnum(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return (
+ fragment &&
+ (fragment.type === 'array' ? fragment.items.enum : fragment.enum)
+ );
+ }
+
+ isRequired(pointer) {
+ const parentPointer = JSONPointer.extractParentPointer(pointer);
+ const lastPart = JSONPointer.extractLastPart(pointer);
+ let parentFragment = this._getSchemaFragment(parentPointer);
+ return (
+ parentFragment &&
+ parentFragment.required &&
+ parentFragment.required.includes(lastPart)
+ );
+ }
+
+ isNumber(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.type === 'number';
+ }
+
+ getMaxValue(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.exclusiveMaximum
+ ? fragment.maximum - 1
+ : fragment.maximum;
+ }
+
+ getMinValue(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.exclusiveMinimum
+ ? fragment.minimum
+ : fragment.minimum;
+ }
+
+ isString(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.type === 'string';
+ }
+
+ getPattern(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.pattern;
+ }
+
+ getMaxLength(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.maxLength;
+ }
+
+ getMinLength(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.minLength;
+ }
+
+ isArray(pointer) {
+ const fragment = this._getSchemaFragment(pointer);
+ return fragment && fragment.type === 'array';
+ }
+
+ _getSchemaFragment(pointer) {
+ if (this._fragmentsCache.has(pointer)) {
+ return this._fragmentsCache.get(pointer);
+ }
+
+ let parts = JSONPointer.extractParts(pointer);
+
+ let fragment = parts.reduce((fragment, part) => {
+ if (fragment === undefined) {
+ return undefined;
+ }
+
+ if (fragment.$ref) {
+ fragment = this._getSchemaFragmentByRef(fragment.$ref);
+ }
+
+ switch (fragment.type) {
+ case 'object':
+ return fragment.properties && fragment.properties[part];
+
+ case 'array':
+ return fragment.enum && fragment.enum[part];
+
+ default:
+ // throw new Error(`Incorrect/unsupported JSONPointer "${pointer}" from "${part}"`);
+ return undefined;
+ }
+ }, this._schema);
+
+ while (fragment && fragment.$ref) {
+ fragment = this._getSchemaFragmentByRef(fragment.$ref);
+ }
+
+ this._fragmentsCache.set(pointer, fragment);
+ return fragment;
+ }
+
+ _getSchemaFragmentByRef($ref) {
+ let pointer = $ref.substr(1);
+ return JSONPointer.getValue(this._schema, pointer);
+ // let fragmentAjv = new Ajv();
+ // fragmentAjv.addSchema(this._schema);
+ // let compiledFragment = fragmentAjv.compile({$ref});
+ // let fragment = compiledFragment.refVal[compiledFragment.refs[$ref]];
+ // return fragment;
+ }
+}
diff --git a/openecomp-ui/src/nfvo-utils/sortByStringProperty.js b/openecomp-ui/src/nfvo-utils/sortByStringProperty.js
index b415dd7e07..89e9f4034c 100644
--- a/openecomp-ui/src/nfvo-utils/sortByStringProperty.js
+++ b/openecomp-ui/src/nfvo-utils/sortByStringProperty.js
@@ -14,5 +14,7 @@
* permissions and limitations under the License.
*/
export default function sortByStringProperty(array, property) {
- return [...array].sort((a, b) => a[property].toLowerCase().localeCompare(b[property].toLowerCase()));
+ return [...array].sort((a, b) =>
+ a[property].toLowerCase().localeCompare(b[property].toLowerCase())
+ );
}