<commit_before>define([

"dojo/_base/xhr", "dojo/_base/lang", "dojo/json", "dojo/_base/declare", "dojo/store/util/QueryResults"

], function(xhr, lang, JSON, declare, QueryResults /*=====, Store =====*/){

// No base class, but for purposes of documentation, the base class is dojo/store/api/Store
var base = null;
/*===== base = Store; =====*/

/*=====
var __HeaderOptions = {
		// headers: Object?
		//		Additional headers to send along with the request.
	},
	__PutDirectives = declare(Store.PutDirectives, __HeaderOptions),
	__QueryOptions = declare(Store.QueryOptions, __HeaderOptions);
=====*/

return declare("dojo.store.JsonRest", base, {
	// summary:
	//		This is a basic store for RESTful communicating with a server through JSON
	//		formatted data. It implements dojo/store/api/Store.

	constructor: function(options){
		// summary:
		//		This is a basic store for RESTful communicating with a server through JSON
		//		formatted data.
		// options: dojo/store/JsonRest
		//		This provides any configuration information that will be mixed into the store
		this.headers = {};
		declare.safeMixin(this, options);
	},

	// headers: Object
	//		Additional headers to pass in all requests to the server. These can be overridden
	//		by passing additional headers to calls to the store.
	headers: {},

	// target: String
	//		The target base URL to use for all requests to the server. This string will be
	//		prepended to the id to generate the URL (relative or absolute) for requests
	//		sent to the server
	target: "",

	// idProperty: String
	//		Indicates the property to use as the identity property. The values of this
	//		property should be unique.
	idProperty: "id",

	// sortParam: String
	//		The query parameter to used for holding sort information. If this is omitted, than
	//		the sort information is included in a functional query token to avoid colliding
	//		with the set of name/value pairs.

	get: function(id, options){
		// summary:
		//		Retrieves an object by its identity. This will trigger a GET request to the server using
		//		the url `this.target + id`.
		// id: Number
		//		The identity to use to lookup the object
		// options: Object?
		//		HTTP headers. For consistency with other methods, if a `headers` key exists on this object, it will be
		//		used to provide HTTP headers instead.
		// returns: Object
		//		The object in the store that matches the given id.
		options = options || {};
		var headers = lang.mixin({ Accept: this.accepts }, this.headers, options.headers || options);
		return xhr("GET", {
      timeout: 8000, // MERC

			url: this.target + id,
			handleAs: "json",
			headers: headers
		});
	},

	// accepts: String
	//		Defines the Accept header to use on HTTP requests
	accepts: "application/javascript, application/json",

	getIdentity: function(object){
		// summary:
		//		Returns an object's identity
		// object: Object
		//		The object to get the identity from
		// returns: Number
		return object[this.idProperty];
	},

	put: function(object, options){
		// summary:
		//		Stores an object. This will trigger a PUT request to the server
		//		if the object has an id, otherwise it will trigger a POST request.
		// object: Object
		//		The object to store.
		// options: __PutDirectives?
		//		Additional metadata for storing the data.  Includes an "id"
		//		property if a specific id is to be used.
		// returns: dojo/_base/Deferred
		options = options || {};
		var id = ("id" in options) ? options.id : this.getIdentity(object);
		var hasId = typeof id != "undefined";
		return xhr(hasId && !options.incremental ? "PUT" : "POST", {
        timeout: 8000, // MERC
				url: hasId ? this.target + id : this.target,
				postData: JSON.stringify(object),
				handleAs: "json",
				headers: lang.mixin({
					"Content-Type": "application/json",
					Accept: this.accepts,
					"If-Match": options.overwrite === true ? "*" : null,
					"If-None-Match": options.overwrite === false ? "*" : null
				}, this.headers, options.headers)
			});
	},

	add: function(object, options){
		// summary:
		//		Adds an object. This will trigger a PUT request to the server
		//		if the object has an id, otherwise it will trigger a POST request.
		// object: Object
		//		The object to store.
		// options: __PutDirectives?
		//		Additional metadata for storing the data.  Includes an "id"
		//		property if a specific id is to be used.
		options = options || {};
		options.overwrite = false;
		return this.put(object, options);
	},

	remove: function(id, options){
		// summary:
		//		Deletes an object by its identity. This will trigger a DELETE request to the server.
		// id: Number
		//		The identity to use to delete the object
		// options: __HeaderOptions?
		//		HTTP headers.
		options = options || {};
		return xhr("DELETE", {
      timeout: 8000, // MERC
			url: this.target + id,
			headers: lang.mixin({}, this.headers, options.headers)
		});
	},

	query: function(query, options){
		// summary:
		//		Queries the store for objects. This will trigger a GET request to the server, with the
		//		query added as a query string.
		// query: Object
		//		The query to use for retrieving objects from the store.
		// options: __QueryOptions?
		//		The optional arguments to apply to the resultset.
		// returns: dojo/store/api/Store.QueryResults
		//		The results of the query, extended with iterative methods.
		options = options || {};

		var headers = lang.mixin({ Accept: this.accepts }, this.headers, options.headers);

		if(options.start >= 0 || options.count >= 0){
			headers.Range = headers["X-Range"] //set X-Range for Opera since it blocks "Range" header
				 = "items=" + (options.start || '0') + '-' +
				(("count" in options && options.count != Infinity) ?
					(options.count + (options.start || 0) - 1) : '');
		}
		var hasQuestionMark = this.target.indexOf("?") > -1;
		if(query && typeof query == "object"){
			query = xhr.objectToQuery(query);
			query = query ? (hasQuestionMark ? "&" : "?") + query: "";
		}
		if(options && options.sort){
			var sortParam = this.sortParam;
			query += (query || hasQuestionMark ? "&" : "?") + (sortParam ? sortParam + '=' : "sort(");
			for(var i = 0; i<options.sort.length; i++){
				var sort = options.sort[i];
				query += (i > 0 ? "," : "") + (sort.descending ? '-' : '+') + encodeURIComponent(sort.attribute);
			}
			if(!sortParam){
				query += ")";
			}
		}
		var results = xhr("GET", {

      timeout: 8000, // MERC

			url: this.target + (query || ""),
			handleAs: "json",
			headers: headers
		});
		results.total = results.then(function(){
			var range = results.ioArgs.xhr.getResponseHeader("Content-Range");
			return range && (range = range.match(/\/(.*)/)) && +range[1];
		});
		return QueryResults(results);
	}
});

});
<commit_msg>Added 10 seconds to the timeout<commit_after>define([

"dojo/_base/xhr", "dojo/_base/lang", "dojo/json", "dojo/_base/declare", "dojo/store/util/QueryResults"

], function(xhr, lang, JSON, declare, QueryResults /*=====, Store =====*/){

// No base class, but for purposes of documentation, the base class is dojo/store/api/Store
var base = null;
/*===== base = Store; =====*/

/*=====
var __HeaderOptions = {
		// headers: Object?
		//		Additional headers to send along with the request.
	},
	__PutDirectives = declare(Store.PutDirectives, __HeaderOptions),
	__QueryOptions = declare(Store.QueryOptions, __HeaderOptions);
=====*/

return declare("dojo.store.JsonRest", base, {
	// summary:
	//		This is a basic store for RESTful communicating with a server through JSON
	//		formatted data. It implements dojo/store/api/Store.

	constructor: function(options){
		// summary:
		//		This is a basic store for RESTful communicating with a server through JSON
		//		formatted data.
		// options: dojo/store/JsonRest
		//		This provides any configuration information that will be mixed into the store
		this.headers = {};
		declare.safeMixin(this, options);
	},

	// headers: Object
	//		Additional headers to pass in all requests to the server. These can be overridden
	//		by passing additional headers to calls to the store.
	headers: {},

	// target: String
	//		The target base URL to use for all requests to the server. This string will be
	//		prepended to the id to generate the URL (relative or absolute) for requests
	//		sent to the server
	target: "",

	// idProperty: String
	//		Indicates the property to use as the identity property. The values of this
	//		property should be unique.
	idProperty: "id",

	// sortParam: String
	//		The query parameter to used for holding sort information. If this is omitted, than
	//		the sort information is included in a functional query token to avoid colliding
	//		with the set of name/value pairs.

	get: function(id, options){
		// summary:
		//		Retrieves an object by its identity. This will trigger a GET request to the server using
		//		the url `this.target + id`.
		// id: Number
		//		The identity to use to lookup the object
		// options: Object?
		//		HTTP headers. For consistency with other methods, if a `headers` key exists on this object, it will be
		//		used to provide HTTP headers instead.
		// returns: Object
		//		The object in the store that matches the given id.
		options = options || {};
		var headers = lang.mixin({ Accept: this.accepts }, this.headers, options.headers || options);
		return xhr("GET", {
      timeout: 18000, // MERC

			url: this.target + id,
			handleAs: "json",
			headers: headers
		});
	},

	// accepts: String
	//		Defines the Accept header to use on HTTP requests
	accepts: "application/javascript, application/json",

	getIdentity: function(object){
		// summary:
		//		Returns an object's identity
		// object: Object
		//		The object to get the identity from
		// returns: Number
		return object[this.idProperty];
	},

	put: function(object, options){
		// summary:
		//		Stores an object. This will trigger a PUT request to the server
		//		if the object has an id, otherwise it will trigger a POST request.
		// object: Object
		//		The object to store.
		// options: __PutDirectives?
		//		Additional metadata for storing the data.  Includes an "id"
		//		property if a specific id is to be used.
		// returns: dojo/_base/Deferred
		options = options || {};
		var id = ("id" in options) ? options.id : this.getIdentity(object);
		var hasId = typeof id != "undefined";
		return xhr(hasId && !options.incremental ? "PUT" : "POST", {
        timeout: 18000, // MERC
				url: hasId ? this.target + id : this.target,
				postData: JSON.stringify(object),
				handleAs: "json",
				headers: lang.mixin({
					"Content-Type": "application/json",
					Accept: this.accepts,
					"If-Match": options.overwrite === true ? "*" : null,
					"If-None-Match": options.overwrite === false ? "*" : null
				}, this.headers, options.headers)
			});
	},

	add: function(object, options){
		// summary:
		//		Adds an object. This will trigger a PUT request to the server
		//		if the object has an id, otherwise it will trigger a POST request.
		// object: Object
		//		The object to store.
		// options: __PutDirectives?
		//		Additional metadata for storing the data.  Includes an "id"
		//		property if a specific id is to be used.
		options = options || {};
		options.overwrite = false;
		return this.put(object, options);
	},

	remove: function(id, options){
		// summary:
		//		Deletes an object by its identity. This will trigger a DELETE request to the server.
		// id: Number
		//		The identity to use to delete the object
		// options: __HeaderOptions?
		//		HTTP headers.
		options = options || {};
		return xhr("DELETE", {
      timeout: 18000, // MERC
			url: this.target + id,
			headers: lang.mixin({}, this.headers, options.headers)
		});
	},

	query: function(query, options){
		// summary:
		//		Queries the store for objects. This will trigger a GET request to the server, with the
		//		query added as a query string.
		// query: Object
		//		The query to use for retrieving objects from the store.
		// options: __QueryOptions?
		//		The optional arguments to apply to the resultset.
		// returns: dojo/store/api/Store.QueryResults
		//		The results of the query, extended with iterative methods.
		options = options || {};

		var headers = lang.mixin({ Accept: this.accepts }, this.headers, options.headers);

		if(options.start >= 0 || options.count >= 0){
			headers.Range = headers["X-Range"] //set X-Range for Opera since it blocks "Range" header
				 = "items=" + (options.start || '0') + '-' +
				(("count" in options && options.count != Infinity) ?
					(options.count + (options.start || 0) - 1) : '');
		}
		var hasQuestionMark = this.target.indexOf("?") > -1;
		if(query && typeof query == "object"){
			query = xhr.objectToQuery(query);
			query = query ? (hasQuestionMark ? "&" : "?") + query: "";
		}
		if(options && options.sort){
			var sortParam = this.sortParam;
			query += (query || hasQuestionMark ? "&" : "?") + (sortParam ? sortParam + '=' : "sort(");
			for(var i = 0; i<options.sort.length; i++){
				var sort = options.sort[i];
				query += (i > 0 ? "," : "") + (sort.descending ? '-' : '+') + encodeURIComponent(sort.attribute);
			}
			if(!sortParam){
				query += ")";
			}
		}
		var results = xhr("GET", {

      timeout: 18000, // MERC

			url: this.target + (query || ""),
			handleAs: "json",
			headers: headers
		});
		results.total = results.then(function(){
			var range = results.ioArgs.xhr.getResponseHeader("Content-Range");
			return range && (range = range.match(/\/(.*)/)) && +range[1];
		});
		return QueryResults(results);
	}
});

});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed 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.
 */
