CommonViewFunction.js 22.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

19
define(['require', 'utils/Utils', 'modules/Modal', 'utils/Messages', 'utils/Enums'], function(require, Utils, Modal, Messages, Enums) {
20 21 22
    'use strict';

    var CommonViewFunction = {};
23
    CommonViewFunction.deleteTagModel = function(options) {
24
        var modal = new Modal({
25 26 27
            title: options.titleMessage,
            okText: options.buttonText,
            htmlContent: options.msg,
28 29 30 31 32 33 34 35 36 37
            cancelText: "Cancel",
            allowCancel: true,
            okCloses: true,
            showFooter: true,
        }).open();
        return modal;
    };
    CommonViewFunction.deleteTag = function(options) {
        require(['models/VTag'], function(VTag) {
            var tagModel = new VTag();
38
            if (options && options.guid && options.tagName) {
39 40 41
                if (options.showLoader) {
                    options.showLoader();
                }
42
                tagModel.deleteAssociation(options.guid, options.tagName, {
43
                    skipDefaultError: true,
44
                    success: function(data) {
45
                        var msg = "Tag " + name.name + Messages.removeSuccessMessage;
46 47 48 49
                        if (options.tagOrTerm === "term") {
                            msg = "Term " + options.tagName + Messages.removeSuccessMessage;
                        } else if (options.tagOrTerm === "tag") {
                            msg = "Tag " + options.tagName + Messages.removeSuccessMessage;
50
                        }
51
                        Utils.notifySuccess({
52
                            content: msg
53
                        });
54 55 56 57 58 59 60
                        if (options.callback) {
                            options.callback();
                        }
                        if (options.collection) {
                            options.collection.fetch({ reset: true });
                        }

61
                    },
62
                    cust_error: function(model, response) {
63
                        var message = options.tagName + Messages.deleteErrorMessage;
64 65
                        if (response && response.responseJSON) {
                            message = response.responseJSON.errorMessage;
66
                        }
67 68 69
                        if (options.hideLoader) {
                            options.hideLoader();
                        }
70 71 72
                        Utils.notifyError({
                            content: message
                        });
73
                    }
74
                });
75
            }
76 77
        });
    };
78 79 80 81 82 83 84 85 86 87 88 89 90
    CommonViewFunction.findAndmergeRefEntity = function(attributeObject, referredEntities) {
        _.each(attributeObject, function(obj, key) {
            if (_.isObject(obj)) {
                if (_.isArray(obj)) {
                    _.each(obj, function(value) {
                        _.extend(value, referredEntities[value.guid]);
                    });
                } else {
                    _.extend(obj, referredEntities[obj.guid]);
                }
            }
        });
    }
91 92 93 94 95 96
    CommonViewFunction.propertyTable = function(options) {
        var scope = options.scope,
            valueObject = options.valueObject,
            extractJSON = options.extractJSON,
            entityDef = options.entityDef;

97 98 99
        var table = "",
            fetchInputOutputValue = function(id) {
                var that = this;
100
                scope.entityModel.getEntity(id, {
101
                    success: function(serverData) {
102
                        var value = "",
103 104
                            deleteButton = "",
                            data = serverData.entity;
105
                        value = Utils.getName(data);
106
                        var id = "";
107
                        if (data.guid) {
108
                            if (Enums.entityStateReadOnly[data.status]) {
109
                                deleteButton += '<button title="Deleted" class="btn btn-atlasAction btn-atlas deleteBtn"><i class="fa fa-trash"></i></button>';
110
                            }
111
                            id = data.guid;
112 113
                        }
                        if (value.length > 1) {
114
                            scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + value + '</a>');
115
                        } else {
116
                            scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + _.escape(id) + '</a>');
117
                        }
118 119 120 121
                        if (deleteButton.length) {
                            scope.$('td div[data-id="' + id + '"]').addClass('block readOnlyLink');
                            scope.$('td div[data-id="' + id + '"]').append(deleteButton);
                        }
122
                    },
123
                    complete: function() {}
124
                });
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
            },
            extractObject = function(keyValue) {
                var valueOfArray = [];
                if (!_.isArray(keyValue) && _.isObject(keyValue)) {
                    keyValue = [keyValue];
                }
                var subLink = "";
                for (var i = 0; i < keyValue.length; i++) {
                    var inputOutputField = keyValue[i],
                        id = inputOutputField.guid || (_.isObject(inputOutputField.id) ? inputOutputField.id.id : inputOutputField.id),
                        tempLink = "",
                        status = inputOutputField.status || (_.isObject(inputOutputField.id) ? inputOutputField.id.state : inputOutputField.state),
                        readOnly = Enums.entityStateReadOnly[status];
                    if (!inputOutputField.attributes && inputOutputField.values) {
                        inputOutputField['attributes'] = inputOutputField.values;
140
                    }
141 142 143 144
                    if (_.isString(inputOutputField) || _.isBoolean(inputOutputField) || _.isNumber(inputOutputField)) {
                        var tempVarfor$check = inputOutputField.toString();
                        if (tempVarfor$check.indexOf("$") == -1) {
                            valueOfArray.push('<span>' + _.escape(inputOutputField) + '</span>');
145
                        }
146 147 148 149 150 151
                    } else if (_.isObject(inputOutputField) && !id) {
                        var attributesList = inputOutputField;
                        if (scope.typeHeaders && inputOutputField.typeName) {
                            var typeNameCategory = scope.typeHeaders.fullCollection.findWhere({ name: inputOutputField.typeName });
                            if (attributesList.attributes && typeNameCategory && typeNameCategory.get('category') === 'STRUCT') {
                                attributesList = attributesList.attributes;
152
                            }
153 154 155 156 157 158 159
                        }
                        _.each(attributesList, function(objValue, objKey) {
                            var value = objValue,
                                tempVarfor$check = objKey.toString();
                            if (tempVarfor$check.indexOf("$") == -1) {
                                if (_.isObject(value)) {
                                    value = JSON.stringify(value);
160
                                }
161 162 163 164 165 166 167 168 169 170 171
                                if (extractJSON) {
                                    if (extractJSON && extractJSON.extractKey) {
                                        if (_.isObject(extractJSON.extractKey)) {
                                            _.each(extractJSON.extractKey, function(extractKey) {
                                                if (objKey === extractKey) {
                                                    valueOfArray.push('<span>' + _.escape(objKey) + ':' + _.escape(value) + '</span>');
                                                }
                                            });
                                        } else if (_.isString(extractJSON.extractKey) && extractJSON.extractKey === objKey) {
                                            valueOfArray.push(_.escape(value));
                                        }
172
                                    }
173
                                } else {
174 175 176
                                    valueOfArray.push('<span>' + _.escape(objKey) + ':' + _.escape(value) + '</span>');
                                }
                            }
177 178 179 180 181 182 183 184 185
                        });
                    }
                    if (id && inputOutputField) {
                        var name = Utils.getName(inputOutputField);
                        if (name === "-" || name === id) {
                            var fetch = true;
                            var fetchId = (_.isObject(id) ? id.id : id);
                            fetchInputOutputValue(fetchId);
                            tempLink += '<div data-id="' + fetchId + '"></div>';
186
                        } else {
187
                            tempLink += '<a href="#!/detailPage/' + id + '">' + name + '</a>'
188
                        }
189
                    }
190 191 192 193 194 195 196 197
                    if (readOnly) {
                        if (!fetch) {
                            tempLink += '<button title="Deleted" class="btn btn-atlasAction btn-atlas deleteBtn"><i class="fa fa-trash"></i></button>';
                            subLink += '<div class="block readOnlyLink">' + tempLink + '</div>';
                        } else {
                            fetch = false;
                            subLink += tempLink;
                        }
198

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
                    } else {
                        if (tempLink.search('href') != -1) {
                            subLink += '<div>' + tempLink + '</div>'
                        } else if (tempLink.length) {
                            subLink += tempLink
                        }
                    }
                }
                if (valueOfArray.length) {
                    subLink = valueOfArray.join(', ');
                }
                return subLink;
            }
        _.sortBy(_.keys(valueObject)).map(function(key) {
            key = _.escape(key);
            var keyValue = valueObject[key];
            var defEntity = _.find(entityDef, { name: key });
            if (defEntity && defEntity.typeName) {
                var defEntityType = defEntity.typeName.toLocaleLowerCase();
                if (defEntityType === 'date' || defEntityType === 'time') {
                    keyValue = new Date(keyValue);
                } else if (_.isObject(keyValue)) {
                    keyValue = extractObject(keyValue);
                }
            } else {
                if (_.isObject(keyValue)) {
                    keyValue = extractObject(keyValue)
226 227
                }
            }
228
            table += '<tr><td>' + _.escape(key) + '</td><td>' + (_.isObject(valueObject[key]) ? keyValue : _.escape(keyValue)) + '</td></tr>';
229 230 231
        });
        return table;
    }
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    CommonViewFunction.breadcrumbUrlMaker = function(url) {
        if (url) {
            var urlList = [];
            var splitURL = url.split("api/atlas/v1/taxonomies/");
            if (splitURL.length > 1) {
                var splitUrlWithoutTerm = splitURL[1].split("/terms/");
                if (splitUrlWithoutTerm.length == 1) {
                    splitUrlWithoutTerm = splitUrlWithoutTerm[0].split("/");
                }
            } else {
                var splitUrlWithoutTerm = splitURL[0].split("/terms/");
                if (splitUrlWithoutTerm.length == 1) {
                    splitUrlWithoutTerm = splitUrlWithoutTerm[0].split("/");
                }
            }

            var href = "";
            for (var i in splitUrlWithoutTerm) {
                if (i == 0) {
                    href = splitUrlWithoutTerm[i];
                    urlList.push({
253
                        value: _.escape(splitUrlWithoutTerm[i]),
254 255 256 257 258
                        href: href
                    });
                } else {
                    href += "/terms/" + splitUrlWithoutTerm[i];
                    urlList.push({
259
                        value: _.escape(splitUrlWithoutTerm[i]),
260 261 262 263 264 265 266 267 268 269 270
                        href: href
                    });
                };
            }
            return urlList;
        }
    }
    CommonViewFunction.breadcrumbMaker = function(options) {
        var li = "";
        if (options.urlList) {
            _.each(options.urlList, function(object) {
271
                li += '<li><a class="link" href="#!/taxonomy/detailCatalog/api/atlas/v1/taxonomies/' + object.href + '?load=true">' + _.escape(object.value) + '</a></li>';
272 273 274 275 276 277 278 279
            });
        }
        if (options.scope) {
            options.scope.html(li);
            options.scope.asBreadcrumbs("destroy");
            options.scope.asBreadcrumbs({
                namespace: 'breadcrumb',
                overflow: "left",
280
                responsive: false,
281 282
                toggleIconClass: 'fa fa-ellipsis-h',
                dropdown: function(classes) {
283 284
                    var dropdownClass = 'dropdown';
                    var dropdownMenuClass = 'dropdown-menu popover popoverTerm bottom arrowPosition';
285 286 287 288
                    if (this.options.overflow === 'right') {
                        dropdownMenuClass += ' dropdown-menu-right';
                    }

289 290 291 292 293 294 295 296
                    return '<li class="' + dropdownClass + ' ' + classes.dropdownClass + '">' +
                        '<a href="javascript:void(0);" class="' + classes.toggleClass + '" data-toggle="dropdown">' +
                        '<i class="' + classes.toggleIconClass + '"></i>' +
                        '</a>' +
                        '<ul class="' + dropdownMenuClass + ' ' + classes.dropdownMenuClass + '">' +
                        '<div class="arrow"></div>' +
                        '</ul>' +
                        '</li>';
297 298 299 300
                }
            });
        }
    }
