Utils.js 13.9 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/Globals', 'pnotify', 'utils/Messages', 'pnotify.buttons', 'pnotify.confirm'], function(require, Globals, pnotify, Messages) {
20 21 22
    'use strict';

    var Utils = {};
23
    var prevNetworkErrorTime = 0;
24 25 26 27 28 29 30 31 32 33 34 35

    Utils.escapeHtml = function(string) {
        var entityMap = {
            "&": "&",
            "<": "&lt;",
            ">": "&gt;",
            '"': '&quot;',
            "'": '&#39;',
            "/": '&#x2F;'
        };
        return String(string).replace(/[&<>"'\/]/g, function(s) {
            return entityMap[s];
36
        });
37
    }
38 39 40 41 42 43 44 45 46 47 48 49 50
    Utils.generateUUID = function() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    };

51
    var notify = function(options) {
52
        return new pnotify(_.extend({ icon: true, hide: true, delay: 3000, remove: true }, options));
53
    }
54
    Utils.notifyInfo = function(options) {
55 56
        notify({
            type: "info",
57
            text: (options.html ? options.content : _.escape(options.content)) || "Info message."
58 59
        });
    };
60

61
    Utils.notifyWarn = function(options) {
62 63
        notify({
            type: "notice",
64
            text: (options.html ? options.content : _.escape(options.content)) || "Info message."
65 66 67 68
        });
    };

    Utils.notifyError = function(options) {
69
        notify({
70
            type: "error",
71
            text: (options.html ? options.content : _.escape(options.content)) || "Error occurred."
72 73 74 75
        });
    };

    Utils.notifySuccess = function(options) {
76
        notify({
77
            type: "success",
78
            text: (options.html ? options.content : _.escape(options.content)) || "Error occurred."
79 80
        });
    };
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

    Utils.notifyConfirm = function(options) {
        notify(_.extend({
            title: 'Confirmation',
            hide: false,
            confirm: {
                confirm: true
            },
            buttons: {
                closer: false,
                sticker: false
            },
            history: {
                history: false
            }
        }, options)).get().on('pnotify.confirm', function() {
            if (options.ok) {
                options.ok();
            }
        }).on('pnotify.cancel', function() {
            if (options.cancel) {
                options.cancel();
            }
        });
    }
106
    Utils.defaultErrorHandler = function(model, error) {
107 108 109 110 111 112 113 114
        if (error && error.status) {
            if (error.status == 401) {
                window.location = 'login.jsp'
            } else if (error.status == 419) {
                window.location = 'login.jsp'
            } else if (error.status == 403) {
                var message = "You are not authorized";
                if (error.statusText) {
115 116 117 118 119 120
                    try {
                        message = JSON.parse(error.statusText).AuthorizationError;
                    } catch (err) {}
                    Utils.notifyError({
                        content: message
                    });
121 122 123 124 125 126 127 128 129 130
                }
            } else if (error.status == "0" && error.statusText != "abort") {
                var diffTime = (new Date().getTime() - prevNetworkErrorTime);
                if (diffTime > 3000) {
                    prevNetworkErrorTime = new Date().getTime();
                    Utils.notifyError({
                        content: "Network Connection Failure : " +
                            "It seems you are not connected to the internet. Please check your internet connection and try again"
                    });
                }
131
            } else {
132
                Utils.serverErrorHandler(model, error)
133
            }
134 135 136 137 138 139 140
        } else {
            Utils.serverErrorHandler(model, error)
        }
    };
    Utils.serverErrorHandler = function(model, response) {
        var responseJSON = response ? response.responseJSON : response;
        if (response && responseJSON && (responseJSON.errorMessage || responseJSON.message || responseJSON.error)) {
141
            Utils.notifyError({
142 143 144 145 146
                content: responseJSON.errorMessage || responseJSON.message || responseJSON.error
            });
        } else {
            Utils.notifyError({
                content: Messages.defaultErrorMessage
147
            });
148
        }
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    };
    Utils.localStorage = {
        checkLocalStorage: function(key, value) {
            if (typeof(Storage) !== "undefined") {
                return this.getLocalStorage(key, value);
            } else {
                console.log('Sorry! No Web Storage support');
                Utils.cookie.checkCookie(key, value);
            }
        },
        setLocalStorage: function(key, value) {
            localStorage.setItem(key, value);
            return { found: false, 'value': value };
        },
        getLocalStorage: function(key, value) {
164
            var keyValue = localStorage.getItem(key);
165 166 167 168 169 170
            if (!keyValue || keyValue == "undefined") {
                return this.setLocalStorage(key, value);
            } else {
                return { found: true, 'value': keyValue };
            }
        }
171
    };
172 173 174 175 176
    Utils.cookie = {
        setCookie: function(cname, cvalue) {
            //var d = new Date();
            //d.setTime(d.getTime() + (exdays*24*60*60*1000));
            //var expires = "expires=" + d.toGMTString();
177
            document.cookie = cname + "=" + cvalue + "; ";
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
            return { found: false, 'value': cvalue };
        },
        getCookie: function(findString) {
            var search = findString + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1);
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        },
        checkCookie: function(key, value) {
            var findString = getCookie(key);
            if (findString != "" || keyValue != "undefined") {
                return { found: true, 'value': ((findString == "undefined") ? (undefined) : (findString)) };
            } else {
                return setCookie(key, value);
            }
        }
200
    };
