Issue-id: OCS-9
[msb/apigateway.git] / msb-core / apiroute / apiroute-service / src / main / resources / iui-route / js / jquery.i18n / jquery.i18n.properties-1.0.9.js
1 /*
2  * Copyright 2016 2015-2016 ZTE, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  *     Author: Zhaoxing Meng
17  *     email: meng.zhaoxing1@zte.com.cn
18  */
19 /******************************************************************************
20  * jquery.i18n.properties
21  * 
22  * Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
23  * MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
24  * 
25  * @version     1.0.x
26  * @author      Nuno Fernandes
27  * @url         www.codingwithcoffee.com
28  * @inspiration Localisation assistance for jQuery (http://keith-wood.name/localisation.html)
29  *              by Keith Wood (kbwood{at}iinet.com.au) June 2007
30  * 
31  *****************************************************************************/
32
33 (function($) {
34 $.i18n = {};
35
36 /** Map holding bundle keys (if mode: 'map') */
37 $.i18n.map = {};
38     
39 /**
40  * Load and parse message bundle files (.properties),
41  * making bundles keys available as javascript variables.
42  * 
43  * i18n files are named <name>.js, or <name>_<language>.js or <name>_<language>_<country>.js
44  * Where:
45  *      The <language> argument is a valid ISO Language Code. These codes are the lower-case, 
46  *      two-letter codes as defined by ISO-639. You can find a full list of these codes at a 
47  *      number of sites, such as: http://www.loc.gov/standards/iso639-2/englangn.html
48  *      The <country> argument is a valid ISO Country Code. These codes are the upper-case,
49  *      two-letter codes as defined by ISO-3166. You can find a full list of these codes at a
50  *      number of sites, such as: http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
51  * 
52  * Sample usage for a bundles/Messages.properties bundle:
53  * $.i18n.properties({
54  *      name:      'Messages', 
55  *      language:  'en_US',
56  *      path:      'bundles'
57  * });
58  * @param  name                 (string/string[], optional) names of file to load (eg, 'Messages' or ['Msg1','Msg2']). Defaults to "Messages"
59  * @param  language             (string, optional) language/country code (eg, 'en', 'en_US', 'pt_PT'). if not specified, language reported by the browser will be used instead.
60  * @param  path                 (string, optional) path of directory that contains file to load
61  * @param  mode                 (string, optional) whether bundles keys are available as JavaScript variables/functions or as a map (eg, 'vars' or 'map')
62  * @param  cache        (boolean, optional) whether bundles should be cached by the browser, or forcibly reloaded on each page load. Defaults to false (i.e. forcibly reloaded)
63  * @param  encoding     (string, optional) the encoding to request for bundles. Property file resource bundles are specified to be in ISO-8859-1 format. Defaults to UTF-8 for backward compatibility.
64  * @param  callback     (function, optional) callback function to be called after script is terminated
65  */
66 $.i18n.properties = function(settings) {
67         // set up settings
68     var defaults = {
69         name:           'Messages',
70         language:       '',
71         path:           '',  
72         mode:           'vars',
73         cache:                  false,
74         encoding:       'UTF-8',
75         callback:       null
76     };
77     settings = $.extend(defaults, settings);    
78     if(settings.language === null || settings.language == '') {
79            settings.language = $.i18n.browserLang();
80         }
81         if(settings.language === null) {settings.language='';}
82         
83         // load and parse bundle files
84         var files = getFiles(settings.name);
85         for(i=0; i<files.length; i++) {
86                 // 1. load base (eg, Messages.properties)
87                 //loadAndParseFile(settings.path + files[i] + '.properties', settings);
88         // 2. with language code (eg, Messages_pt.properties)
89                 //if(settings.language.length >= 2) {
90         //    loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
91                 //}
92                 // 3. with language code and country code (eg, Messages_pt_PT.properties)
93                 // 将寻找资源文件的顺序倒置
94         if(settings.language.length >= 5) {
95             loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 5) +'.properties', settings);
96         } else if(settings.language.length >= 2) {
97             loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
98                 } else {
99                         loadAndParseFile(settings.path + files[i] + '.properties', settings);
100                 }
101         }
102         
103         // call callback
104         if(settings.callback){ settings.callback(); }
105 };
106
107
108 /**
109  * When configured with mode: 'map', allows access to bundle values by specifying its key.
110  * Eg, jQuery.i18n.prop('com.company.bundles.menu_add')
111  */
112 $.i18n.prop = function(key /* Add parameters as function arguments as necessary  */) {
113         var value = $.i18n.map[key];
114         if (value == null)
115                 return '[' + key + ']';
116         
117 //      if(arguments.length < 2) // No arguments.
118 //    //if(key == 'spv.lbl.modified') {alert(value);}
119 //              return value;
120         
121 //      if (!$.isArray(placeHolderValues)) {
122 //              // If placeHolderValues is not an array, make it into one.
123 //              placeHolderValues = [placeHolderValues];
124 //              for (var i=2; i<arguments.length; i++)
125 //                      placeHolderValues.push(arguments[i]);
126 //      }
127
128         // Place holder replacement
129         /**
130          * Tested with:
131          *   test.t1=asdf ''{0}''
132          *   test.t2=asdf '{0}' '{1}'{1}'zxcv
133          *   test.t3=This is \"a quote" 'a''{0}''s'd{fgh{ij'
134          *   test.t4="'''{'0}''" {0}{a}
135          *   test.t5="'''{0}'''" {1}
136          *   test.t6=a {1} b {0} c
137          *   test.t7=a 'quoted \\ s\ttringy' \t\t x
138          *
139          * Produces:
140          *   test.t1, p1 ==> asdf 'p1'
141          *   test.t2, p1 ==> asdf {0} {1}{1}zxcv
142          *   test.t3, p1 ==> This is "a quote" a'{0}'sd{fgh{ij
143          *   test.t4, p1 ==> "'{0}'" p1{a}
144          *   test.t5, p1 ==> "'{0}'" {1}
145          *   test.t6, p1 ==> a {1} b p1 c
146          *   test.t6, p1, p2 ==> a p2 b p1 c
147          *   test.t6, p1, p2, p3 ==> a p2 b p1 c
148          *   test.t7 ==> a quoted \ s   tringy           x
149          */
150         
151         var i;
152         if (typeof(value) == 'string') {
153         // Handle escape characters. Done separately from the tokenizing loop below because escape characters are 
154                 // active in quoted strings.
155         i = 0;
156         while ((i = value.indexOf('\\', i)) != -1) {
157                    if (value[i+1] == 't')
158                            value = value.substring(0, i) + '\t' + value.substring((i++) + 2); // tab
159                    else if (value[i+1] == 'r')
160                            value = value.substring(0, i) + '\r' + value.substring((i++) + 2); // return
161                    else if (value[i+1] == 'n')
162                            value = value.substring(0, i) + '\n' + value.substring((i++) + 2); // line feed
163                    else if (value[i+1] == 'f')
164                            value = value.substring(0, i) + '\f' + value.substring((i++) + 2); // form feed
165                    else if (value[i+1] == '\\')
166                            value = value.substring(0, i) + '\\' + value.substring((i++) + 2); // \
167                    else
168                            value = value.substring(0, i) + value.substring(i+1); // Quietly drop the character
169         }
170                 
171                 // Lazily convert the string to a list of tokens.
172                 var arr = [], j, index;
173                 i = 0;
174                 while (i < value.length) {
175                         if (value[i] == '\'') {
176                                 // Handle quotes
177                                 if (i == value.length-1)
178                                         value = value.substring(0, i); // Silently drop the trailing quote
179                                 else if (value[i+1] == '\'')
180                                         value = value.substring(0, i) + value.substring(++i); // Escaped quote
181                                 else {
182                                         // Quoted string
183                                         j = i + 2;
184                                         while ((j = value.indexOf('\'', j)) != -1) {
185                                                 if (j == value.length-1 || value[j+1] != '\'') {
186                                                         // Found start and end quotes. Remove them
187                                                         value = value.substring(0,i) + value.substring(i+1, j) + value.substring(j+1);
188                                                         i = j - 1;
189                                                         break;
190                                                 }
191                                                 else {
192                                                         // Found a double quote, reduce to a single quote.
193                                                         value = value.substring(0,j) + value.substring(++j);
194                                                 }
195                                         }
196                                         
197                                         if (j == -1) {
198                                                 // There is no end quote. Drop the start quote
199                                                 value = value.substring(0,i) + value.substring(i+1);
200                                         }
201                                 }
202                         }
203                         else if (value[i] == '{') {
204                                 // Beginning of an unquoted place holder.
205                                 j = value.indexOf('}', i+1);
206                                 if (j == -1)
207                                         i++; // No end. Process the rest of the line. Java would throw an exception
208                                 else {
209                                         // Add 1 to the index so that it aligns with the function arguments.
210                                         index = parseInt(value.substring(i+1, j));
211                                         if (!isNaN(index) && index >= 0) {
212                                                 // Put the line thus far (if it isn't empty) into the array
213                                                 var s = value.substring(0, i);
214                                                 if (s != "")
215                                                         arr.push(s);
216                                                 // Put the parameter reference into the array
217                                                 arr.push(index);
218                                                 // Start the processing over again starting from the rest of the line.
219                                                 i = 0;
220                                                 value = value.substring(j+1);
221                                         }
222                                         else
223                                                 i = j + 1; // Invalid parameter. Leave as is.
224                                 }
225                         }
226                         else
227                                 i++;
228                 }
229                 
230                 // Put the remainder of the no-empty line into the array.
231                 if (value != "")
232                         arr.push(value);
233                 value = arr;
234                 
235                 // Make the array the value for the entry.
236                 $.i18n.map[key] = arr;
237         }
238         
239         if (value.length == 0)
240                 return "";
241         if (value.lengh == 1 && typeof(value[0]) == "string")
242                 return value[0];
243         
244         var s = "";
245         for (i=0; i<value.length; i++) {
246                 if (typeof(value[i]) == "string")
247                         s += value[i];
248                 // Must be a number
249                 else if (value[i] + 1 < arguments.length)
250                         s += arguments[value[i] + 1];
251                 else
252                         s += "{"+ value[i] +"}";
253         }
254         
255         return s;
256 };
257
258 /** Language reported by browser, normalized code */
259 $.i18n.browserLang = function() {
260         return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
261 }
262
263
264 /** Load and parse .properties files */
265 function loadAndParseFile(filename, settings) {
266         $.ajax({
267         url:        filename,
268         async:      false,
269         cache:          settings.cache,
270         contentType:'text/plain;charset='+ settings.encoding,
271         dataType:   'text',
272         success:    function(data, status) {
273                                         parseData(data, settings.mode); 
274                                         }
275     });
276 }
277
278 /** Parse .properties files */
279 function parseData(data, mode) {
280    var parsed = '';
281    var parameters = data.split( /\n/ );
282    var regPlaceHolder = /(\{\d+\})/g;
283    var regRepPlaceHolder = /\{(\d+)\}/g;
284    var unicodeRE = /(\\u.{4})/ig;
285    for(var i=0; i<parameters.length; i++ ) {
286        parameters[i] = parameters[i].replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
287        if(parameters[i].length > 0 && parameters[i].match("^#")!="#") { // skip comments
288            var pair = parameters[i].split('=');
289            if(pair.length > 0) {
290                /** Process key & value */
291                var name = unescape(pair[0]).replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
292                var value = pair.length == 1 ? "" : pair[1];
293                // process multi-line values
294                while(value.match(/\\$/)=="\\") {
295                         value = value.substring(0, value.length - 1);
296                         value += parameters[++i].replace( /\s\s*$/, '' ); // right trim
297                }               
298                // Put values with embedded '='s back together
299                for(var s=2;s<pair.length;s++){ value +='=' + pair[s]; }
300                value = value.replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
301                
302                /** Mode: bundle keys in a map */
303                if(mode == 'map' || mode == 'both') {
304                    // handle unicode chars possibly left out
305                    var unicodeMatches = value.match(unicodeRE);
306                    if(unicodeMatches) {
307                      for(var u=0; u<unicodeMatches.length; u++) {
308                         value = value.replace( unicodeMatches[u], unescapeUnicode(unicodeMatches[u]));
309                      }
310                    }
311                    // add to map
312                    $.i18n.map[name] = value;
313                }
314                
315                /** Mode: bundle keys as vars/functions */
316                if(mode == 'vars' || mode == 'both') {
317                    value = value.replace( /"/g, '\\"' ); // escape quotation mark (")
318                    
319                    // make sure namespaced key exists (eg, 'some.key') 
320                    checkKeyNamespace(name);
321                    
322                    // value with variable substitutions
323                    if(regPlaceHolder.test(value)) {
324                        var parts = value.split(regPlaceHolder);
325                        // process function args
326                        var first = true;
327                        var fnArgs = '';
328                        var usedArgs = [];
329                        for(var p=0; p<parts.length; p++) {
330                            if(regPlaceHolder.test(parts[p]) && (usedArgs.length == 0 || usedArgs.indexOf(parts[p]) == -1)) {
331                                if(!first) {fnArgs += ',';}
332                                fnArgs += parts[p].replace(regRepPlaceHolder, 'v$1');
333                                usedArgs.push(parts[p]);
334                                first = false;
335                            }
336                        }
337                        parsed += name + '=function(' + fnArgs + '){';
338                        // process function body
339                        var fnExpr = '"' + value.replace(regRepPlaceHolder, '"+v$1+"') + '"';
340                        parsed += 'return ' + fnExpr + ';' + '};';
341                        
342                    // simple value
343                    }else{
344                        parsed += name+'="'+value+'";';
345                    }
346                } // END: Mode: bundle keys as vars/functions
347            } // END: if(pair.length > 0)
348        } // END: skip comments
349    }
350    eval(parsed);
351 }
352
353 /** Make sure namespace exists (for keys with dots in name) */
354 // TODO key parts that start with numbers quietly fail. i.e. month.short.1=Jan
355 function checkKeyNamespace(key) {
356         var regDot = /\./;
357         if(regDot.test(key)) {
358                 var fullname = '';
359                 var names = key.split( /\./ );
360                 for(var i=0; i<names.length; i++) {
361                         if(i>0) {fullname += '.';}
362                         fullname += names[i];
363                         if(eval('typeof '+fullname+' == "undefined"')) {
364                                 eval(fullname + '={};');
365                         }
366                 }
367         }
368 }
369
370 /** Make sure filename is an array */
371 function getFiles(names) {
372         return (names && names.constructor == Array) ? names : [names];
373 }
374
375 /** Ensure language code is in the format aa_AA. */
376 function normaliseLanguageCode(lang) {
377     lang = lang.toLowerCase();
378     if(lang.length > 3) {
379         lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
380     }
381     return lang;
382 }
383
384 /** Unescape unicode chars ('\u00e3') */
385 function unescapeUnicode(str) {
386   // unescape unicode codes
387   var codes = [];
388   var code = parseInt(str.substr(2), 16);
389   if (code >= 0 && code < Math.pow(2, 16)) {
390      codes.push(code);
391   }
392   // convert codes to text
393   var unescaped = '';
394   for (var i = 0; i < codes.length; ++i) {
395     unescaped += String.fromCharCode(codes[i]);
396   }
397   return unescaped;
398 }
399
400 /* Cross-Browser Split 1.0.1
401 (c) Steven Levithan <stevenlevithan.com>; MIT License
402 An ECMA-compliant, uniform cross-browser split method */
403 var cbSplit;
404 // avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
405 if (!cbSplit) {    
406   cbSplit = function(str, separator, limit) {
407       // if `separator` is not a regex, use the native `split`
408       if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
409         if(typeof cbSplit._nativeSplit == "undefined")
410           return str.split(separator, limit);
411         else
412           return cbSplit._nativeSplit.call(str, separator, limit);
413       }
414   
415       var output = [],
416           lastLastIndex = 0,
417           flags = (separator.ignoreCase ? "i" : "") +
418                   (separator.multiline  ? "m" : "") +
419                   (separator.sticky     ? "y" : ""),
420           separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
421           separator2, match, lastIndex, lastLength;
422   
423       str = str + ""; // type conversion
424       if (!cbSplit._compliantExecNpcg) {
425           separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
426       }
427   
428       /* behavior for `limit`: if it's...
429       - `undefined`: no limit.
430       - `NaN` or zero: return an empty array.
431       - a positive number: use `Math.floor(limit)`.
432       - a negative number: no limit.
433       - other: type-convert, then use the above rules. */
434       if (limit === undefined || +limit < 0) {
435           limit = Infinity;
436       } else {
437           limit = Math.floor(+limit);
438           if (!limit) {
439               return [];
440           }
441       }
442   
443       while (match = separator.exec(str)) {
444           lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
445   
446           if (lastIndex > lastLastIndex) {
447               output.push(str.slice(lastLastIndex, match.index));
448   
449               // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
450               if (!cbSplit._compliantExecNpcg && match.length > 1) {
451                   match[0].replace(separator2, function () {
452                       for (var i = 1; i < arguments.length - 2; i++) {
453                           if (arguments[i] === undefined) {
454                               match[i] = undefined;
455                           }
456                       }
457                   });
458               }
459   
460               if (match.length > 1 && match.index < str.length) {
461                   Array.prototype.push.apply(output, match.slice(1));
462               }
463   
464               lastLength = match[0].length;
465               lastLastIndex = lastIndex;
466   
467               if (output.length >= limit) {
468                   break;
469               }
470           }
471   
472           if (separator.lastIndex === match.index) {
473               separator.lastIndex++; // avoid an infinite loop
474           }
475       }
476   
477       if (lastLastIndex === str.length) {
478           if (lastLength || !separator.test("")) {
479               output.push("");
480           }
481       } else {
482           output.push(str.slice(lastLastIndex));
483       }
484   
485       return output.length > limit ? output.slice(0, limit) : output;
486   };
487   
488   cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
489   cbSplit._nativeSplit = String.prototype.split;
490
491 } // end `if (!cbSplit)`
492 String.prototype.split = function (separator, limit) {
493     return cbSplit(this, separator, limit);
494 };
495
496 })(jQuery);
497