301 302
    CommonViewFunction.termTableBreadcrumbMaker = function(obj) {
        if (!obj) {
303 304
            return "";
        }
305
        var traits = obj.classificationNames || _.pluck(obj.classifications, 'typeName'),
306
            url = "",
307 308
            deleteHtml = "",
            html = "",
309 310
            id = obj.guid,
            terms = [],
311
            entityName = Utils.getName(obj);
312 313
        if (traits) {
            traits.map(function(term) {
314 315
                var checkTagOrTerm = Utils.checkTagOrTerm(term);
                if (checkTagOrTerm.term) {
316 317 318 319 320 321 322 323
                    terms.push({
                        deleteHtml: '<a class="pull-left" title="Remove Term"><i class="fa fa-trash" data-id="tagClick" data-type="term" data-assetname="' + entityName + '" data-name="' + term + '" data-guid="' + obj.guid + '" ></i></a>',
                        url: _.unescape(term).split(".").join("/"),
                        name: term
                    });
                }
            });
        }
324 325 326 327
        _.each(terms, function(obj, i) {
            var className = "";
            if (i >= 1) {
                className += "showHideDiv hide";
328
            }
329
            obj['valueUrl'] = CommonViewFunction.breadcrumbUrlMaker(obj.url);
330
            html += '<div class="' + className + '" dataterm-name="' + obj.name + '"><div class="liContent"></div>' + obj.deleteHtml + '</div>';
331 332 333 334
        })
        if (terms.length > 1) {
            html += '<div><a  href="javascript:void(0)" data-id="showMoreLessTerm" class="inputTag inputTagGreen"><span>Show More </span><i class="fa fa-angle-right"></i></a></div>'
        }
335 336 337 338 339 340
        if (!Enums.entityStateReadOnly[obj.status]) {
            if (obj.guid) {
                html += '<div><a href="javascript:void(0)" class="inputAssignTag" data-id="addTerm" data-guid="' + (obj.guid) + '"><i class="fa fa-folder-o"></i>' + " " + 'Assign Term</a></div>'
            } else {
                html += '<div><a href="javascript:void(0)" class="inputAssignTag" data-id="addTerm"><i class="fa fa-folder-o"></i>' + " " + 'Assign Term</a></div>'
            }
341 342 343 344
        }
        return {
            html: '<div class="termTableBreadcrumb" dataterm-id="' + id + '">' + html + '</div>',
            object: { scopeId: id, value: terms }
345
        }
346

347
    }