201 202 203 204

    Utils.setUrl = function(options) {
        if (options) {
            if (options.mergeBrowserUrl) {
205 206
                var param = Utils.getUrlState.getQueryParams();
                if (param) {
207
                    options.urlParams = $.extend(param, options.urlParams);
208 209 210
                }
            }
            if (options.urlParams) {
211
                var urlParams = "?";
212 213 214 215 216 217
                _.each(options.urlParams, function(value, key, obj) {
                    urlParams += key + "=" + value + "&";
                });
                urlParams = urlParams.slice(0, -1);
                options.url += urlParams;
            }
218
            if (options.updateTabState) {
219
                $.extend(Globals.saveApplicationState.tabState, options.updateTabState());
220
            }
221 222
            Backbone.history.navigate(options.url, { trigger: options.trigger != undefined ? options.trigger : true });
        }
223
    };
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

    Utils.getUrlState = {
        getQueryUrl: function() {
            var hashValue = window.location.hash;
            return {
                firstValue: hashValue.split('/')[1],
                hash: hashValue,
                queyParams: hashValue.split("?"),
                lastValue: hashValue.split('/')[hashValue.split('/').length - 1]
            }
        },
        isInitial: function() {
            return this.getQueryUrl().firstValue == undefined ? true : false;
        },
        isTagTab: function() {
            return this.getQueryUrl().firstValue == "tag" ? true : false;
        },
        isTaxonomyTab: function() {
            return this.getQueryUrl().firstValue == "taxonomy" ? true : false;
        },
        isSearchTab: function() {
            return this.getQueryUrl().firstValue == "search" ? true : false;
        },
247 248 249
        isDetailPage: function() {
            return this.getQueryUrl().firstValue == "detailPage" ? true : false;
        },
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        getLastValue: function() {
            return this.getQueryUrl().lastValue;
        },
        getFirstValue: function() {
            return this.getQueryUrl().firstValue;
        },
        getQueryParams: function() {
            var qs = this.getQueryUrl().queyParams[1];
            if (typeof qs == "string") {
                qs = qs.split('+').join(' ');
                var params = {},
                    tokens,
                    re = /[?&]?([^=]+)=([^&]*)/g;
                while (tokens = re.exec(qs)) {
                    params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
                }
                return params;
            }
        },
        getKeyValue: function(key) {
            var paramsObj = this.getQueryParams();
            if (key.length) {
                var values = [];
                _.each(key, function(objKey) {
                    var obj = {};
                    obj[objKey] = paramsObj[objKey]
                    values.push(obj);
                    return values;
                })
            } else {
                return paramsObj[key];
            }
        }
    }
284 285 286 287 288 289
    Utils.checkTagOrTerm = function(value, isTermView) {
        if (value && _.isString(value) && isTermView) {
            // For string break
            if (value == "TaxonomyTerm") {
                return {}
            }
290
            var name = _.escape(value).split('.');
291 292 293 294 295 296 297
            return {
                term: true,
                tag: false,
                name: name[name.length - 1],
                fullName: value
            }
        }
298 299 300 301 302
        if (value && _.isString(value)) {
            value = {
                typeName: value
            }
        }
303 304 305 306 307 308 309 310 311 312
        if (_.isObject(value)) {
            var name = "";
            if (value && value.$typeName$) {
                name = value.$typeName$;
            } else if (value && value.typeName) {
                name = value.typeName;
            }
            if (name === "TaxonomyTerm") {
                return {}
            }
313
            name = _.escape(name).split('.');
314

315 316 317 318 319
            var trem = false;
            if (value['taxonomy.namespace']) {
                trem = true;
            } else if (value.values && value.values['taxonomy.namespace']) {
                trem = true;
320 321
            } else if (name.length > 1) {
                trem = true; // Temp fix
322 323 324
            }

            if (trem) {
325 326
                return {
                    term: true,
327
                    tag: false,
328
                    name: name[name.length - 1],
329
                    fullName: name.join('.')
330 331 332 333
                }
            } else {
                return {
                    term: false,
334
                    tag: true,
335
                    name: name[name.length - 1],
336
                    fullName: name.join('.')
337
                }
338 339 340
            }
        }
    }
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    Utils.getName = function(collectionJSON, priorityAttribute) {
        if (collectionJSON) {
            if (collectionJSON.attributes && collectionJSON.attributes[priorityAttribute]) {
                return _.escape(collectionJSON.attributes[priorityAttribute]);
            }
            if (collectionJSON[priorityAttribute]) {
                return _.escape(collectionJSON[priorityAttribute]);
            }
            if (collectionJSON.attributes) {
                if (collectionJSON.attributes.name) {
                    return _.escape(collectionJSON.attributes.name);
                }
                if (collectionJSON.attributes.qualifiedName) {
                    return _.escape(collectionJSON.attributes.qualifiedName);
                }
                if (collectionJSON.attributes.id) {
                    return _.escape(collectionJSON.attributes.id);
                }
            }
            if (collectionJSON.name) {
                return _.escape(collectionJSON.name);
            }
            if (collectionJSON.qualifiedName) {
                return _.escape(collectionJSON.qualifiedName);
            }
            if (collectionJSON.displayText) {
                return _.escape(collectionJSON.displayText);
            }
            if (collectionJSON.guid) {
                return _.escape(collectionJSON.guid);
            }
            if (collectionJSON.id) {
                return _.escape(collectionJSON.id);
            }
        }
        return "-";
    }
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    Utils.showTitleLoader = function(loaderEl, titleBoxEl) {
        loaderEl.css({
            'display': 'block',
            'position': 'relative',
            'height': '85px',
            'marginTop': '85px',
            'marginLeft': '50%',
            'left': '0%'
        });
        titleBoxEl.hide();
    }
    Utils.hideTitleLoader = function(loaderEl, titleBoxEl) {
        loaderEl.hide();
        titleBoxEl.fadeIn();
    }
393
    return Utils;
394
});