goog.addDependency('../../../tachyfont/backendservice.js',
    ['tachyfont.BackendService'],
    ['goog.Promise', 'goog.events', 'goog.functions', 'goog.net.EventType',
     'goog.net.XhrIo', 'tachyfont.FontInfo', 'tachyfont.GlyphBundleResponse']);
goog.addDependency('../../../tachyfont/binaryfonteditor.js',
    ['tachyfont.BinaryFontEditor'],
    []);
goog.addDependency('../../../tachyfont/browser_chrome.js',
    ['tachyfont.Browser'],
    ['goog.Promise', 'goog.log', 'goog.log.Level',
     'tachyfont.IncrementalFontUtils', 'tachyfont.Logger']);
goog.addDependency('../../../tachyfont/cff_dict.js',
    ['tachyfont.CffDict'],
    ['goog.log', 'tachyfont.BinaryFontEditor', 'tachyfont.Logger',
    'tachyfont.utils',]);
goog.addDependency('../../../tachyfont/cff_index.js',
    ['tachyfont.CffIndex'],
    ['goog.log', 'tachyfont.CffDict', 'tachyfont.Logger', 'tachyfont.utils',]);
goog.addDependency('../../../tachyfont/cff.js',
    ['tachyfont.Cff'],
    ['tachyfont.BinaryFontEditor', 'tachyfont.CffDict', 'tachyfont.CffIndex',]);
goog.addDependency('../../../tachyfont/charcmapinfo.js',
    ['tachyfont.CharCmapInfo'],
    []);