348
    CommonViewFunction.tagForTable = function(obj) {
349
        var traits = obj.classificationNames || _.pluck(obj.classifications, 'typeName'),
350 351
            atags = "",
            addTag = "",
352
            popTag = "",
353
            count = 0,
354
            entityName = Utils.getName(obj);
355 356
        if (traits) {
            traits.map(function(tag) {
357 358
                var checkTagOrTerm = Utils.checkTagOrTerm(tag);
                if (checkTagOrTerm.tag) {
359 360
                    var className = "inputTag",
                        tagString = '<a class="' + className + '" data-id="tagClick"><span class="inputValue">' + tag + '</span><i class="fa fa-times" data-id="delete"  data-assetname="' + entityName + '"data-name="' + tag + '" data-type="tag" data-guid="' + obj.guid + '" ></i></a>';
361
                    if (count >= 1) {
362
                        popTag += tagString;
363
                    } else {
364
                        atags += tagString;
365 366
                    }
                    ++count;
367
                }
368 369 370 371 372 373 374
            });
        }
        if (!Enums.entityStateReadOnly[obj.status]) {
            if (obj.guid) {
                addTag += '<a href="javascript:void(0)" data-id="addTag" class="inputTagAdd assignTag" data-guid="' + obj.guid + '" ><i class="fa fa-plus"></i></a>';
            } else {
                addTag += '<a href="javascript:void(0)" data-id="addTag" class="inputTagAdd assignTag"><i style="right:0" class="fa fa-plus"></i></a>';
375 376 377
            }
        }
        if (count > 1) {
378
            addTag += '<div data-id="showMoreLess" class="inputTagAdd assignTag tagDetailPopover"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></div>'
379
        }
380
        return '<div class="tagList">' + atags + addTag + '<div class="popover popoverTag bottom" style="display:none"><div class="arrow"></div><div class="popover-content popoverContainer">' + popTag + '</div></div></div>';
381
    }
