javascript UTIL ...base64, setCookie, ..너무 깔끔함.
카테고리 없음 / 2011. 11. 25. 10:41
http://localhost:7402/crx/de/js/CRX/util/Util.js
/*
* Copyright 1997-2008 Day Management AG
* Barfuesserplatz 6, 4001 Basel, Switzerland
* All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Day Management AG, ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Day.
*/
/**
* The <code>CRX.utils.Util</code> library contains utility methods for CRXDE.
* @static
* @class CRX.utils.Util
*/
CRX.util.Util = function() {
var lastAuthHeader = null;
var connectionData = null;
var globalDialogs = {};
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// private method for UTF-8 encoding
var _utf8_encode = function (string) {
string = string.replace(/\\r\\n/g,'\\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var fileMap = {};
var eventObject = new Ext.util.Observable();
eventObject.addEvents("reinit");
return {
on : function(eventName, fn, scope, o) {
eventObject.on(eventName, fn, scope, o);
},
/**
* Evaluates and returns a string.
* @param {String} param The string
* @return The evaluated object
* @type Object
*/
eval: function(json) {
try {
return eval("(" + json + ")");
} catch (e) {
return null;
}
},
/**
* Returns the anchor part of the URL.
* @static
* @param {String} url The URL
* @return {String} The anchor
*/
getAnchor: function(url) {
if (url.indexOf("#") != -1) {
return url.substring(url.indexOf("#") + 1);
}
},
getURLParams: function(url) {
url = url || window.location.search;
url = url.split("?");
if (url.length > 1) {
return Ext.urlDecode(url[1]);
}
return {};
},
/**
* Returns the value of the cookie with the given name.
* @static
* @param {String} name The name of the cookie
* @return {String} The value of the cookie
*/
getCookie: function(name) {
var cname = encodeURIComponent(name) + "=";
var dc = document.cookie;
if (dc.length > 0) {
var begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
var end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return decodeURIComponent(dc.substring(begin, end));
}
}
return null;
},
/**
* Sets the value of the cookie with the given name.
* @static
* @param {String} name The name of the cookie
* @param {String} value The value of the cookie
* @param {String} path (Optional) The server path the cookie applies to
* @param {int} days (Optional) The number of days the cookie will live,
* no value creates a session cookie, 0 removes
* the cookie
* @param {String} domain (Optional) The server domain
* @param {boolean} secure (Optional) <code>true</code> if the
* connection is secure, <code>false</code> otherwise
* @return {String} The value of the cookie
*/
setCookie: function(name, value, path, days, domain, secure) {
if (days && (typeof(days) != "number")) days = 7;
var date;
if (days > 0) {
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
} else if (days == 0) {
date = new Date(1970, 0, 1);
}
document.cookie = encodeURIComponent(name) + "=" +
encodeURIComponent(value) + "; " +
(date ? "expires=" + date.toGMTString() + "; " : "") +
(domain ? "domain=" + domain + "; " : "") +
(path ? "path=" + path : "") +
(secure ? "; secure" : "");
return value;
},
// public method for encoding
base64Encode: function (input) {
var output = '';
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
},
reinit: function() {
Ext.Ajax.request({
url:CRX.Util.getContextPath() + "/de/init.jsp",
success:function(response, options) {
connectionData = CRX.Util.eval(response.responseText);
eventObject.fireEvent("reinit", this);
if (CRX.NodetypeRegistry) {
// todo: probably the wrong place, use event listener
// reload node types
CRX.NodetypeRegistry.reload(function() {
var tree = Ext.getCmp(CRX.ide.TREE_ID);
tree.setWorkspace(CRX.Util.getWorkspace());
});
}
}
});
},
/**
* Creates a new dialog or returns an existing dialog if there was already a dialog
* created with the same xtype before.
*
* @param {String/Object} config either an xtype string or a full dialog config object
* @param {Object} dialogs (optional) cache for dialogs; if omitted, a global cache will be used
**/
getDialog: function(config, dialogs) {
dialogs = dialogs || globalDialogs;
var type = typeof config === "string" ? config : config.xtype;
config = typeof config === "string" ? {xtype: type} : config;
if (!dialogs[type]) {
dialogs[type] = Ext.ComponentMgr.create(config);
}
return dialogs[type];
},
getLocalWorkspacePath: function(path) {
var localPath = path.substr(path.indexOf(CRX.ide.JCR_ROOT_NAME)
+ CRX.ide.JCR_ROOT_NAME.length);
if (localPath == "") {
localPath = "/"; // it the root node
}
return decodeURIComponent(localPath);
},
convertToTreePath: function(path) {
// encode path
var labels = path.split("/");
for (var i=0; i<labels.length; i++) {
labels[i] = encodeURIComponent(labels[i]);
}
path = labels.join("/");
return "/" + CRX.Util.getWorkspace() + "/" + CRX.ide.JCR_ROOT_NAME + path;
},
setWorkspaceFromPath: function(path) {
connectionData.workspace = path.substr(0, path.indexOf(CRX.ide.JCR_ROOT_NAME) - 1).substr(1);
},
setConnectionData: function(data) {
connectionData = CRX.Util.eval(data);
},
getWorkspace: function() {
return connectionData.workspace;
},
getWorkspaces: function() {
return connectionData.workspaces;
},
getLaunchpadContextPath: function() {
return connectionData.launchpadContextPath == "/" ? "" : connectionData.launchpadContextPath;
},
getSpiBaseUrl: function() {
return CRX.Util.getContextPath() + "/server";
},
getSpiRootUrl: function() {
return CRX.Util.getSpiBaseUrl()
+ "/" + CRX.Util.getWorkspace()
+ "/" + CRX.ide.JCR_ROOT_NAME;
},
getJcrVersion: function() {
return connectionData.jcrVersion;
},
getContextPath: function() {
return connectionData.contextPath;
},
getUserID: function() {
return connectionData.userID;
},
getFileExtension: function(name) {
name = name.replace(/^\s|\s$/g, ""); //trims string
if (/\.\w+$/.test(name)) {
if (name.match(/([^\/\\]+)\.(\w+)$/)) {
return RegExp.$2;
}
}
},
getDateAsISO8601: function(date) {
return date.format("Y-m-d") + "T" + date.format("H:i:s.uP");
},
isFormatISO8601: function(date) {
return Date.parseDate(date,"Y-m-dTH:i:s.uP") != undefined;
},
getErrorMsgFromXML: function(response) {
var msgs, xmlDoc = response.responseXML;
if (xmlDoc) {
if (Ext.isGecko) {
msgs = xmlDoc.getElementsByTagName("dcr:message");
return msgs[0].textContent;
} else {
msgs = xmlDoc.getElementsByTagName("message");
return msgs.item(0).textContent;
}
} else {
return "Unknown error (Error Code: " + response.status + ")";
}
},
openActionDialog: function() {
var dialogId;
var loadSelection;
if (this.baseAction) {
dialogId = this.baseAction.initialConfig.dialogId;
loadSelection = this.baseAction.initialConfig.loadSelection;
} else {
dialogId = this.initialConfig.dialogId;
loadSelection = this.initialConfig.loadSelection;
}
var tree = Ext.getCmp(CRX.ide.TREE_ID);
var node = tree.getSelectionModel().getSelectedNode();
if (node) {
var dlg = CRX.Util.getDialog(dialogId);
dlg.init(node);
if (Ext.isFunction(dlg.reset)) {
dlg.reset();
}
if (loadSelection) {
var cb = function() {
dlg.show();
};
if (!node.isLoaded()) {
node.reload(cb);
} else {
cb.call();
}
} else {
dlg.show();
}
}
},
validateNodeName: function(value) {
var valid = true;
var tree = Ext.getCmp(CRX.ide.TREE_ID);
var selection = tree.getSelectionModel().getSelectedNode();
if (selection) {
var node = selection.findChild("name", value);
if (node) {
if (CRX.State.isDeleted(node.getRealPath())) {
valid = "A locally deleted node with the same name was detected. "
+"Please save changes in order to create a new node with this name.";
} else {
valid = "A node with this name already exist";
}
}
}
return valid;
// TODO validate name against child node definitions
},
createNode: function(name, text, type, parent, loader, atts, data) {
var attr = loader.processAttributes({
name:encodeURIComponent(name), text:text,
primaryType:type
}, type);
var node = loader.createNode(attr);
if (node) {
parent.appendChild(node);
var propDefs = CRX.NodetypeRegistry.getPropertyDefinitions([
node.getPrimaryType()
]);
if (!atts) {
atts = {};
}
atts[CRX.util.JCR_PRIMARY_TYPE] = type;
atts[":" + CRX.util.JCR_PRIMARY_TYPE] = CRX.util.NAME;
var records = loader.createPropertyRecords(atts, propDefs);
records.each(function(record) {
if (record.get("name") == CRX.util.JCR_DATA) {
record.set("type", CRX.util.BINARY);
if (data) {
record.set("value", data);
}
}
record.markDirty(); // ugly hack to deal with property grid
});
node.addPropertyRecords(records);
CRX.State.addTransientNode(node);
}
return node;
},
/**
* Recursive variant of Ext.applyIf(). The optional last param "r" is
* true/false (go recursive), or number (number of levels to go recursive);
* defaults to "true".
**/
applyDefaults: function(o, c, r) {
// default r to true
r = (typeof r == "undefined") ? true : r;
if (o && c) {
for (var p in c) {
if (typeof o[p] == "undefined") {
o[p] = c[p];
} else if (typeof o[p] == "object" && r) {
if (typeof r == "number") {
r--;
}
CRX.Util.applyDefaults(o[p], c[p], r);
}
}
}
return o;
},
/**
* Requests the specified URL from the server using GET. The request
* will be synchronous, unless a callback function is specified.
* @static
* @param {String} url The URL to request
* @param {Function} callback (optional) The callback function which is
* called regardless of success or failure and is passed the following
* parameters:<ul>
* <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
* <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li>
* <li><b>response</b> : Object<div class="sub-desc">The response object.</div></li>
* </ul>
* @return {Mixed} The response object or, if the
* request is asynchronous, the transaction ID
*/
httpGet: function(url, callback) {
if (callback != undefined) {
return Ext.Ajax.request({
url: url,
callback: callback
});
} else {
var request = document.all ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
try {
request.open("GET", url, false);
request.send(null);
return {
status: request.status,
body: request.responseText
};
} catch (e) {
return null;
}
}
},
/**
* Pre-caches file contents for {@link #loadFile()}.
*
* @param {String} path URL path to the file (without CRX.Util.getContentPath())
* @param {String} content file contents to cache
*/
storeFile: function(path, content) {
fileMap[path] = content;
},
/**
* Loads a server side file via Ajax and caches its contents internally.
* To pre-populate the cache, for example in a single production js file,
* {@link #storeFile()} can be used.
*
* @param {String} path URL path to the file (without CRX.Util.getContentPath(),
* but with leading slash)
* @param {Boolean} noCaching (optional) if true, the file will be fetched and not
* cached; if it was pre-cached via {@link #storeFile()}
* it will be removed from the cache. Useful for larger
* files that are used one time only
*
* @return {String} the file contents or null if not found
*/
loadFile: function(path, noCaching) {
if (fileMap[path] === undefined) {
var response = CRX.Util.httpGet( CRX.Util.getContextPath() + path );
if (response !== null && response.status == 200) {
if (noCaching) {
return response.body;
}
fileMap[path] = response.body;
return fileMap[path];
}
return null;
} else {
var content = fileMap[path];
if (noCaching) {
delete fileMap[path];
}
return content;
}
},
logout: function() {
Ext.Ajax.request({
url:CRX.Util.getContextPath() + "/de/logout.jsp",
params: {
},
success:function(response, options) {
CRX.Util.setAuthHeader("");
CRX.Util.reinit();
},
failure:function(response, options) {
}
});
return false;
},
isLoggedIn: function() {
return connectionData && connectionData.userID && connectionData.userID != "anonymous";
},
getAuthHeader: function() {
if (lastAuthHeader) {
return lastAuthHeader;
} else {
if (window.name.indexOf("Basic ") == 0) {
return window.name;
} else {
return null;
}
}
},
setAuthHeader: function(hdr) {
window.name = lastAuthHeader = hdr;
},
login: function(username, password, workspace, opts) {
Ext.Ajax.request({
url:CRX.Util.getContextPath() + "/de/login.jsp",
params: {
UserId: username,
Password: password,
Workspace: workspace,
_charset_: "utf-8",
".token": ""
},
success:function(response, options) {
// TODO: check response if token-auth is supported.
var tokenLoginSupported = !!CRX.Util.getCookie("login-token");
if (!tokenLoginSupported) {
// store auth header
CRX.Util.setAuthHeader("Basic " + CRX.Util.base64Encode(username + ":" + password));
CRX.Util.setCookie("login-workspace", workspace, CRX.Util.getContextPath());
}
if (opts.success) {
opts.success(response, options);
}
CRX.Util.reinit();
},
failure:function(response, options) {
if (opts.failure) {
opts.failure(response, options);
}
}
});
return false;
},
/**
* Utility for updating a panel body's contents regardless whether the panel
* is already rendered (ie. the body el is present) or not (ie. if called
* right after the constructor).
*/
updatePanel: function(panel, html) {
if (panel.body) {
panel.body.update(html);
} else {
panel.html = html;
}
},
/**
* Rendering bug utility that will re-set the current height of the
* Ext element or component passed.
*/
updateHeight: function(el) {
var h = el.getHeight();
el.setHeight(h + 1);
el.setHeight(h);
},
/**
* Rendering bug utility that will re-set the current width of the
* Ext element or component passed.
*/
updateWidth: function(el) {
var w = el.getWidth();
el.setWidth(w + 1);
el.setWidth(w);
}
};
}();
CRX.util.Mimetypes = function() { var mimetypes = { "css":"text/css", "html":"text/html", "js":"text/javascript", "ecma":"text/javascript", "txt":"text/plain", "xml":"text/xml", "json":"application/json", "java":"text/plain", "bnd":"text/plain", "esp":"text/plain", "jsp":"text/plain", "bmp":"image/bmp", "bmp":"image/bmp", "gif":"image/gif", "bmp":"image/bmp", "jpg":"image/jpeg", "jpeg":"image/jpeg", "bmp":"image/bmp", "png":"image/png", "tif":"image/tiff", "tiff":"image/tiff" }; return { getMimetype: function(name) { var ext = CRX.Util.getFileExtension(name); if (mimetypes[ext]) { return mimetypes[ext]; } else { return "application/octet-stream"; } }};