goog.addDependency('../../../tachyfont/cmap.js',
    ['tachyfont.Cmap'],
    ['goog.log', 'goog.log.Level', 'tachyfont.BinaryFontEditor',
     'tachyfont.Logger', 'tachyfont.Reporter', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/demobackendservice.js',
    ['tachyfont.DemoBackendService'],
    ['tachyfont.BackendService']);
goog.addDependency('../../../tachyfont/fontinfo.js',
    ['tachyfont.FontInfo'],
    []);
goog.addDependency('../../../tachyfont/fontsinfo.js',
    ['tachyfont.FontsInfo'],
    ['tachyfont.FontInfo']);
goog.addDependency('../../../tachyfont/glyphbundleresponse.js',
    ['tachyfont.GlyphBundleResponse'],
    ['tachyfont.BinaryFontEditor']);
goog.addDependency('../../../tachyfont/googlebackendservice.js',
    ['tachyfont.GoogleBackendService'],
    ['goog.Promise', 'tachyfont.BackendService', 'tachyfont.FontInfo',
     'tachyfont.utils']);
goog.addDependency('../../../tachyfont/incrementalfont.js',
    ['tachyfont.IncrementalFont'],
    ['goog.Promise', 'goog.log', 'goog.log.Level', 'goog.math',
     'tachyfont.BinaryFontEditor', 'tachyfont.Browser', 'tachyfont.Cmap',
     'tachyfont.DemoBackendService', 'tachyfont.GoogleBackendService',
     'tachyfont.IncrementalFontUtils', 'tachyfont.Logger', 'tachyfont.Persist',
     'tachyfont.RLEDecoder', 'tachyfont.Reporter', 'tachyfont.chainedPromises',
     'tachyfont.promise', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/incrementalfontutils.js',
    ['tachyfont.IncrementalFontUtils'],
    ['goog.asserts', 'goog.log', 'goog.log.Level', 'tachyfont.BinaryFontEditor',
     'tachyfont.CharCmapInfo', 'tachyfont.FontInfo', 'tachyfont.Logger']);
goog.addDependency('../../../tachyfont/persist_idb.js',
    ['tachyfont.Persist'],
    ['goog.Promise', 'goog.log', 'tachyfont.Logger', 'tachyfont.Reporter',
    'tachyfont.utils']);
goog.addDependency('../../../tachyfont/rledecoder.js',
    ['tachyfont.RLEDecoder'],
    []);
goog.addDependency('../../../tachyfont/sfnt.js',
    ['tachyfont.sfnt'],
    ['tachyfont.BinaryFontEditor']);
goog.addDependency('../../../tachyfont/tachyfont.js',
    ['tachyfont', 'tachyfont.TachyFont'],
    ['goog.Promise', 'goog.Uri', 'goog.debug.Console', 'goog.debug.Logger',
     'goog.log', 'goog.log.Level', 'tachyfont.FontsInfo',
     'tachyfont.IncrementalFont', 'tachyfont.IncrementalFontUtils',
     'tachyfont.Logger', 'tachyfont.Reporter',
     'tachyfont.TachyFontSet', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/tachyfontlogger.js',
    [ 'tachyfont.Logger'],
    ['goog.log']);
goog.addDependency('../../../tachyfont/tachyfontpromise.js',
    [ 'tachyfont.chainedPromises', 'tachyfont.promise'],
    ['goog.Promise', 'goog.log', 'goog.log.Level', 'tachyfont.Logger',
    'tachyfont.Reporter']);
goog.addDependency('../../../tachyfont/tachyfontreporter.js',
    ['tachyfont.Reporter'],
    ['goog.log', 'tachyfont.Logger']);
goog.addDependency('../../../tachyfont/tachyfontset.js',
    ['tachyfont.TachyFontSet'],
    ['goog.Promise', 'goog.array', 'goog.log', 'goog.log.Level', 'goog.style',
     'tachyfont.IncrementalFontUtils', 'tachyfont.Logger', 'tachyfont.Reporter',
     'tachyfont.chainedPromises', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/tachyfontutils.js',
    ['tachyfont.utils', 'tachyfont.utils.IncrementalFontLoader',
    'tachyfont.utils.uint8'],
    []);
goog.addDependency('../../../tachyfont/webfonttailoralternate.js',
    ['tachyfont.webfonttailor_alternate'],
    ['tachyfont.FontInfo', 'tachyfont.FontsInfo']);
goog.addDependency('../../../tachyfont/webfonttailor.js',
    ['tachyfont.webfonttailor'],
    ['tachyfont.FontInfo', 'tachyfont.FontsInfo', 'webfonttailor.alternate']);
<commit_msg>Update the closure dependencies.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed 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.
 */
goog.addDependency('../../../tachyfont/backendservice.js',
    ['tachyfont.BackendService'],
    ['goog.Promise', 'goog.events', 'goog.functions', 'goog.net.EventType',
     'goog.net.XhrIo', 'tachyfont.FontInfo', 'tachyfont.GlyphBundleResponse']);
goog.addDependency('../../../tachyfont/binaryeditor.js',
  ['tachyfont.BinaryEditor'],
  ['tachyfont.typedef.FileInfo', 'tachyfont.typedef.uint8']);
goog.addDependency('../../../tachyfont/binaryfonteditor.js',
  ['tachyfont.BinaryFontEditor'],
  ['tachyfont.BinaryEditor', 'tachyfont.CharCmapInfo',
   'tachyfont.typedef.FileInfo', 'tachyfont.typedef.uint8']);
goog.addDependency('../../../tachyfont/browser_chrome.js',
    ['tachyfont.Browser'],
    ['goog.Promise', 'goog.log', 'goog.log.Level',
     'tachyfont.IncrementalFontUtils', 'tachyfont.Logger']);
goog.addDependency('../../../tachyfont/cff_dict.js',
    ['tachyfont.CffDict'],
    ['goog.log', 'tachyfont.BinaryFontEditor', 'tachyfont.Logger',
    'tachyfont.utils',]);
goog.addDependency('../../../tachyfont/cff_index.js',
    ['tachyfont.CffIndex'],
    ['goog.log', 'tachyfont.CffDict', 'tachyfont.Logger', 'tachyfont.utils',]);
goog.addDependency('../../../tachyfont/cff.js',
    ['tachyfont.Cff'],
    ['tachyfont.BinaryFontEditor', 'tachyfont.CffDict', 'tachyfont.CffIndex',]);
goog.addDependency('../../../tachyfont/charcmapinfo.js',
    ['tachyfont.CharCmapInfo'],
    []);
goog.addDependency('../../../tachyfont/cmap.js',
    ['tachyfont.Cmap'],
    ['goog.log', 'goog.log.Level', 'tachyfont.BinaryFontEditor',
     'tachyfont.Logger', 'tachyfont.Reporter', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/demobackendservice.js',
    ['tachyfont.DemoBackendService'],
    ['tachyfont.BackendService']);
goog.addDependency('../../../tachyfont/fontinfo.js',
    ['tachyfont.FontInfo'],
    []);
goog.addDependency('../../../tachyfont/fontsinfo.js',
    ['tachyfont.FontsInfo'],
    ['tachyfont.FontInfo']);
goog.addDependency('../../../tachyfont/glyphbundleresponse.js',
    ['tachyfont.GlyphBundleResponse'],
    ['tachyfont.BinaryFontEditor']);
goog.addDependency('../../../tachyfont/googlebackendservice.js',
    ['tachyfont.GoogleBackendService'],
    ['goog.Promise', 'tachyfont.BackendService', 'tachyfont.FontInfo',
     'tachyfont.utils']);
goog.addDependency('../../../tachyfont/incrementalfont.js',
    ['tachyfont.IncrementalFont'],
    ['goog.Promise', 'goog.log', 'goog.log.Level', 'goog.math',
     'tachyfont.BinaryFontEditor', 'tachyfont.Browser', 'tachyfont.Cmap',
     'tachyfont.DemoBackendService', 'tachyfont.GoogleBackendService',
     'tachyfont.IncrementalFontUtils', 'tachyfont.Logger', 'tachyfont.Persist',
     'tachyfont.RLEDecoder', 'tachyfont.Reporter', 'tachyfont.chainedPromises',
     'tachyfont.promise', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/incrementalfontutils.js',
    ['tachyfont.IncrementalFontUtils'],
    ['goog.asserts', 'goog.log', 'goog.log.Level', 'tachyfont.BinaryFontEditor',
     'tachyfont.CharCmapInfo', 'tachyfont.FontInfo', 'tachyfont.Logger']);
goog.addDependency('../../../tachyfont/persist_idb.js',
    ['tachyfont.Persist'],
    ['goog.Promise', 'goog.log', 'tachyfont.Logger', 'tachyfont.Reporter',
    'tachyfont.utils']);
goog.addDependency('../../../tachyfont/rledecoder.js',
    ['tachyfont.RLEDecoder'],
    []);
goog.addDependency('../../../tachyfont/sfnt.js',
    ['tachyfont.sfnt'],
    ['tachyfont.BinaryFontEditor']);
goog.addDependency('../../../tachyfont/tachyfont.js',
    ['tachyfont', 'tachyfont.TachyFont'],
    ['goog.Promise', 'goog.Uri', 'goog.debug.Console', 'goog.debug.Logger',
     'goog.log', 'goog.log.Level', 'tachyfont.FontsInfo',
     'tachyfont.IncrementalFont', 'tachyfont.IncrementalFontUtils',
     'tachyfont.Logger', 'tachyfont.Reporter',
     'tachyfont.TachyFontSet', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/tachyfontlogger.js',
    [ 'tachyfont.Logger'],
    ['goog.log']);
goog.addDependency('../../../tachyfont/tachyfontpromise.js',
    [ 'tachyfont.chainedPromises', 'tachyfont.promise'],
    ['goog.Promise', 'goog.log', 'goog.log.Level', 'tachyfont.Logger',
    'tachyfont.Reporter']);
goog.addDependency('../../../tachyfont/tachyfontreporter.js',
    ['tachyfont.Reporter'],
    ['goog.log', 'tachyfont.Logger']);
goog.addDependency('../../../tachyfont/tachyfontset.js',
    ['tachyfont.TachyFontSet'],
    ['goog.Promise', 'goog.array', 'goog.log', 'goog.log.Level', 'goog.style',
     'tachyfont.IncrementalFontUtils', 'tachyfont.Logger', 'tachyfont.Reporter',
     'tachyfont.chainedPromises', 'tachyfont.utils']);
goog.addDependency('../../../tachyfont/tachyfontutils.js',
  ['tachyfont.utils', 'tachyfont.utils.IncrementalFontLoader',
  'tachyfont.typedef.uint8'],
  []);
goog.addDependency('../../../tachyfont/typedefs.js',
  ['tachyfont.typedef', 'tachyfont.typedef.CMap12', 'tachyfont.typedef.CMap4',
   'tachyfont.typedef.CmapMapping', 'tachyfont.typedef.FileInfo',
   'tachyfont.typedef.uint8'],
  []);
goog.addDependency('../../../tachyfont/webfonttailoralternate.js',
    ['tachyfont.webfonttailor_alternate'],
    ['tachyfont.FontInfo', 'tachyfont.FontsInfo']);
goog.addDependency('../../../tachyfont/webfonttailor.js',
    ['tachyfont.webfonttailor'],
    ['tachyfont.FontInfo', 'tachyfont.FontsInfo', 'webfonttailor.alternate']);
<|endoftext|>


<commit_before>// ======================================
// Form buttons: shortcuts, AJAX improvements and form validation
// To be completed.

var XWiki = (function(XWiki) {
// Start XWiki augmentation.
var actionButtons = XWiki.actionButtons = XWiki.actionButtons || {};

actionButtons.EditActions = Class.create({
  initialize : function() {
    this.addListeners();
    this.addShortcuts();
    this.addValidators();
  },
  addListeners : function() {
    $$('input[name=action_cancel]').each(function(item) {
      item.observe('click', this.onCancel.bindAsEventListener(this));
    }.bind(this));
    $$('input[name=action_preview]').each(function(item) {
      item.observe('click', this.onPreview.bindAsEventListener(this));
    }.bind(this));
    $$('input[name=action_save]').each(function(item) {
      item.observe('click', this.onSaveAndView.bindAsEventListener(this));
    }.bind(this));
    $$('input[name=action_saveandcontinue]').each(function(item) {
      item.observe('click', this.onSaveAndContinue.bindAsEventListener(this));
    }.bind(this));
  },
  addShortcuts : function() {
    var shortcuts = {
      'action_cancel' : "$msg.get('core.shortcuts.edit.cancel')",
      'action_preview' : "$msg.get('core.shortcuts.edit.preview')",
      // The following 2 are both "Back to edit" in the preview mode, depending on the used editor
      'action_edit' : "$msg.get('core.shortcuts.edit.backtoedit')",
      'action_inline' : "$msg.get('core.shortcuts.edit.backtoedit')",
      'action_save' : "$msg.get('core.shortcuts.edit.saveandview')",
      'action_propupdate' : "$msg.get('core.shortcuts.edit.saveandview')",
      'action_saveandcontinue' : "$msg.get('core.shortcuts.edit.saveandcontinue')"
    }
    for (var key in shortcuts) {
      var targetButtons = $$("input[name=" + key + "]");
      if (targetButtons.size() > 0) {
        shortcut.add(shortcuts[key], function() {
          this.click();
        }.bind(targetButtons.first()), {'propagate' : false} );
      }
    }
  },
  validators : new Array(),
  addValidators : function() {
    // Add live presence validation for inputs with classname 'required'.
    var inputs = $(document.body).select("input.required");
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      var validator = new LiveValidation(input, { validMessage: "" });
      validator.add(Validate.Presence, {
        failureMessage: "$msg.get('core.validation.required.message')"
      });
      validator.validate();
      this.validators.push(validator);
    }
  },
  validateForm : function(form) {
    for (var i = 0; i < this.validators.length; i++) {
      if (!this.validators[i].validate()) {
        return false;
      }
    }
    #if($xwiki.isEditCommentMandatory())
      var commentField = form.comment
      while (commentField.value == "") {
        var response = prompt("${msg.get('core.comment.prompt')}");
        if (response === null) {
          return false;
        }
        commentField.value = response;
      }
    #elseif($xwiki.isEditCommentSuggested())
      var commentField = form.comment
      if (commentField.value == "") {
        var response = prompt("${msg.get('core.comment.prompt')}");
        if (response === null) {
          return false;
        }
        commentField.value = response;
      }
    #end
    return true;
  },
  onCancel : function(event) {
    event.stop();

    // Notify others we are going to cancel
    this.notify(event, "cancel");

    var location = event.element().form.action;
    if (typeof location != "string") {
       location = event.element().form.attributes.getNamedItem("action");
       if (location) {
         location = location.nodeValue;
       } else {
         location = window.self.location.href;
       }
    }
    var parts = location.split('#', 2);
    var fragmentId = (parts.length == 2) ? parts[1] : '';
    location = parts[0];
    if (location.indexOf('?') == -1) {
      location += '?';
    }
    // Prevent a redundant request to remove the edit lock when the page unloads.
    XWiki.EditLock.setLocked(false);
    window.location = location + '&action_cancel=true' + fragmentId;
  },
  onPreview : function(event) {
    if (!this.validateForm(event.element().form)) {
      event.stop();
    } else {
      // Notify others
      this.notify(event, "preview");
    }
  },
  onSaveAndView : function(event) {
    if (!this.validateForm(event.element().form)) {
      event.stop();
    } else {
      this.notify(event, "save", {"continue" : false});
    }
  },
  onSaveAndContinue : function(event) {
    if (!this.validateForm(event.element().form)) {
      event.stop();
    } else {
      this.notify(event, "save", {"continue" : true});
    }
  },
  notify : function(event, action, params) {
    document.fire("xwiki:actions:" + action, Object.extend({originalEvent : event, form: event.element().form}, params || { }));
    // In IE, events can't be stopped from another event's handler, so we must call stop() again here
    if (event.stopped) {
      event.stop();
    }
  }
});

// ======================================
// Save and continue button: Ajax improvements
actionButtons.AjaxSaveAndContinue = Class.create({
  initialize : function() {
    this.createMessages();
    this.addListeners();
  },
  createMessages : function() {
    this.savingBox = new XWiki.widgets.Notification("Saving...", "inprogress", {inactive: true});
    this.savedBox = new XWiki.widgets.Notification("Saved", "done", {inactive: true});
    this.failedBox = new XWiki.widgets.Notification("Failed to save the document. Reason: ", "error", {inactive: true});
  },
  addListeners : function() {
    document.observe("xwiki:actions:save", this.onSave.bindAsEventListener(this));
  },
  onSave : function(event) {
    // Don't continue if the event has been stopped already
    if (event.stopped) {
      return;
    }
    if (event.memo["continue"]) {
      if (typeof (event.memo.originalEvent) != 'undefined') {
        event.memo.originalEvent.stop();
      }
      this.form = $(event.memo.form);
      this.savedBox.hide();
      this.failedBox.hide();
      this.savingBox.show();
      var formData = new Hash(this.form.serialize({hash: true, submit: 'action_saveandcontinue'}));
      formData.set('minorEdit', '1');
      if (!Prototype.Browser.Opera) {
        // Opera can't handle properly 204 responses.
        formData.set('ajax', 'true');
      }
      new Ajax.Request(this.form.action, {
        method : 'post',
        parameters : formData.toQueryString(),
        onSuccess : this.onSuccess.bindAsEventListener(this),
        on1223 : this.on1223.bindAsEventListener(this),
        on0 : this.on0.bindAsEventListener(this),
        onFailure : this.onFailure.bind(this)
      });
    }
  },
  // IE converts 204 status code into 1223...
  on1223 : function(response) {
    response.request.options.onSuccess(response);
  },
  // 0 is returned for network failures, except on IE where a strange large number (12031) is returned.
  on0 : function(response) {
    response.request.options.onFailure(response);
  },
  onSuccess : function(response) {
    // If there was a 'template' field in the form, disable it to avoid 'This document already exists' errors.
    if (this.form && this.form.template) {
      this.form.template.disabled = true;
      this.form.template.value = "";
    }
    this.savingBox.replace(this.savedBox);
    // Announce that the document has been saved
    // TODO: We should send the new version as a memo field
    document.fire("xwiki:document:saved");
  },
  onFailure : function(response) {
    this.savingBox.replace(this.failedBox);
    if (response.statusText == '' /* No response */ || response.status == 12031 /* In IE */) {
      $('ajaxRequestFailureReason').update('Server not responding');
    } else if (response.getHeader('Content-Type').match(/^\s*text\/plain/)) {
      // Regard the body of plain text responses as custom status messages.
      $('ajaxRequestFailureReason').update(response.responseText);
    } else {
      $('ajaxRequestFailureReason').update(response.statusText);
    }
    // Announce that a document save attempt has failed
    document.fire("xwiki:document:saveFailed", {'response' : response});
  }
});

function init() {
  new actionButtons.EditActions();
  // In preview mode, the &continue part of the save&continue should lead back to the edit action.
  if (!$(document.body).hasClassName("previewbody")) {
    new actionButtons.AjaxSaveAndContinue();
  }
  return true;
}

// When the document is loaded, install action buttons
(XWiki.domIsLoaded && init())
|| document.observe('xwiki:dom:loaded', init );

function updateForShortcut() {
  if (typeof(Wysiwyg) == 'undefined') {
    return;
  }
  var editors = Wysiwyg.getInstances();
  for(var hookId in editors) {
    var editor = editors[hookId];
    var plainTextArea = editor.getPlainTextArea();
    if(plainTextArea && !plainTextArea.disabled) {
      $(hookId).value = plainTextArea.value;
    } else {
      editor.getCommandManager().execute('submit');
    }
  }
}
document.observe("xwiki:actions:save", updateForShortcut);
document.observe("xwiki:actions:preview", updateForShortcut);
// End XWiki augmentation.
return XWiki;
}(XWiki || {}));
<commit_msg>[misc] XWiki.EditLock is not defined in preview mode.<commit_after>// ======================================
// Form buttons: shortcuts, AJAX improvements and form validation
// To be completed.

var XWiki = (function(XWiki) {
// Start XWiki augmentation.
var actionButtons = XWiki.actionButtons = XWiki.actionButtons || {};

actionButtons.EditActions = Class.create({
  initialize : function() {
    this.addListeners();
    this.addShortcuts();
    this.addValidators();
  },
  addListeners : function() {
    $$('input[name=action_cancel]').each(function(item) {
      item.observe('click', this.onCancel.bindAsEventListener(this));
    }.bind(this));
    $$('input[name=action_preview]').each(function(item) {
      item.observe('click', this.onPreview.bindAsEventListener(this));
    }.bind(this));
    $$('input[name=action_save]').each(function(item) {
      item.observe('click', this.onSaveAndView.bindAsEventListener(this));
    }.bind(this));
    $$('input[name=action_saveandcontinue]').each(function(item) {
      item.observe('click', this.onSaveAndContinue.bindAsEventListener(this));
    }.bind(this));
  },
  addShortcuts : function() {
    var shortcuts = {
      'action_cancel' : "$msg.get('core.shortcuts.edit.cancel')",
      'action_preview' : "$msg.get('core.shortcuts.edit.preview')",
      // The following 2 are both "Back to edit" in the preview mode, depending on the used editor
      'action_edit' : "$msg.get('core.shortcuts.edit.backtoedit')",
      'action_inline' : "$msg.get('core.shortcuts.edit.backtoedit')",
      'action_save' : "$msg.get('core.shortcuts.edit.saveandview')",
      'action_propupdate' : "$msg.get('core.shortcuts.edit.saveandview')",
      'action_saveandcontinue' : "$msg.get('core.shortcuts.edit.saveandcontinue')"
    }
    for (var key in shortcuts) {
      var targetButtons = $$("input[name=" + key + "]");
      if (targetButtons.size() > 0) {
        shortcut.add(shortcuts[key], function() {
          this.click();
        }.bind(targetButtons.first()), {'propagate' : false} );
      }
    }
  },
  validators : new Array(),
  addValidators : function() {
    // Add live presence validation for inputs with classname 'required'.
    var inputs = $(document.body).select("input.required");
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      var validator = new LiveValidation(input, { validMessage: "" });
      validator.add(Validate.Presence, {
        failureMessage: "$msg.get('core.validation.required.message')"
      });
      validator.validate();
      this.validators.push(validator);
    }
  },
  validateForm : function(form) {
    for (var i = 0; i < this.validators.length; i++) {
      if (!this.validators[i].validate()) {
        return false;
      }
    }
    #if($xwiki.isEditCommentMandatory())
      var commentField = form.comment
      while (commentField.value == "") {
        var response = prompt("${msg.get('core.comment.prompt')}");
        if (response === null) {
          return false;
        }
        commentField.value = response;
      }
    #elseif($xwiki.isEditCommentSuggested())
      var commentField = form.comment
      if (commentField.value == "") {
        var response = prompt("${msg.get('core.comment.prompt')}");
        if (response === null) {
          return false;
        }
        commentField.value = response;
      }
    #end
    return true;
  },
  onCancel : function(event) {
    event.stop();

    // Notify others we are going to cancel
    this.notify(event, "cancel");

    var location = event.element().form.action;
    if (typeof location != "string") {
       location = event.element().form.attributes.getNamedItem("action");
       if (location) {
         location = location.nodeValue;
       } else {
         location = window.self.location.href;
       }
    }
    var parts = location.split('#', 2);
    var fragmentId = (parts.length == 2) ? parts[1] : '';
    location = parts[0];
    if (location.indexOf('?') == -1) {
      location += '?';
    }
    // Prevent a redundant request to remove the edit lock when the page unloads.
    XWiki.EditLock && XWiki.EditLock.setLocked(false);
    window.location = location + '&action_cancel=true' + fragmentId;
  },
  onPreview : function(event) {
    if (!this.validateForm(event.element().form)) {
      event.stop();
    } else {
      // Notify others
      this.notify(event, "preview");
    }
  },
  onSaveAndView : function(event) {
    if (!this.validateForm(event.element().form)) {
      event.stop();
    } else {
      this.notify(event, "save", {"continue" : false});
    }
  },
  onSaveAndContinue : function(event) {
    if (!this.validateForm(event.element().form)) {
      event.stop();
    } else {
      this.notify(event, "save", {"continue" : true});
    }
  },
  notify : function(event, action, params) {
    document.fire("xwiki:actions:" + action, Object.extend({originalEvent : event, form: event.element().form}, params || { }));
    // In IE, events can't be stopped from another event's handler, so we must call stop() again here
    if (event.stopped) {
      event.stop();
    }
  }
});

// ======================================
// Save and continue button: Ajax improvements
actionButtons.AjaxSaveAndContinue = Class.create({
  initialize : function() {
    this.createMessages();
    this.addListeners();
  },
  createMessages : function() {
    this.savingBox = new XWiki.widgets.Notification("Saving...", "inprogress", {inactive: true});
    this.savedBox = new XWiki.widgets.Notification("Saved", "done", {inactive: true});
    this.failedBox = new XWiki.widgets.Notification("Failed to save the document. Reason: ", "error", {inactive: true});
  },
  addListeners : function() {
    document.observe("xwiki:actions:save", this.onSave.bindAsEventListener(this));
  },
  onSave : function(event) {
    // Don't continue if the event has been stopped already
    if (event.stopped) {
      return;
    }
    if (event.memo["continue"]) {
      if (typeof (event.memo.originalEvent) != 'undefined') {
        event.memo.originalEvent.stop();
      }
      this.form = $(event.memo.form);
      this.savedBox.hide();
      this.failedBox.hide();
      this.savingBox.show();
      var formData = new Hash(this.form.serialize({hash: true, submit: 'action_saveandcontinue'}));
      formData.set('minorEdit', '1');
      if (!Prototype.Browser.Opera) {
        // Opera can't handle properly 204 responses.
        formData.set('ajax', 'true');
      }
      new Ajax.Request(this.form.action, {
        method : 'post',
        parameters : formData.toQueryString(),
        onSuccess : this.onSuccess.bindAsEventListener(this),
        on1223 : this.on1223.bindAsEventListener(this),
        on0 : this.on0.bindAsEventListener(this),
        onFailure : this.onFailure.bind(this)
      });
    }
  },
  // IE converts 204 status code into 1223...
  on1223 : function(response) {
    response.request.options.onSuccess(response);
  },
  // 0 is returned for network failures, except on IE where a strange large number (12031) is returned.
  on0 : function(response) {
    response.request.options.onFailure(response);
  },
  onSuccess : function(response) {
    // If there was a 'template' field in the form, disable it to avoid 'This document already exists' errors.
    if (this.form && this.form.template) {
      this.form.template.disabled = true;
      this.form.template.value = "";
    }
    this.savingBox.replace(this.savedBox);
    // Announce that the document has been saved
    // TODO: We should send the new version as a memo field
    document.fire("xwiki:document:saved");
  },
  onFailure : function(response) {
    this.savingBox.replace(this.failedBox);
    if (response.statusText == '' /* No response */ || response.status == 12031 /* In IE */) {
      $('ajaxRequestFailureReason').update('Server not responding');
    } else if (response.getHeader('Content-Type').match(/^\s*text\/plain/)) {
      // Regard the body of plain text responses as custom status messages.
      $('ajaxRequestFailureReason').update(response.responseText);
    } else {
      $('ajaxRequestFailureReason').update(response.statusText);
    }
    // Announce that a document save attempt has failed
    document.fire("xwiki:document:saveFailed", {'response' : response});
  }
});

function init() {
  new actionButtons.EditActions();
  // In preview mode, the &continue part of the save&continue should lead back to the edit action.
  if (!$(document.body).hasClassName("previewbody")) {
    new actionButtons.AjaxSaveAndContinue();
  }
  return true;
}

// When the document is loaded, install action buttons
(XWiki.domIsLoaded && init())
|| document.observe('xwiki:dom:loaded', init );

function updateForShortcut() {
  if (typeof(Wysiwyg) == 'undefined') {
    return;
  }
  var editors = Wysiwyg.getInstances();
  for(var hookId in editors) {
    var editor = editors[hookId];
    var plainTextArea = editor.getPlainTextArea();
    if(plainTextArea && !plainTextArea.disabled) {
      $(hookId).value = plainTextArea.value;
    } else {
      editor.getCommandManager().execute('submit');
    }
  }
}
document.observe("xwiki:actions:save", updateForShortcut);
document.observe("xwiki:actions:preview", updateForShortcut);
// End XWiki augmentation.
return XWiki;
}(XWiki || {}));
<|endoftext|>


<commit_before>"use strict";

var api = require("./api-utils");
var couchWrapper = require("./couch-wrapper");
var notifyio = require("./notifications");
var crypto = require("crypto");
var http = require("http");

/* register API calls */

api.register({
	method: "POST",
	path: "/users/signin",
	needAuth: false
}, function (params, response) {
	var shasum = crypto.createHash("sha512").update(params.passwd, "utf8").digest("hex");
	couchWrapper.userLogin(params.login, function (user_data) {
		if (user_data && user_data.shasum && shasum === user_data.shasum) {
			api.registerUser(user_data.uuid, params.login);
			response.setHeader("Set-Cookie", "token=" + user_data.uuid + "; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT");
			response.writeHead(204, "No Content");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "POST",
	path: "/user/signout",
	needAuth: true
}, function (params, response) {
	api.unregisterUser(params.token);
	response.setHeader("Set-Cookie", "token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT");
	response.writeHead(204, "No Content");
	response.end();
});

api.register({
	method: "POST",
	path: "/users/signup",
	needAuth: false
}, function (params, response) {
	var shasum = crypto.createHash("sha512").update(params.passwd, "utf8").digest("hex");
	params.shasum = shasum;
	// ... then delete the password
	delete params.passwd;
	couchWrapper.userCreate(params, function (uuid) {
		if (uuid) {
			api.registerUser(uuid, params.login);
			response.setHeader("Set-Cookie", "token=" + uuid + "; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT");
			response.writeHead(201, "Created");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "GET",
	path: "/user",
	needAuth: true
}, function (params, response) {
	couchWrapper.userGet(api.getLogin(params.token), function (user_object) {
		if (user_object) {
			couchWrapper.
			docByUser(api.getLogin(params.token), function (docs_list) {
				if (docs_list !== null) {
					user_object.documents = docs_list;
					response.writeHead(200, "OK");
					response.write(JSON.stringify(user_object));
				} else {
					response.writeHead(403, "Forbidden");
				}
				response.end();
			});
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

api.register({
	method: "GET",
	path: "/users/{login}",
	needAuth: true
}, function (params, response) {
	couchWrapper.userGet(params.path.login, function (user_object) {
		if (user_object) {
			couchWrapper.docByUser(params.path.login, function (docs_list) {
				if (docs_list !== null) {
					delete user_object.shasum;
					user_object.documents = docs_list;
					response.writeHead(200, "OK");
					response.write(JSON.stringify(user_object));
				} else {
					response.writeHead(403, "Forbidden");
				}
				response.end();
			});
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

api.register({
	method: "PUT",
	path: "/user",
	needAuth: true
}, function (params, response) {
	/* sanitize object */
	delete params.token;
	delete params.path;
	couchWrapper.userUpdate(params, function (success) {
		if (success) {
			response.writeHead(200, "OK");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "DELETE",
	path: "/user",
	needAuth: true
}, function (params, response) {
	couchWrapper.userDelete(api.getLogin(params.token), function (success) {
		if (success) {
			response.writeHead(204, "No Content");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
	api.unregisterUser(params.token);
});

api.register({
	method: "GET",
	path: "/users",
	needAuth: true
}, function (params, response) {
	var prefix = params.prefix || "";
	couchWrapper.userByPrefix(prefix, function (users) {
		if (users !== null) {
			if (users.length === 0) {
				response.writeHead(204, "No Content");
			} else {
				response.writeHead(200, "OK");
				response.write(JSON.stringify(users));
			}
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "POST",
	path: "/documents",
	needAuth: true
}, function (params, response) {
	/* sanitize object */
	delete params.path;
	delete params.token;
	couchWrapper.docAdd(params, function (id) {
		if (id) {
			notifyio.notifyAll(notifyio.collaboratorsLogins(params.collaborators), {type: "document", text: notifyio.notificationsOfCreation(params), id: id});
			response.writeHead(201, "Created");
			response.write(JSON.stringify(id));
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "PUT",
	path: "/documents/{id}",
	needAuth: true
}, function (params, response) {
	couchWrapper.docGet(params.docId, -1, function (old_doc) {
		if (!old_doc) {
			console.log("unable to get document with id " + params.docId);
		}
		else {
			var notifications, i;
			notifications = notifyio.notificationsOfChanges(old_doc, params, api.getLogin(params.token));
			for (i = 0; i < notifications.length; i += 1) {
				notifyio.notifyAll(notifyio.notifieds(old_doc.owner, notifyio.collaboratorsLogins(old_doc.collaborators), api.getLogin(params.token)), {type: "discussion", text: notifications[i], id: params.docId});
			}
		}

		/* sanitize doc */
		delete params.path;
		delete params.token;

		couchWrapper.docUpdate(params, function (success) {
			if (success) {
				response.writeHead(204, "No Content");
				/* looking for new discussions */
			} else {
				response.writeHead(403, "Forbidden");
			}
			response.end();
		});
	});
});

api.register({
	method: "DELETE",
	path: "/documents/{id}",
	needAuth: true
}, function (params, response) {
	couchWrapper.docDelete(params.path.id, function (success) {
		if (success) {
			response.writeHead(204, "No Content");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "GET",
	path: "/documents/{id}/versions",
	needAuth: true
}, function (params, response) {
	couchWrapper.getLastVersion(params.path.id, function (lastVersion) {
		response.writeHead(200, "OK");
		response.write(JSON.stringify({lastVersion: lastVersion}));
		response.end();
	});
});

function format_doc(doc) {
	var doc_md = {}, md = "", i;
	doc_md._id = doc._id;
	doc_md.settings = require("../md2pdf/default.json");
	md += "#" + doc.title + "\n";
	for (i = 0; i < doc.content.length; i += 16) {
		md += [doc.content[i].level + 2].join("#") + " " + doc.content[i].title;
		md += "\n";
		md += doc.content[i].content;
		md += "\n";
	}
	doc_md.content = md;
	return doc_md;
}

api.register({
	method: "GET",
	path: "/documents/{id}",
	needAuth: true
}, function (params, response) {
	couchWrapper.docGet(params.path.id, -1, function (doc) {
		if (doc !== null) {
			if (params.path.output) {
				var doc_md = format_doc(doc), req;
				req = http.request({hostname: "localhost", port: 8081, path: "/" + params.path.output, method: "POST"}, function (res) {
					response.writeHead(200, "OK");
					res.on("data", function (buffer) {
						response.write(buffer);
					});
					res.on("end", function () {
						response.end();
					});
				});
				req.write(JSON.stringify(doc_md));
				req.end();
			} else {
				response.writeHead(200, "OK");
				response.write(JSON.stringify(doc));
				response.end();
			}
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

api.register({
	method: "GET",
	path: "/documents/{id}/versions/{version}",
	needAuth: true
}, function (params, response) {
	couchWrapper.docGet(params.path.id, params.path.version, function (doc) {
		if (doc !== null) {
			if (params.path.output) {
				var doc_md = format_doc(doc), req;
				req = http.request({hostname: "localhost", port: 8081, path: "/" + params.path.output, method: "POST"}, function (res) {
					response.writeHead(200, "OK");
					res.on("data", function (buffer) {
						response.write(buffer);
					});
					res.on("end", function () {
						response.end();
					});
				});
				req.write(JSON.stringify(doc_md));
				req.end();
			} else {
				response.writeHead(200, "OK");
				response.write(JSON.stringify(doc));
				response.end();
			}
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

/* start the server */
notifyio.initIO(api.run(8080));
<commit_msg>Fix "x added you to collaborators" notification when new iteration.<commit_after>"use strict";

var api = require("./api-utils");
var couchWrapper = require("./couch-wrapper");
var notifyio = require("./notifications");
var crypto = require("crypto");
var http = require("http");

/* register API calls */

api.register({
	method: "POST",
	path: "/users/signin",
	needAuth: false
}, function (params, response) {
	var shasum = crypto.createHash("sha512").update(params.passwd, "utf8").digest("hex");
	couchWrapper.userLogin(params.login, function (user_data) {
		if (user_data && user_data.shasum && shasum === user_data.shasum) {
			api.registerUser(user_data.uuid, params.login);
			response.setHeader("Set-Cookie", "token=" + user_data.uuid + "; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT");
			response.writeHead(204, "No Content");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "POST",
	path: "/user/signout",
	needAuth: true
}, function (params, response) {
	api.unregisterUser(params.token);
	response.setHeader("Set-Cookie", "token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT");
	response.writeHead(204, "No Content");
	response.end();
});

api.register({
	method: "POST",
	path: "/users/signup",
	needAuth: false
}, function (params, response) {
	var shasum = crypto.createHash("sha512").update(params.passwd, "utf8").digest("hex");
	params.shasum = shasum;
	// ... then delete the password
	delete params.passwd;
	couchWrapper.userCreate(params, function (uuid) {
		if (uuid) {
			api.registerUser(uuid, params.login);
			response.setHeader("Set-Cookie", "token=" + uuid + "; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT");
			response.writeHead(201, "Created");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "GET",
	path: "/user",
	needAuth: true
}, function (params, response) {
	couchWrapper.userGet(api.getLogin(params.token), function (user_object) {
		if (user_object) {
			couchWrapper.
			docByUser(api.getLogin(params.token), function (docs_list) {
				if (docs_list !== null) {
					user_object.documents = docs_list;
					response.writeHead(200, "OK");
					response.write(JSON.stringify(user_object));
				} else {
					response.writeHead(403, "Forbidden");
				}
				response.end();
			});
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

api.register({
	method: "GET",
	path: "/users/{login}",
	needAuth: true
}, function (params, response) {
	couchWrapper.userGet(params.path.login, function (user_object) {
		if (user_object) {
			couchWrapper.docByUser(params.path.login, function (docs_list) {
				if (docs_list !== null) {
					delete user_object.shasum;
					user_object.documents = docs_list;
					response.writeHead(200, "OK");
					response.write(JSON.stringify(user_object));
				} else {
					response.writeHead(403, "Forbidden");
				}
				response.end();
			});
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

api.register({
	method: "PUT",
	path: "/user",
	needAuth: true
}, function (params, response) {
	/* sanitize object */
	delete params.token;
	delete params.path;
	couchWrapper.userUpdate(params, function (success) {
		if (success) {
			response.writeHead(200, "OK");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "DELETE",
	path: "/user",
	needAuth: true
}, function (params, response) {
	couchWrapper.userDelete(api.getLogin(params.token), function (success) {
		if (success) {
			response.writeHead(204, "No Content");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
	api.unregisterUser(params.token);
});

api.register({
	method: "GET",
	path: "/users",
	needAuth: true
}, function (params, response) {
	var prefix = params.prefix || "";
	couchWrapper.userByPrefix(prefix, function (users) {
		if (users !== null) {
			if (users.length === 0) {
				response.writeHead(204, "No Content");
			} else {
				response.writeHead(200, "OK");
				response.write(JSON.stringify(users));
			}
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

function notificationsOfChangedDocument(old_doc, new_doc, login) {
	var notifications = null;
	if (old_doc) {
		var i, texts;
		notifications = [];
		texts = notifyio.notificationsOfChanges(old_doc, new_doc, login);
		console.log(texts);
		for (i = 0; i < texts.length; i += 1) {
			notifications.push({type: "discussion", text: texts[i], docId: new_doc.docId});
		}
	}
	return notifications;
}

function notificationsOfNewDocument(new_doc) {
	var notifications = [];
	notifications.push({type: "document", text: notifyio.notificationsOfCreation(new_doc), docId: new_doc.docId});
	return notifications;
}

api.register({
	method: "POST",
	path: "/documents",
	needAuth: true
}, function (params, response) {
	/* sanitize object */
	delete params.path;
	delete params.token;
	couchWrapper.docAdd(params, function (id) {
		if (id) {
			if (params.version === 0) {
				var notifications, i;
				notifications = notificationsOfNewDocument(params);
				for (i = 0; i < notifications.length; i += 1) {
					notifyio.notifyAll(notifyio.notifieds(params.owner, notifyio.collaboratorsLogins(params.collaborators), api.getLogin(params.token)), notifications[i]);
				}
			} else {
				couchWrapper.docGet(params.docId, -1, function(old_doc) {
					var notifications, i;
					notifications = notificationsOfChangedDocument(old_doc, params, api.getLogin(params.token));
					for (i = 0; i < notifications.length; i += 1) {
						notifyio.notifyAll(notifyio.notifieds(old_doc.owner, notifyio.collaboratorsLogins(old_doc.collaborators), api.getLogin(params.token)), notifications[i]);
					}
				});
			}
			response.writeHead(201, "Created");
			response.write(JSON.stringify(id));
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "PUT",
	path: "/documents/{id}",
	needAuth: true
}, function (params, response) {
	couchWrapper.docGet(params.docId, -1, function (old_doc) {
		var notifications, i;
		var notifications;
		notifications = notificationsOfChangedDocument(old_doc, params, api.getLogin(params.token));
		for (i = 0; i < notifications.length; i += 1) {
			notifyio.notifyAll(notifyio.notifieds(old_doc.owner, notifyio.collaboratorsLogins(old_doc.collaborators), api.getLogin(params.token)), notifications[i]);
		}

		/* sanitize doc */
		delete params.path;
		delete params.token;
		couchWrapper.docUpdate(params, function (success) {
			if (success) {
				response.writeHead(204, "No Content");
				/* looking for new discussions */
			} else {
				response.writeHead(403, "Forbidden");
			}
			response.end();
		});
	});
});

api.register({
	method: "DELETE",
	path: "/documents/{id}",
	needAuth: true
}, function (params, response) {
	/* this is a docId */
	couchWrapper.docDelete(params.path.id, function (success) {
		if (success) {
			response.writeHead(204, "No Content");
		} else {
			response.writeHead(403, "Forbidden");
		}
		response.end();
	});
});

api.register({
	method: "GET",
	path: "/documents/{id}/versions",
	needAuth: true
}, function (params, response) {
	couchWrapper.getLastVersion(params.path.id, function (lastVersion) {
		response.writeHead(200, "OK");
		response.write(JSON.stringify({lastVersion: lastVersion}));
		response.end();
	});
});

function format_doc(doc) {
	var doc_md = {}, md = "", i;
	doc_md._id = doc._id;
	doc_md.settings = require("../md2pdf/default.json");
	md += "#" + doc.title + "\n";
	for (i = 0; i < doc.content.length; i += 16) {
		md += [doc.content[i].level + 2].join("#") + " " + doc.content[i].title;
		md += "\n";
		md += doc.content[i].content;
		md += "\n";
	}
	doc_md.content = md;
	return doc_md;
}

api.register({
	method: "GET",
	path: "/documents/{id}",
	needAuth: true
}, function (params, response) {
	couchWrapper.docGet(params.path.id, -1, function (doc) {
		if (doc !== null) {
			if (params.path.output) {
				var doc_md = format_doc(doc), req;
				req = http.request({hostname: "localhost", port: 8081, path: "/" + params.path.output, method: "POST"}, function (res) {
					response.writeHead(200, "OK");
					res.on("data", function (buffer) {
						response.write(buffer);
					});
					res.on("end", function () {
						response.end();
					});
				});
				req.write(JSON.stringify(doc_md));
				req.end();
			} else {
				response.writeHead(200, "OK");
				response.write(JSON.stringify(doc));
				response.end();
			}
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

api.register({
	method: "GET",
	path: "/documents/{id}/versions/{version}",
	needAuth: true
}, function (params, response) {
	couchWrapper.docGet(params.path.id, params.path.version, function (doc) {
		if (doc !== null) {
			if (params.path.output) {
				var doc_md = format_doc(doc), req;
				req = http.request({hostname: "localhost", port: 8081, path: "/" + params.path.output, method: "POST"}, function (res) {
					response.writeHead(200, "OK");
					res.on("data", function (buffer) {
						response.write(buffer);
					});
					res.on("end", function () {
						response.end();
					});
				});
				req.write(JSON.stringify(doc_md));
				req.end();
			} else {
				response.writeHead(200, "OK");
				response.write(JSON.stringify(doc));
				response.end();
			}
		} else {
			response.writeHead(403, "Forbidden");
			response.end();
		}
	});
});

/* start the server */
notifyio.initIO(api.run(8080));
<|endoftext|>


<commit_before>function IImageElement(data,parentContainer,globalData,placeholder){
    this.assetData = globalData.getAssetData(data.refId);
    this.path = globalData.getPath();
    this.parent.constructor.call(this,data,parentContainer,globalData,placeholder);
}
createElement(SVGBaseElement, IImageElement);

IImageElement.prototype.createElements = function(){

    var self = this;

    var imageLoaded = function(){
        self.image.setAttributeNS('http://www.w3.org/1999/xlink','href',self.path+self.assetData.p);
        self.maskedElement = self.image;
    };

    var img = new Image();
    img.addEventListener('load', imageLoaded, false);
    img.addEventListener('error', imageLoaded, false);

    img.src = this.path+this.assetData.p;

    this.parent.createElements.call(this);

    this.innerElem = document.createElementNS(svgNS,'image');
    this.innerElem.setAttribute('width',this.assetData.w+"px");
    this.innerElem.setAttribute('height',this.assetData.h+"px");
    if(this.layerElement === this.parentContainer){
        this.appendNodeToParent(this.innerElem);
    }else{
        this.layerElement.appendChild(this.innerElem);
    }

};

IImageElement.prototype.hide = function(){
    if(!this.hidden){
        this.innerElem.setAttribute('visibility','hidden');
        this.hidden = true;
    }
};

IImageElement.prototype.renderFrame = function(parentMatrix){
    var renderParent = this.parent.renderFrame.call(this,parentMatrix);
    if(renderParent===false){
        this.hide();
        return;
    }
    if(this.hidden){
        this.hidden = false;
        this.innerElem.setAttribute('visibility', 'visible');
    }
    if(!this.data.hasMask){
        if(this.finalTransform.matMdf){
            this.layerElement.setAttribute('transform','matrix('+this.finalTransform.mat.props.join(',')+')');
        }
        if(this.finalTransform.opMdf){
            this.layerElement.setAttribute('opacity',this.finalTransform.opacity);
        }
    }
};

IImageElement.prototype.destroy = function(){
    this.parent.destroy.call();
    this.innerElem =  null;
};<commit_msg>fix inner element translation<commit_after>function IImageElement(data,parentContainer,globalData,placeholder){
    this.assetData = globalData.getAssetData(data.refId);
    this.path = globalData.getPath();
    this.parent.constructor.call(this,data,parentContainer,globalData,placeholder);
}
createElement(SVGBaseElement, IImageElement);

IImageElement.prototype.createElements = function(){

    var self = this;

    var imageLoaded = function(){
        self.image.setAttributeNS('http://www.w3.org/1999/xlink','href',self.path+self.assetData.p);
        self.maskedElement = self.image;
    };

    var img = new Image();
    img.addEventListener('load', imageLoaded, false);
    img.addEventListener('error', imageLoaded, false);

    img.src = this.path+this.assetData.p;

    this.parent.createElements.call(this);

    this.innerElem = document.createElementNS(svgNS,'image');
    this.innerElem.setAttribute('width',this.assetData.w+"px");
    this.innerElem.setAttribute('height',this.assetData.h+"px");
    if(this.layerElement === this.parentContainer){
        this.appendNodeToParent(this.innerElem);
    }else{
        this.layerElement.appendChild(this.innerElem);
    }

};

IImageElement.prototype.hide = function(){
    if(!this.hidden){
        this.innerElem.setAttribute('visibility','hidden');
        this.hidden = true;
    }
};

IImageElement.prototype.renderFrame = function(parentMatrix){
    var renderParent = this.parent.renderFrame.call(this,parentMatrix);
    if(renderParent===false){
        this.hide();
        return;
    }
    if(this.hidden){
        this.hidden = false;
        this.innerElem.setAttribute('visibility', 'visible');
    }
    if(!this.data.hasMask){
        if(this.finalTransform.matMdf){
            this.innerElem.setAttribute('transform','matrix('+this.finalTransform.mat.props.join(',')+')');
        }
        if(this.finalTransform.opMdf){
            this.innerElem.setAttribute('opacity',this.finalTransform.opacity);
        }
    }
};

IImageElement.prototype.destroy = function(){
    this.parent.destroy.call();
    this.innerElem =  null;
};<|endoftext|>


<commit_before>var emr = (function($) {

    var accentMap = {
        "ä": "a", "á": "a", "à": "a", "â": "a", "ã": "a",
        "Ä": "A", "Á": "A", "À": "A", "Â": "A", "Ã": "A",
        "é": "e", "è": "e", "ê": "e", "ë": "e", "œ": "e","æ":"e",
        "É": "E", "È": "E", "Ê": "E", "Ë": "E",
        "ï": "i", "ì": "i", "í": "i", "î": "i",
        "Ï": "I", "Ì": "I", "Í": "I", "Î": "I",
        "ö": "o", "ó": "o", "ò": "o", "ô": "o", "õ": "o",
        "Ö": "O", "Ó": "O", "Ò": "O", "Ô": "O", "Õ": "O",
        "ü": "u", "ú": "u", "ù": "u", "û": "u",
        "Ü": "U", "Ú": "U", "Ù": "U", "Û": "U",
        "ÿ": "y", "Ÿ": "Y", "ñ": "n", "Ñ": "N",
        "ç": "c", "Ç": "C", "ß": "s"
    };

    var toQueryString = function(options) {
        var ret = "?";
        if (options) {
            for (key in options) {
                var val = options[key];
                if ($.isArray(val)) {
                    for (ind in val) {
                        ret += key + '=' + encodeURIComponent(val[ind]) + '&';
                    }
                } else {
                    ret += key + '=' + encodeURIComponent(val) + '&';
                }
            }
        }
        return ret;
    };

    var requireOptions = function() {
        var opts = arguments[0];
        for (var i = 1; i < arguments.length; ++i) {
            if (!opts[arguments[i]]) {
                throw "Missing option: " + arguments[i];
            }
        }
    };

    var jqObject = $();

    return {

        // just used in testing so we can replace the instance with a mock or spy as needed
        setJqObject: function(jqueryInstanceToSet)  {
            jqObject = jqueryInstanceToSet;
        },

        loadMessages: function(codes, callback) {
            if (!window.messages) {
                window.messages = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "messages", "get", { codes: codes }, function(response) {
                for (var code in response) {
                    window.messages[code] = response[code];
                }
                if (callback) {
                    callback(window.messages);
                }
            });
        },

        loadGlobalProperties: function(properties, callback) {
            if (!window.globalProperties) {
                window.globalProperties = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "globalProperties", "get", {properties: properties}, function(response) {
                for (var property in response) {
                    window.globalProperties[property] = response[property];
                }
                if (callback) {
                    callback(window.globalProperties);
                }
            });
        },

        message: function(code, defaultText) {
            if (window.messages) {
                var translated = window.messages[code];
                return translated ? translated : (defaultText ? defaultText : code);
            } else {
                return defaultText ? defaultText : code;
            }
        },

        navigateTo: function(opts) {
            var url = opts.url;
            if (opts.applicationUrl) {
                url = '/' + OPENMRS_CONTEXT_PATH
                    + (opts.applicationUrl.charAt(0) == '/' ? '' : '/')
                    + opts.applicationUrl;
            }
            if (opts.page) {
                var provider = opts.provider;
                if (provider == null) {
                    provider = "*"
                }
                url = this.pageLink(provider, opts.page, opts.query);
            }
            location.href = url;
        },

        pageLink: function(providerName, pageName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + pageName + '.page';
            return ret + toQueryString(options);
        },

        resourceLink: function(providerName, resourceName) {
            if (providerName == null)
                providerName = '*';
            return '/' + OPENMRS_CONTEXT_PATH + '/ms/uiframework/resource/' + providerName + '/' + resourceName;
        },

        fragmentActionLink: function(providerName, fragmentName, actionName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + fragmentName + '/' + actionName + '.action';
            return ret += toQueryString(options);
        },

        getFragmentActionWithCallback: function(providerName, fragmentName, actionName, options, callback, errorCallback) {
            if (!errorCallback) {
                errorCallback = function(xhr) {
                    emr.handleError(xhr);
                };
            }
            var url = this.fragmentActionLink(providerName, fragmentName, actionName, options);
            $.getJSON(url).success(callback).error(errorCallback);
        },

        /*
         * opts should contain:
         *   provider (defaults to '*')
         *   fragment
         *   action
         *   query, e.g. { q: "bob", checkedInAt: 5 }
         *   resultTarget e.g. '#search-results'
         *   resultTemplate (should be an underscore template)
         */
        ajaxSearch: function(opts) {
            var provider = opts.provider;
            if (!provider) {
                provider = '*';
            }
            var url = this.fragmentActionLink(provider, opts.fragment, opts.action);
            var target = $(opts.resultTarget);
            $.getJSON(url, opts.query)
                .success(function(data) {
                    target.html('');
                    jq.each(data, function(i, result) {
                        jq(opts.resultTemplate(result)).appendTo(target);
                    });
                })
                .error(function(err) {
                    emr.errorMessage(err);
                });
        },

        successMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        errorMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                                              position: 'top-right',
                                              sticky: true,
                                              text:  emr.message(message) } );
        },

        alertMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'alert',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        successAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } );
        },

        errorAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } )
        },

        handleError: function(xhr) {
            emr.handleParsedError(jq.parseJSON(xhr.responseText), xhr.status);
        },

        handleParsedError: function(data, status) {
            if (!emr.redirectOnAuthenticationFailure(status)) {
                if (data.globalErrors) {
                    emr.errorAlert(data.globalErrors[0]);
                } else if (data.error.message) {
                    emr.errorAlert(data.error.message);
                } else {
                    emr.errorAlert("Error!");
                }
            }
        },

        redirectOnAuthenticationFailure: function (status) {
            if (status == 403) {
                window.location = '/' + OPENMRS_CONTEXT_PATH;
                return true;
            }
            return false;
        },

        updateBreadcrumbs: function(extraBreadcrumbs) {
            if (!Array.isArray(breadcrumbs)) {
                // In case the page defines no JS var called breadcrumbs, but does have an html element with that id
                return;
            }
            var toUse = breadcrumbs;
            if (extraBreadcrumbs) {
                toUse = _.clone(breadcrumbs);
                if (extraBreadcrumbs == null || extraBreadcrumbs.length == 0) {
                    var index = toUse.length - 1;
                    var modified = _.clone(toUse[index]);
                    if(modified.link !=null){
                        modified.link = null;
                    }
                    toUse[index] = modified;
                }
                _.each(extraBreadcrumbs, function(item) {
                    toUse.push(item);
                })
            }
            $('#breadcrumbs').html(this.generateBreadcrumbHtml(toUse));
        },

        generateBreadcrumbHtml: function(breadcrumbs) {
            var breadcrumbTemplate = _.template($('#breadcrumb-template').html());
            var html = "";

            _.each(breadcrumbs, function(item, index) {
                html += breadcrumbTemplate({ breadcrumb: item, first: index == 0, last: index == breadcrumbs.length-1 });
            });
            return html;
        },

        /*
         * returns an object with show() and close() functions
         */
        setupConfirmationDialog: function(opts) {
            requireOptions(opts, 'selector');
            var element = $(opts.selector);
            element.hide();
            if (opts.actions) {
                if (opts.actions.confirm) {
                    element.find(".confirm").unbind('click');
                    element.find(".confirm").click(opts.actions.confirm);
                }
                if (opts.actions.cancel) {
                    element.find(".cancel").unbind('click');
                    element.find(".cancel").click(opts.actions.cancel);
                }
            }

            var dialogApi = {};
            var dialogOpts = {
                overlayClose: true,
                overlayId: "modal-overlay",
                opacity: 80,
                persist: true,
                closeClass: "cancel"
            };
            if (opts.dialogOpts) {
                $.extend(dialogOpts, opts.dialogOpts);
            }

            dialogApi.show = function() {
                $(opts.selector).modal(dialogOpts);
            };
            dialogApi.close = function() {
                $.modal.close();
            };

           return dialogApi;
        },

        stripAccents: function(term) {
            var ret = "";
            for ( var i = 0; i < term.length; i++ ) {
                ret += accentMap[ term.charAt(i) ] || term.charAt(i);
            }
            return ret;
        },

        formatAsHtml: function(str) {
            return str.replace(/\n/g,'<br/>')
        },

        isFeatureEnabled: function(key) {
            return featureToggles[key];
        },

        applyContextModel: function(input, contextModel) {
            if (contextModel) {
                $.each(contextModel, function(key, value) {
                    var pattern = new RegExp('{{\\s*' + key + '\\s*}}', 'g');
                    input = input.replace(pattern, value);
                });
            }
            return input;
        },

		getJSON: function(url, data, success) {
			var settings = {
				dataType: "json",
				url: url,
				data: data,
				success: success,
				beforeSend: function(xhr) {
					xhr.setRequestHeader('Disable-WWW-Authenticate', 'true');
				}
			};

			return jq.ajax(settings).fail(emr.handleNotLoggedIn);
		},

        handleNotLoggedIn: function(jqXHR) {
           if (jqXHR.status == 401 || jqXHR.status == 404) {
               if (confirm(emr.message("uicommons.notLoggedIn", "The operation cannot be completed, because you are no longer logged in. Do you want to go to login page?"))) {
                   window.location = "/" + OPENMRS_CONTEXT_PATH + "/login.htm";
               }
           }
        },

        domId: function(useIfNotNull, prefix, suffix) {
            if (useIfNotNull) {
                return useIfNotNull;
            }
            return (prefix ? prefix : 'id-') + Math.floor(Math.random() * 10000) + (suffix ? suffix : '');
        },

        isCompatibleWithSessionLocale: function(locale) {
            return window.sessionContext.locale.slice(0, locale.length) === locale ||
                locale.slice(0, window.sessionContext.locale.length) === window.sessionContext.locale;
        },

        focusNextElement: function(within, afterThisOne) {
            var fields = within.find('button,input,textarea,select');
            var index = fields.index(afterThisOne);
            if (index > -1 && (index + 1) < fields.length) {
                fields.eq(index + 1).focus();
            }
        },

        startsWithIgnoreCase: function(string, lookFor) {
            return string.toLowerCase().indexOf(lookFor.toLowerCase()) === 0;
        }

    };

})(jQuery);

var jq = jQuery;
_.templateSettings = {
    interpolate : /{{=(.+?)}}/g ,
    escape : /{{-(.+?)}}/g ,
    evaluate : /{{(.+?)}}/g
};
<commit_msg>UICM-64 - JS utility functions for getting concepts from a reference list, by mappings<commit_after>var emr = (function($) {

    var accentMap = {
        "ä": "a", "á": "a", "à": "a", "â": "a", "ã": "a",
        "Ä": "A", "Á": "A", "À": "A", "Â": "A", "Ã": "A",
        "é": "e", "è": "e", "ê": "e", "ë": "e", "œ": "e","æ":"e",
        "É": "E", "È": "E", "Ê": "E", "Ë": "E",
        "ï": "i", "ì": "i", "í": "i", "î": "i",
        "Ï": "I", "Ì": "I", "Í": "I", "Î": "I",
        "ö": "o", "ó": "o", "ò": "o", "ô": "o", "õ": "o",
        "Ö": "O", "Ó": "O", "Ò": "O", "Ô": "O", "Õ": "O",
        "ü": "u", "ú": "u", "ù": "u", "û": "u",
        "Ü": "U", "Ú": "U", "Ù": "U", "Û": "U",
        "ÿ": "y", "Ÿ": "Y", "ñ": "n", "Ñ": "N",
        "ç": "c", "Ç": "C", "ß": "s"
    };

    var toQueryString = function(options) {
        var ret = "?";
        if (options) {
            for (key in options) {
                var val = options[key];
                if ($.isArray(val)) {
                    for (ind in val) {
                        ret += key + '=' + encodeURIComponent(val[ind]) + '&';
                    }
                } else {
                    ret += key + '=' + encodeURIComponent(val) + '&';
                }
            }
        }
        return ret;
    };

    var requireOptions = function() {
        var opts = arguments[0];
        for (var i = 1; i < arguments.length; ++i) {
            if (!opts[arguments[i]]) {
                throw "Missing option: " + arguments[i];
            }
        }
    };

    var jqObject = $();

    return {

        // just used in testing so we can replace the instance with a mock or spy as needed
        setJqObject: function(jqueryInstanceToSet)  {
            jqObject = jqueryInstanceToSet;
        },

        loadMessages: function(codes, callback) {
            if (!window.messages) {
                window.messages = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "messages", "get", { codes: codes }, function(response) {
                for (var code in response) {
                    window.messages[code] = response[code];
                }
                if (callback) {
                    callback(window.messages);
                }
            });
        },

        loadGlobalProperties: function(properties, callback) {
            if (!window.globalProperties) {
                window.globalProperties = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "globalProperties", "get", {properties: properties}, function(response) {
                for (var property in response) {
                    window.globalProperties[property] = response[property];
                }
                if (callback) {
                    callback(window.globalProperties);
                }
            });
        },

        message: function(code, defaultText) {
            if (window.messages) {
                var translated = window.messages[code];
                return translated ? translated : (defaultText ? defaultText : code);
            } else {
                return defaultText ? defaultText : code;
            }
        },

        navigateTo: function(opts) {
            var url = opts.url;
            if (opts.applicationUrl) {
                url = '/' + OPENMRS_CONTEXT_PATH
                    + (opts.applicationUrl.charAt(0) == '/' ? '' : '/')
                    + opts.applicationUrl;
            }
            if (opts.page) {
                var provider = opts.provider;
                if (provider == null) {
                    provider = "*"
                }
                url = this.pageLink(provider, opts.page, opts.query);
            }
            location.href = url;
        },

        pageLink: function(providerName, pageName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + pageName + '.page';
            return ret + toQueryString(options);
        },

        resourceLink: function(providerName, resourceName) {
            if (providerName == null)
                providerName = '*';
            return '/' + OPENMRS_CONTEXT_PATH + '/ms/uiframework/resource/' + providerName + '/' + resourceName;
        },

        fragmentActionLink: function(providerName, fragmentName, actionName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + fragmentName + '/' + actionName + '.action';
            return ret += toQueryString(options);
        },

        getFragmentActionWithCallback: function(providerName, fragmentName, actionName, options, callback, errorCallback) {
            if (!errorCallback) {
                errorCallback = function(xhr) {
                    emr.handleError(xhr);
                };
            }
            var url = this.fragmentActionLink(providerName, fragmentName, actionName, options);
            $.getJSON(url).success(callback).error(errorCallback);
        },

        /*
         * opts should contain:
         *   provider (defaults to '*')
         *   fragment
         *   action
         *   query, e.g. { q: "bob", checkedInAt: 5 }
         *   resultTarget e.g. '#search-results'
         *   resultTemplate (should be an underscore template)
         */
        ajaxSearch: function(opts) {
            var provider = opts.provider;
            if (!provider) {
                provider = '*';
            }
            var url = this.fragmentActionLink(provider, opts.fragment, opts.action);
            var target = $(opts.resultTarget);
            $.getJSON(url, opts.query)
                .success(function(data) {
                    target.html('');
                    jq.each(data, function(i, result) {
                        jq(opts.resultTemplate(result)).appendTo(target);
                    });
                })
                .error(function(err) {
                    emr.errorMessage(err);
                });
        },

        successMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        errorMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                                              position: 'top-right',
                                              sticky: true,
                                              text:  emr.message(message) } );
        },

        alertMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'alert',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        successAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } );
        },

        errorAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } )
        },

        handleError: function(xhr) {
            emr.handleParsedError(jq.parseJSON(xhr.responseText), xhr.status);
        },

        handleParsedError: function(data, status) {
            if (!emr.redirectOnAuthenticationFailure(status)) {
                if (data.globalErrors) {
                    emr.errorAlert(data.globalErrors[0]);
                } else if (data.error.message) {
                    emr.errorAlert(data.error.message);
                } else {
                    emr.errorAlert("Error!");
                }
            }
        },

        redirectOnAuthenticationFailure: function (status) {
            if (status == 403) {
                window.location = '/' + OPENMRS_CONTEXT_PATH;
                return true;
            }
            return false;
        },

        updateBreadcrumbs: function(extraBreadcrumbs) {
            if (!Array.isArray(breadcrumbs)) {
                // In case the page defines no JS var called breadcrumbs, but does have an html element with that id
                return;
            }
            var toUse = breadcrumbs;
            if (extraBreadcrumbs) {
                toUse = _.clone(breadcrumbs);
                if (extraBreadcrumbs == null || extraBreadcrumbs.length == 0) {
                    var index = toUse.length - 1;
                    var modified = _.clone(toUse[index]);
                    if(modified.link !=null){
                        modified.link = null;
                    }
                    toUse[index] = modified;
                }
                _.each(extraBreadcrumbs, function(item) {
                    toUse.push(item);
                })
            }
            $('#breadcrumbs').html(this.generateBreadcrumbHtml(toUse));
        },

        generateBreadcrumbHtml: function(breadcrumbs) {
            var breadcrumbTemplate = _.template($('#breadcrumb-template').html());
            var html = "";

            _.each(breadcrumbs, function(item, index) {
                html += breadcrumbTemplate({ breadcrumb: item, first: index == 0, last: index == breadcrumbs.length-1 });
            });
            return html;
        },

        /*
         * returns an object with show() and close() functions
         */
        setupConfirmationDialog: function(opts) {
            requireOptions(opts, 'selector');
            var element = $(opts.selector);
            element.hide();
            if (opts.actions) {
                if (opts.actions.confirm) {
                    element.find(".confirm").unbind('click');
                    element.find(".confirm").click(opts.actions.confirm);
                }
                if (opts.actions.cancel) {
                    element.find(".cancel").unbind('click');
                    element.find(".cancel").click(opts.actions.cancel);
                }
            }

            var dialogApi = {};
            var dialogOpts = {
                overlayClose: true,
                overlayId: "modal-overlay",
                opacity: 80,
                persist: true,
                closeClass: "cancel"
            };
            if (opts.dialogOpts) {
                $.extend(dialogOpts, opts.dialogOpts);
            }

            dialogApi.show = function() {
                $(opts.selector).modal(dialogOpts);
            };
            dialogApi.close = function() {
                $.modal.close();
            };

           return dialogApi;
        },

        stripAccents: function(term) {
            var ret = "";
            for ( var i = 0; i < term.length; i++ ) {
                ret += accentMap[ term.charAt(i) ] || term.charAt(i);
            }
            return ret;
        },

        formatAsHtml: function(str) {
            return str.replace(/\n/g,'<br/>')
        },

        isFeatureEnabled: function(key) {
            return featureToggles[key];
        },

        applyContextModel: function(input, contextModel) {
            if (contextModel) {
                $.each(contextModel, function(key, value) {
                    var pattern = new RegExp('{{\\s*' + key + '\\s*}}', 'g');
                    input = input.replace(pattern, value);
                });
            }
            return input;
        },

		getJSON: function(url, data, success) {
			var settings = {
				dataType: "json",
				url: url,
				data: data,
				success: success,
				beforeSend: function(xhr) {
					xhr.setRequestHeader('Disable-WWW-Authenticate', 'true');
				}
			};

			return jq.ajax(settings).fail(emr.handleNotLoggedIn);
		},

        handleNotLoggedIn: function(jqXHR) {
           if (jqXHR.status == 401 || jqXHR.status == 404) {
               if (confirm(emr.message("uicommons.notLoggedIn", "The operation cannot be completed, because you are no longer logged in. Do you want to go to login page?"))) {
                   window.location = "/" + OPENMRS_CONTEXT_PATH + "/login.htm";
               }
           }
        },

        domId: function(useIfNotNull, prefix, suffix) {
            if (useIfNotNull) {
                return useIfNotNull;
            }
            return (prefix ? prefix : 'id-') + Math.floor(Math.random() * 10000) + (suffix ? suffix : '');
        },

        isCompatibleWithSessionLocale: function(locale) {
            return window.sessionContext.locale.slice(0, locale.length) === locale ||
                locale.slice(0, window.sessionContext.locale.length) === window.sessionContext.locale;
        },

        focusNextElement: function(within, afterThisOne) {
            var fields = within.find('button,input,textarea,select');
            var index = fields.index(afterThisOne);
            if (index > -1 && (index + 1) < fields.length) {
                fields.eq(index + 1).focus();
            }
        },

        startsWithIgnoreCase: function(string, lookFor) {
            return string.toLowerCase().indexOf(lookFor.toLowerCase()) === 0;
        },

        hasMapping: function(concept, sourceName, code) {
            if (concept.mappings) {
                // this quick hack implementation presumes the concept mapping's display property is like "CIEL: 1513"
                var lookForDisplay = sourceName + ": " + code;
                return _.findWhere(concept.mappings, {display: lookForDisplay})
            }
            return null;
        },

        findConceptWithMapping: function(conceptArray, sourceName, code) {
            return _.find(conceptArray, function(concept) {
                return emr.hasMapping(concept, sourceName, code);
            });
        }

    };

})(jQuery);

var jq = jQuery;
_.templateSettings = {
    interpolate : /{{=(.+?)}}/g ,
    escape : /{{-(.+?)}}/g ,
    evaluate : /{{(.+?)}}/g
};
<|endoftext|>


<commit_before>define(['plugin/PluginBase', 'plugin/PluginConfig', 'path',
       '../utils/WebgmeUtils', '../utils/NescUtils'],
function (PluginBase, PluginConfig, path, wgme_utils, nesc_utils) {

'use strict';

var AppImporter = function () {
  PluginBase.call(this);
};

AppImporter.prototype = Object.create(PluginBase.prototype);
AppImporter.prototype.constructor = AppImporter;
AppImporter.prototype.getName = function () {
  return "AppImporter";
};
AppImporter.prototype.getVersion = function () {
  return '0.0.0';
};

AppImporter.prototype.main = function (callback) {
  var self = this;
  var core = self.core;
  var log = self.logger;
  var async = require('async');
  var save = true;

  var app_path = path.resolve(process.env.TOSROOT, 'apps', 'Blink', 'BlinkAppC.nc');

  var cwp = core.getRegistry(self.rootNode, 'configuration_paths');
  var mwp = core.getRegistry(self.rootNode, 'module_paths');
  var fwp = core.getRegistry(self.rootNode, 'folder_paths');

  var paths_arr = [
    { paths: cwp, depth: 1 },
    { paths: mwp, depth: 2 },
    { paths: fwp, depth: 0 }
  ];

  var reg_obj = {
    cwp: cwp,
    mwp: mwp,
    fwp: fwp
  };

  async.parallel([
    function (callback) {
      wgme_utils.loadObjects.call(self, paths_arr, callback);
    },
    function (callback) {
      nesc_utils.getAppJson(app_path, callback);
    }
  ],
  function (err, results) {
    if (err) {
      log.info(err);
      self.result.setSuccess(false);
      return callback(null, self.result);
    }

    self.run(results[1], results[0], reg_obj);

    var fs = require('fs-extra');
    fs.outputJsonSync('temp/BlinkAppC.json', results[1], {spaces: 2});

    if (save) {
      self.save('save', function (err) {
        call_callback(true);
      });
    } else call_callback(true);

  });

  function call_callback (success) {
    self.result.setSuccess(success);
    callback(null, self.result);
  }

};

AppImporter.prototype.run = function (app_json, nodes, reg_obj) {
  var self = this;
  // Create components
  var components = app_json.components;
  for (var c_name in components) {
    if ( nodes[c_name] === undefined ) {
      var comp_json = components[c_name];
      var parent = wgme_utils.mkdirp.call(self, comp_json.file_path, nodes, reg_obj.fwp);
      var base = wgme_utils.getMetaNode.call(self, nesc_utils.getBase(comp_json));
      self.createNode(c_name, parent, base);
    }
  }
  self.core.setRegistry(self.rootNode, 'folder_paths', reg_obj.fwp);
};

AppImporter.prototype.createNode = function(name, parent, base) {
  this.logger.info('', 'to be created', name);
};

return AppImporter;

});
<commit_msg>Create component nodes<commit_after>define(['plugin/PluginBase', 'plugin/PluginConfig', 'path',
       '../utils/WebgmeUtils', '../utils/NescUtils'],
function (PluginBase, PluginConfig, path, wgme_utils, nesc_utils) {

'use strict';

var AppImporter = function () {
  PluginBase.call(this);
};

AppImporter.prototype = Object.create(PluginBase.prototype);
AppImporter.prototype.constructor = AppImporter;
AppImporter.prototype.getName = function () {
  return "AppImporter";
};
AppImporter.prototype.getVersion = function () {
  return '0.0.0';
};

AppImporter.prototype.main = function (callback) {
  var self = this;
  var core = self.core;
  var log = self.logger;
  var async = require('async');
  var save = true;

  var app_path = path.resolve(process.env.TOSROOT, 'apps', 'Blink', 'BlinkAppC.nc');

  var cwp = core.getRegistry(self.rootNode, 'configuration_paths');
  var mwp = core.getRegistry(self.rootNode, 'module_paths');
  var fwp = core.getRegistry(self.rootNode, 'folder_paths');

  var paths_arr = [
    { paths: cwp, depth: 1 },
    { paths: mwp, depth: 2 },
    { paths: fwp, depth: 0 }
  ];

  var reg_obj = {
    cwp: cwp,
    mwp: mwp,
    fwp: fwp
  };

  log.info('', reg_obj);

  async.parallel([
    function (callback) {
      wgme_utils.loadObjects.call(self, paths_arr, callback);
    },
    function (callback) {
      nesc_utils.getAppJson(app_path, callback);
    }
  ],
  function (err, results) {
    if (err) {
      log.info(err);
      self.result.setSuccess(false);
      return callback(null, self.result);
    }

    self.run(results[1], results[0], reg_obj);

    var fs = require('fs-extra');
    fs.outputJsonSync('temp/BlinkAppC.json', results[1], {spaces: 2});

    if (save) {
      self.save('save', function (err) {
        call_callback(true);
      });
    } else call_callback(true);

  });

  function call_callback (success) {
    self.result.setSuccess(success);
    callback(null, self.result);
  }

};

AppImporter.prototype.run = function (app_json, nodes, reg_obj) {
  var self = this;
  var core = self.core;
  // Create components
  var components = app_json.components;
  for (var c_name in components) {
    if ( nodes[c_name] === undefined ) {
      var comp_json = components[c_name];
      var parent = wgme_utils.mkdirp.call(self, comp_json.file_path, nodes, reg_obj.fwp);
      var base = wgme_utils.getMetaNode.call(self, nesc_utils.getBase(comp_json));
      var new_node = self.createNode(c_name, parent, base);
      core.setAttribute(new_node, 'safe', comp_json.safe);
      cache_and_register();
    }
  }

  function cache_and_register () {
    nodes[c_name] = new_node;

    if ( comp_json.comp_type === 'Configuration')
      var wp = reg_obj.cwp;
    else if ( comp_json.comp_type === 'Module')
      wp = reg_obj.mwp;
    wp[c_name] = core.getPath(new_node);

    core.setRegistry(new_node, 'nesc-dump', comp_json);
    // TODO: set call graph and tasks in registry
  }

};

AppImporter.prototype.createNode = function(name, parent, base) {
  var new_node = this.core.createNode({
    parent: parent,
    base: base
  });
  this.core.setAttribute(new_node, 'name', name);
  return new_node;
};

return AppImporter;

});
<|endoftext|>