382
    CommonViewFunction.saveTermToAsset = function(options, that) {
383 384 385
        require(['models/VCatalog'], function(Vcatalog) {
            var VCatalog = new Vcatalog();
            var name = options.termName;
386
            ++that.asyncFetchCounter;
387 388 389 390 391 392 393 394 395 396 397 398
            VCatalog.url = function() {
                return "api/atlas/v1/entities/" + options.guid + "/tags/" + name;
            };
            VCatalog.save(null, {
                success: function(data) {
                    Utils.notifySuccess({
                        content: "Term " + name + Messages.addTermToEntitySuccessMessage
                    });
                    if (options.collection) {
                        options.collection.fetch({ reset: true });
                    }
                },
399 400 401 402 403 404
                complete: function() {
                    --that.asyncFetchCounter
                    if (that.callback && that.asyncFetchCounter === 0) {
                        that.callback(); // It will call to parent of parent Callback i.e callback of searchLayoutView
                    }
                }
405 406 407
            });
        })
    }
408 409 410 411 412 413 414 415 416 417 418 419 420
    CommonViewFunction.addRestCsrfCustomHeader = function(xhr, settings) {
        //    if (settings.url == null || !settings.url.startsWith('/webhdfs/')) {
        if (settings.url == null) {
            return;
        }
        var method = settings.type;
        if (CommonViewFunction.restCsrfCustomHeader != null && !CommonViewFunction.restCsrfMethodsToIgnore[method]) {
            // The value of the header is unimportant.  Only its presence matters.
            xhr.setRequestHeader(CommonViewFunction.restCsrfCustomHeader, '""');
        }
    }
    CommonViewFunction.restCsrfCustomHeader = null;
    CommonViewFunction.restCsrfMethodsToIgnore = null;
421
    CommonViewFunction.userDataFetch = function(options) {
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        var csrfEnabled = false,
            header = null,
            methods = [];

        function getTrimmedStringArrayValue(string) {
            var str = string,
                array = [];
            if (str) {
                var splitStr = str.split(',');
                for (var i = 0; i < splitStr.length; i++) {
                    array.push(splitStr[i].trim());
                }
            }
            return array;
        }
437 438 439 440
        if (options.url) {
            $.ajax({
                url: options.url,
                success: function(response) {
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
                    if (response) {
                        if (response['atlas.rest-csrf.enabled']) {
                            var str = "" + response['atlas.rest-csrf.enabled'];
                            csrfEnabled = (str.toLowerCase() == 'true');
                        }
                        if (response['atlas.rest-csrf.custom-header']) {
                            header = response['atlas.rest-csrf.custom-header'].trim();
                        }
                        if (response['atlas.rest-csrf.methods-to-ignore']) {
                            methods = getTrimmedStringArrayValue(response['atlas.rest-csrf.methods-to-ignore']);
                        }
                        if (csrfEnabled) {
                            CommonViewFunction.restCsrfCustomHeader = header;
                            CommonViewFunction.restCsrfMethodsToIgnore = {};
                            methods.map(function(method) { CommonViewFunction.restCsrfMethodsToIgnore[method] = true; });
                            Backbone.$.ajaxSetup({
                                beforeSend: CommonViewFunction.addRestCsrfCustomHeader
                            });
                        }
                    }
                },
                complete: function(response) {
463
                    if (options.callback) {
464
                        options.callback(response.responseJSON);
465 466 467 468 469
                    }
                }
            });
        }
    }
470 471
    return CommonViewFunction;
});