From 5e6c9c2c9db42a83a91387b6150b232ee4a41163 Mon Sep 17 00:00:00 2001 From: James Muehlner Date: Wed, 17 Feb 2016 23:09:13 -0800 Subject: [PATCH 01/11] GUAC-1378: Added decorator to intercept and modify templates as they are loaded. --- .../index/config/templateRequestDecorator.js | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js diff --git a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js new file mode 100644 index 000000000..b4c78c754 --- /dev/null +++ b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2016 Glyptodon LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * Overrides $templateRequest such that HTML patches defined within Guacamole + * extensions are automatically applied to template contents. + */ +angular.module('index').config(['$provide', function($provide) { + $provide.decorator('$templateRequest', ['$delegate', '$injector', + function decorateTemplateRequest($delegate, $injector) { + + // Required services + var $q = $injector.get('$q'); + + /** + * Invokes $templateRequest() with all arguments exactly as provided, + * applying all HTML patches from any installed Guacamole extensions + * to the HTML of the requested template. + * + * @returns {Promise.} + * A Promise which resolves with the patched HTML contents of the + * requested template if retrieval of the template is successful. + */ + var decoratedTemplateRequest = function decoratedTemplateRequest() { + + var deferred = $q.defer(); + + // Resolve promise with patched template HTML + $delegate.apply(this, arguments).then(function patchTemplate(data) { + + // Parse HTML into DOM tree + var root = $('
').html(data); + + // STUB: Apply HTML patches + root.find('a').after('

HELLO

'); + + // Transform back into HTML + deferred.resolve.call(this, root.html()); + + }, deferred.reject); + + return deferred.promise; + + }; + + return decoratedTemplateRequest; + + }]); +}]); \ No newline at end of file From 9c11363224b8c362cd3b7051d933d94fcf900de1 Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Thu, 18 Feb 2016 13:34:07 -0800 Subject: [PATCH 02/11] GUAC-1378: Define HTML patches using a special root element. --- .../index/config/templateRequestDecorator.js | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js index b4c78c754..cb848c3c0 100644 --- a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js +++ b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js @@ -31,6 +31,18 @@ angular.module('index').config(['$provide', function($provide) { // Required services var $q = $injector.get('$q'); + /** + * Array of the root elements of all patches which should be applied to + * the HTML of retrieved templates. + * + * @type Element[] + */ + var patches = [ + $('

HELLO BEFORE

')[0], + $('

HELLO AFTER

')[0], + $('
:-)
')[0] + ]; + /** * Invokes $templateRequest() with all arguments exactly as provided, * applying all HTML patches from any installed Guacamole extensions @@ -50,8 +62,34 @@ angular.module('index').config(['$provide', function($provide) { // Parse HTML into DOM tree var root = $('
').html(data); - // STUB: Apply HTML patches - root.find('a').after('

HELLO

'); + // Apply all defined patches + angular.forEach(patches, function applyPatch(patch) { + + // Ignore any patches which are malformed + if (patch.tagName !== 'GUAC-PATCH') + return; + + // Insert after any elements which match the "after" + // selector (if defined) + var after = patch.getAttribute('after'); + if (after) + root.find(after).after(patch.innerHTML); + + // Insert before any elements which match the "before" + // selector (if defined) + var before = patch.getAttribute('before'); + if (before) + root.find(before).before(patch.innerHTML); + + // Replace any elements which match the "replace" selector + // (if defined) + var replace = patch.getAttribute('replace'); + if (replace) + root.find(replace).html(patch.innerHTML); + + // Ignore all other attributes + + }); // Transform back into HTML deferred.resolve.call(this, root.html()); From f57a4f80db8ddd4c89514acdc990306337da0a6b Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Thu, 18 Feb 2016 17:13:47 -0800 Subject: [PATCH 03/11] GUAC-1378: Use tags instead of a special root element. --- .../index/config/templateRequestDecorator.js | 235 ++++++++++++++++-- 1 file changed, 210 insertions(+), 25 deletions(-) diff --git a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js index cb848c3c0..51e2361d1 100644 --- a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js +++ b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js @@ -32,17 +32,193 @@ angular.module('index').config(['$provide', function($provide) { var $q = $injector.get('$q'); /** - * Array of the root elements of all patches which should be applied to - * the HTML of retrieved templates. + * Array of the raw HTML of all patches which should be applied to the + * HTML of retrieved templates. * - * @type Element[] + * @type String[] */ var patches = [ - $('

HELLO BEFORE

')[0], - $('

HELLO AFTER

')[0], - $('
:-)
')[0] + '

HELLO BEFORE

', + '

HELLO AFTER

', + '
:-)
' ]; + /** + * Represents a single HTML patching operation which will be applied + * to the raw HTML of a template. The name of the patching operation + * MUST be one of the valid names defined within + * PatchOperation.Operations. + * + * @contructor + * @param {String} name + * The name of the patching operation that will be applied. Valid + * names are defined within PatchOperation.Operations. + * + * @param {String} selector + * The CSS selector which determines which elements within a + * template will be affected by the patch operation. + */ + var PatchOperation = function PatchOperation(name, selector) { + + /** + * Applies this patch operation to the template defined by the + * given root element, which must be a single element wrapped by + * JQuery. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template to which + * this patch operation should be applied. + * + * @param {Element[]} elements + * The elements which should be applied by the patch + * operation. For example, if the patch operation is inserting + * elements, these are the elements that will be inserted. + */ + this.apply = function apply(root, elements) { + PatchOperation.Operations[name](root, selector, elements); + }; + + }; + + /** + * Mapping of all valid patch operation names to their corresponding + * implementations. Each implementation accepts the same three + * parameters: the root element of the template being patched, the CSS + * selector determining which elements within the template are patched, + * and an array of elements which make up the body of the patch. + * + * @type Object. + */ + PatchOperation.Operations = { + + /** + * Inserts the given elements before the elements matched by the + * provided CSS selector. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template being + * patched. + * + * @param {String} selector + * The CSS selector which determines where this patch operation + * should be applied within the template defined by root. + * + * @param {Element[]} elements + * The contents of the patch which should be applied to the + * template defined by root at the locations selected by the + * given CSS selector. + */ + 'before' : function before(root, selector, elements) { + root.find(selector).before(elements); + }, + + /** + * Inserts the given elements after the elements matched by the + * provided CSS selector. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template being + * patched. + * + * @param {String} selector + * The CSS selector which determines where this patch operation + * should be applied within the template defined by root. + * + * @param {Element[]} elements + * The contents of the patch which should be applied to the + * template defined by root at the locations selected by the + * given CSS selector. + */ + 'after' : function after(root, selector, elements) { + root.find(selector).after(elements); + }, + + /** + * Replaces the elements matched by the provided CSS selector with + * the given elements. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template being + * patched. + * + * @param {String} selector + * The CSS selector which determines where this patch operation + * should be applied within the template defined by root. + * + * @param {Element[]} elements + * The contents of the patch which should be applied to the + * template defined by root at the locations selected by the + * given CSS selector. + */ + 'replace' : function replace(root, selector, elements) { + root.find(selector).replaceWith(elements); + }, + + /** + * Inserts the given elements within the elements matched by the + * provided CSS selector, before any existing children. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template being + * patched. + * + * @param {String} selector + * The CSS selector which determines where this patch operation + * should be applied within the template defined by root. + * + * @param {Element[]} elements + * The contents of the patch which should be applied to the + * template defined by root at the locations selected by the + * given CSS selector. + */ + 'before-children' : function beforeChildren(root, selector, elements) { + root.find(selector).prepend(elements); + }, + + /** + * Inserts the given elements within the elements matched by the + * provided CSS selector, after any existing children. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template being + * patched. + * + * @param {String} selector + * The CSS selector which determines where this patch operation + * should be applied within the template defined by root. + * + * @param {Element[]} elements + * The contents of the patch which should be applied to the + * template defined by root at the locations selected by the + * given CSS selector. + */ + 'after-children' : function afterChildren(root, selector, elements) { + root.find(selector).append(elements); + }, + + /** + * Inserts the given elements within the elements matched by the + * provided CSS selector, replacing any existing children. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template being + * patched. + * + * @param {String} selector + * The CSS selector which determines where this patch operation + * should be applied within the template defined by root. + * + * @param {Element[]} elements + * The contents of the patch which should be applied to the + * template defined by root at the locations selected by the + * given CSS selector. + */ + 'replace-children' : function replaceChildren(root, selector, elements) { + root.find(selector).empty().append(elements); + } + + }; + /** * Invokes $templateRequest() with all arguments exactly as provided, * applying all HTML patches from any installed Guacamole extensions @@ -65,29 +241,38 @@ angular.module('index').config(['$provide', function($provide) { // Apply all defined patches angular.forEach(patches, function applyPatch(patch) { - // Ignore any patches which are malformed - if (patch.tagName !== 'GUAC-PATCH') - return; + var elements = $(patch); - // Insert after any elements which match the "after" - // selector (if defined) - var after = patch.getAttribute('after'); - if (after) - root.find(after).after(patch.innerHTML); + // Filter out and parse all applicable meta tags + var operations = []; + elements = elements.filter(function filterMetaTags(index, element) { - // Insert before any elements which match the "before" - // selector (if defined) - var before = patch.getAttribute('before'); - if (before) - root.find(before).before(patch.innerHTML); + // Leave non-meta tags untouched + if (element.tagName !== 'META') + return true; - // Replace any elements which match the "replace" selector - // (if defined) - var replace = patch.getAttribute('replace'); - if (replace) - root.find(replace).html(patch.innerHTML); + // Only meta tags having a valid "name" attribute need + // to be filtered + var name = element.getAttribute('name'); + if (!name || !(name in PatchOperation.Operations)) + return true; - // Ignore all other attributes + // The "content" attribute must be present for any + // valid "name" meta tag + var content = element.getAttribute('content'); + if (!content) + return true; + + // Filter out and parse meta tag + operations.push(new PatchOperation(name, content)); + return false; + + }); + + // Apply each operation implied by the meta tags + angular.forEach(operations, function applyOperation(operation) { + operation.apply(root, elements); + }); }); From f2a767f04542f85f09c26ec99ba80a1273e0828e Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Thu, 18 Feb 2016 17:18:13 -0800 Subject: [PATCH 04/11] GUAC-1378: It's a constructor, not a contructor. --- .../main/webapp/app/index/config/templateRequestDecorator.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js index 51e2361d1..68eb6a1f5 100644 --- a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js +++ b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js @@ -49,7 +49,7 @@ angular.module('index').config(['$provide', function($provide) { * MUST be one of the valid names defined within * PatchOperation.Operations. * - * @contructor + * @constructor * @param {String} name * The name of the patching operation that will be applied. Valid * names are defined within PatchOperation.Operations. From 8f17e9ed0a1529c6bae380b691181a0b22e73e03 Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Thu, 18 Feb 2016 17:49:48 -0800 Subject: [PATCH 05/11] GUAC-1378: Cache previous calls to $templateRequest() to avoid duplicating patch processing work. --- .../index/config/templateRequestDecorator.js | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js index 68eb6a1f5..43655bc62 100644 --- a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js +++ b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js @@ -31,6 +31,16 @@ angular.module('index').config(['$provide', function($provide) { // Required services var $q = $injector.get('$q'); + /** + * A map of previously-returned promises from past calls to + * $templateRequest(). Future calls to $templateRequest() will return + * new promises chained to the first promise returned for a given URL, + * rather than redo patch processing for every request. + * + * @type Object.> + */ + var promiseCache = {}; + /** * Array of the raw HTML of all patches which should be applied to the * HTML of retrieved templates. @@ -224,14 +234,24 @@ angular.module('index').config(['$provide', function($provide) { * applying all HTML patches from any installed Guacamole extensions * to the HTML of the requested template. * + * @param {String} url + * The URL of the template being requested. + * * @returns {Promise.} * A Promise which resolves with the patched HTML contents of the * requested template if retrieval of the template is successful. */ - var decoratedTemplateRequest = function decoratedTemplateRequest() { + var decoratedTemplateRequest = function decoratedTemplateRequest(url) { var deferred = $q.defer(); + // Chain to cached promise if it already exists + var cachedPromise = promiseCache[url]; + if (cachedPromise) { + cachedPromise.then(deferred.resolve, deferred.reject); + return deferred.promise; + } + // Resolve promise with patched template HTML $delegate.apply(this, arguments).then(function patchTemplate(data) { @@ -281,6 +301,8 @@ angular.module('index').config(['$provide', function($provide) { }, deferred.reject); + // Cache this promise for future results + promiseCache[url] = deferred.promise; return deferred.promise; }; From c01e8c6a9a6037295272353910ad11bc0bff1562 Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Thu, 18 Feb 2016 19:52:44 -0800 Subject: [PATCH 06/11] GUAC-1378: Evict cache of $templateRequest results when $templateCache is modified externally. --- .../index/config/templateRequestDecorator.js | 64 +++++++++++++++---- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js index 43655bc62..07b669bce 100644 --- a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js +++ b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js @@ -22,25 +22,67 @@ /** * Overrides $templateRequest such that HTML patches defined within Guacamole - * extensions are automatically applied to template contents. + * extensions are automatically applied to template contents. As the results of + * $templateRequest are cached internally, $templateCache is also overridden to + * update the internal cache as necessary. */ angular.module('index').config(['$provide', function($provide) { + + /** + * A map of previously-returned promises from past calls to + * $templateRequest(). Future calls to $templateRequest() will return + * new promises chained to the first promise returned for a given URL, + * rather than redo patch processing for every request. + * + * @type Object.> + */ + var promiseCache = {}; + + // Decorate $templateCache such that promiseCache is updated if a template + // is modified within $templateCache at runtime + $provide.decorator('$templateCache', ['$delegate', + function decorateTemplateCache($delegate) { + + // Create shallow copy of original $templateCache which we can safely + // override + var decoratedTemplateCache = angular.extend({}, $delegate); + + /** + * Overridden version of $templateCache.put() which automatically + * invalidates the cached $templateRequest result when used. Only the + * URL parameter is defined, as all other arguments, if any, will be + * passed through to the original $templateCache.put() when the actual + * put() operation is performed. + * + * @param {String} url + * The URL of the template whose entry is being updated. + * + * @return {Object} + * The value returned by $templateCache.put(), which is defined as + * being the value that was just stored at the provided URL. + */ + decoratedTemplateCache.put = function put(url) { + + // Evict old cached $templateRequest() result + delete promiseCache[url]; + + // Continue with originally-requested put() operation + return $delegate.put.apply(this, arguments); + + }; + + return decoratedTemplateCache; + + }]); + + // Decorate $templateRequest such that it automatically applies any HTML + // patches associated with installed Guacamole extensions $provide.decorator('$templateRequest', ['$delegate', '$injector', function decorateTemplateRequest($delegate, $injector) { // Required services var $q = $injector.get('$q'); - /** - * A map of previously-returned promises from past calls to - * $templateRequest(). Future calls to $templateRequest() will return - * new promises chained to the first promise returned for a given URL, - * rather than redo patch processing for every request. - * - * @type Object.> - */ - var promiseCache = {}; - /** * Array of the raw HTML of all patches which should be applied to the * HTML of retrieved templates. From 29a071587bfd7ef247b4a8f36a9a38b32c53a02d Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Fri, 19 Feb 2016 00:06:49 -0800 Subject: [PATCH 07/11] GUAC-1378: Add "html" property to manifest. --- .../net/basic/extension/Extension.java | 20 +++++++++++ .../basic/extension/ExtensionManifest.java | 36 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/Extension.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/Extension.java index ea990351f..517e9c085 100644 --- a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/Extension.java +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/Extension.java @@ -89,6 +89,12 @@ public class Extension { */ private final Map cssResources; + /** + * Map of all HTML patch resources defined within the extension, where each + * key is the path to that resource within the extension. + */ + private final Map htmlResources; + /** * Map of all translation resources defined within the extension, where * each key is the path to that resource within the extension. @@ -352,6 +358,7 @@ public class Extension { // Define static resources cssResources = getClassPathResources("text/css", manifest.getCSSPaths()); javaScriptResources = getClassPathResources("text/javascript", manifest.getJavaScriptPaths()); + htmlResources = getClassPathResources("text/html", manifest.getHTMLPaths()); translationResources = getClassPathResources("application/json", manifest.getTranslationPaths()); staticResources = getClassPathResources(manifest.getResourceTypes()); @@ -431,6 +438,19 @@ public class Extension { return cssResources; } + /** + * Returns a map of all declared HTML patch resources associated with this + * extension, where the key of each entry in the map is the path to that + * resource within the extension .jar. HTML patch resources are declared + * within the extension manifest. + * + * @return + * All declared HTML patch resources associated with this extension. + */ + public Map getHTMLResources() { + return htmlResources; + } + /** * Returns a map of all declared translation resources associated with this * extension, where the key of each entry in the map is the path to that diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionManifest.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionManifest.java index 6d121b7a9..750d7aa54 100644 --- a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionManifest.java +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionManifest.java @@ -67,6 +67,12 @@ public class ExtensionManifest { */ private Collection cssPaths; + /** + * The paths of all HTML patch resources within the .jar of the extension + * associated with this manifest. + */ + private Collection htmlPaths; + /** * The paths of all translation JSON files within this extension, if any. */ @@ -232,6 +238,36 @@ public class ExtensionManifest { this.cssPaths = cssPaths; } + /** + * Returns the paths to all HTML patch resources within the extension. These + * paths are defined within the manifest by the "html" property as an array + * of strings, where each string is a path relative to the root of the + * extension .jar. + * + * @return + * A collection of paths to all HTML patch resources within the + * extension. + */ + @JsonProperty("html") + public Collection getHTMLPaths() { + return htmlPaths; + } + + /** + * Sets the paths to all HTML patch resources within the extension. These + * paths are defined within the manifest by the "html" property as an array + * of strings, where each string is a path relative to the root of the + * extension .jar. + * + * @param htmlPatchPaths + * A collection of paths to all HTML patch resources within the + * extension. + */ + @JsonProperty("html") + public void setHTMLPaths(Collection htmlPatchPaths) { + this.htmlPaths = htmlPatchPaths; + } + /** * Returns the paths to all translation resources within the extension. * These paths are defined within the manifest by the "translations" From ec4f37032b54c9b55471f18e120ba5120bf4f29b Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Fri, 19 Feb 2016 00:20:02 -0800 Subject: [PATCH 08/11] GUAC-1378: Read HTML patch resources from extensions into service. --- .../net/basic/extension/ExtensionModule.java | 16 +++- .../basic/extension/PatchResourceService.java | 84 +++++++++++++++++++ 2 files changed, 97 insertions(+), 3 deletions(-) create mode 100644 guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/PatchResourceService.java diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionModule.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionModule.java index 6296ea5de..deca3c831 100644 --- a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionModule.java +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/ExtensionModule.java @@ -101,6 +101,11 @@ public class ExtensionModule extends ServletModule { * Service for adding and retrieving language resources. */ private final LanguageResourceService languageResourceService; + + /** + * Service for adding and retrieving HTML patch resources. + */ + private final PatchResourceService patchResourceService; /** * Returns the classloader that should be used as the parent classloader @@ -140,6 +145,7 @@ public class ExtensionModule extends ServletModule { public ExtensionModule(Environment environment) { this.environment = environment; this.languageResourceService = new LanguageResourceService(environment); + this.patchResourceService = new PatchResourceService(); } /** @@ -307,7 +313,7 @@ public class ExtensionModule extends ServletModule { * A modifiable collection of static JavaScript resources which may * receive new JavaScript resources from extensions. * - * @param cssResources + * @param cssResources * A modifiable collection of static CSS resources which may receive * new CSS resources from extensions. */ @@ -366,6 +372,9 @@ public class ExtensionModule extends ServletModule { // Add any translation resources serveLanguageResources(extension.getTranslationResources()); + // Add all HTML patch resources + patchResourceService.addPatchResources(extension.getHTMLResources().values()); + // Add all static resources under namespace-derived prefix String staticResourcePrefix = "/app/ext/" + extension.getNamespace() + "/"; serveStaticResources(staticResourcePrefix, extension.getStaticResources()); @@ -394,12 +403,13 @@ public class ExtensionModule extends ServletModule { @Override protected void configureServlets() { - // Bind language resource service + // Bind resource services bind(LanguageResourceService.class).toInstance(languageResourceService); + bind(PatchResourceService.class).toInstance(patchResourceService); // Load initial language resources from servlet context languageResourceService.addLanguageResources(getServletContext()); - + // Load authentication provider from guacamole.properties for sake of backwards compatibility Class authProviderProperty = getAuthProviderProperty(); if (authProviderProperty != null) diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/PatchResourceService.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/PatchResourceService.java new file mode 100644 index 000000000..7c882927b --- /dev/null +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/extension/PatchResourceService.java @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2016 Glyptodon LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package org.glyptodon.guacamole.net.basic.extension; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import org.glyptodon.guacamole.net.basic.resource.Resource; + +/** + * Service which provides access to all HTML patches as resources, and allows + * other patch resources to be added. + * + * @author Michael Jumper + */ +public class PatchResourceService { + + /** + * A list of all HTML patch resources currently defined, in the order they + * should be applied. + */ + private final List resources = new ArrayList(); + + /** + * Adds the given HTML patch resource such that it will apply to the + * Guacamole UI. The patch will be applied by the JavaScript side of the + * web application in the order that addPatchResource() is invoked. + * + * @param resource + * The HTML patch resource to add. This resource must have the mimetype + * "text/html". + */ + public void addPatchResource(Resource resource) { + resources.add(resource); + } + + /** + * Adds the given HTML patch resources such that they will apply to the + * Guacamole UI. The patches will be applied by the JavaScript side of the + * web application in the order provided. + * + * @param resources + * The HTML patch resources to add. Each resource must have the + * mimetype "text/html". + */ + public void addPatchResources(Collection resources) { + for (Resource resource : resources) + addPatchResource(resource); + } + + /** + * Returns a list of all HTML patches currently associated with this + * service, in the order they should be applied. The returned list cannot + * be modified. + * + * @return + * A list of all HTML patches currently associated with this service. + */ + public List getPatchResources() { + return Collections.unmodifiableList(resources); + } + +} From 4881e5c778537413a56ffdde619eb2c7693ef939 Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Fri, 19 Feb 2016 00:21:42 -0800 Subject: [PATCH 09/11] GUAC-1378: Serve HTML patch resources from /api/patches. --- .../net/basic/rest/RESTServiceModule.java | 2 + .../basic/rest/patch/PatchRESTService.java | 124 ++++++++++++++++++ .../net/basic/rest/patch/package-info.java | 27 ++++ 3 files changed, 153 insertions(+) create mode 100644 guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/PatchRESTService.java create mode 100644 guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/package-info.java diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/RESTServiceModule.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/RESTServiceModule.java index 40ee2d330..72842ba16 100644 --- a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/RESTServiceModule.java +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/RESTServiceModule.java @@ -38,6 +38,7 @@ import org.glyptodon.guacamole.net.basic.rest.auth.SecureRandomAuthTokenGenerato import org.glyptodon.guacamole.net.basic.rest.auth.TokenSessionMap; import org.glyptodon.guacamole.net.basic.rest.history.HistoryRESTService; import org.glyptodon.guacamole.net.basic.rest.language.LanguageRESTService; +import org.glyptodon.guacamole.net.basic.rest.patch.PatchRESTService; import org.glyptodon.guacamole.net.basic.rest.schema.SchemaRESTService; import org.glyptodon.guacamole.net.basic.rest.user.UserRESTService; @@ -91,6 +92,7 @@ public class RESTServiceModule extends ServletModule { bind(ConnectionRESTService.class); bind(HistoryRESTService.class); bind(LanguageRESTService.class); + bind(PatchRESTService.class); bind(SchemaRESTService.class); bind(TokenRESTService.class); bind(UserRESTService.class); diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/PatchRESTService.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/PatchRESTService.java new file mode 100644 index 000000000..f0de9b604 --- /dev/null +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/PatchRESTService.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2016 Glyptodon LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package org.glyptodon.guacamole.net.basic.rest.patch; + +import com.google.inject.Inject; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import org.glyptodon.guacamole.GuacamoleException; +import org.glyptodon.guacamole.GuacamoleServerException; +import org.glyptodon.guacamole.net.basic.extension.PatchResourceService; +import org.glyptodon.guacamole.net.basic.resource.Resource; + +/** + * A REST Service for handling the listing of HTML patches. + * + * @author Michael Jumper + */ +@Path("/patches") +@Produces(MediaType.APPLICATION_JSON) +public class PatchRESTService { + + /** + * Service for retrieving information regarding available HTML patch + * resources. + */ + @Inject + private PatchResourceService patchResourceService; + + /** + * Reads the entire contents of the given resource as a String. The + * resource is assumed to be encoded in UTF-8. + * + * @param resource + * The resource to read as a new String. + * + * @return + * A new String containing the contents of the given resource. + * + * @throws IOException + * If an I/O error prevents reading the resource. + */ + private String readResourceAsString(Resource resource) throws IOException { + + StringBuilder contents = new StringBuilder(); + + char buffer[] = new char[8192]; + int length; + + // Read entire resource into StringBuilder one chunk at a time + Reader reader = new InputStreamReader(resource.asStream(), "UTF-8"); + while ((length = reader.read(buffer)) != -1) { + contents.append(buffer, 0, length); + } + + return contents.toString(); + + } + + /** + * Returns a list of all available HTML patches, in the order they should + * be applied. Each patch is raw HTML containing additional meta tags + * describing how and where the patch should be applied. + * + * @return + * A list of all HTML patches defined in the system, in the order they + * should be applied. + * + * @throws GuacamoleException + * If an error occurs preventing any HTML patch from being read. + */ + @GET + public List getPatches() throws GuacamoleException { + + try { + + // Allocate a list of equal size to the total number of patches + List resources = patchResourceService.getPatchResources(); + List patches = new ArrayList(resources.size()); + + // Convert each patch resource to a string + for (Resource resource : resources) { + patches.add(readResourceAsString(resource)); + } + + // Return all patches in string form + return patches; + + } + + // Bail out entirely on error + catch (IOException e) { + throw new GuacamoleServerException("Unable to read HTML patches.", e); + } + + } + +} diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/package-info.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/package-info.java new file mode 100644 index 000000000..49a979397 --- /dev/null +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/patch/package-info.java @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2016 Glyptodon LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * Classes related to the HTML patch retrieval aspect of the Guacamole REST API. + */ +package org.glyptodon.guacamole.net.basic.rest.patch; + From bda64a21081800b4fc8165006c7f96b35903a0e2 Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Fri, 19 Feb 2016 00:22:43 -0800 Subject: [PATCH 10/11] GUAC-1378: Add service for communicating with the /api/patches REST endpoint. --- .../webapp/app/rest/services/cacheService.js | 7 ++ .../webapp/app/rest/services/patchService.js | 65 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 guacamole/src/main/webapp/app/rest/services/patchService.js diff --git a/guacamole/src/main/webapp/app/rest/services/cacheService.js b/guacamole/src/main/webapp/app/rest/services/cacheService.js index ef523dcb8..9fb9b4437 100644 --- a/guacamole/src/main/webapp/app/rest/services/cacheService.js +++ b/guacamole/src/main/webapp/app/rest/services/cacheService.js @@ -48,6 +48,13 @@ angular.module('rest').factory('cacheService', ['$injector', */ service.languages = $cacheFactory('API-LANGUAGES'); + /** + * Cache used by patchService. + * + * @type $cacheFactory.Cache + */ + service.patches = $cacheFactory('API-PATCHES'); + /** * Cache used by schemaService. * diff --git a/guacamole/src/main/webapp/app/rest/services/patchService.js b/guacamole/src/main/webapp/app/rest/services/patchService.js new file mode 100644 index 000000000..b3db669d2 --- /dev/null +++ b/guacamole/src/main/webapp/app/rest/services/patchService.js @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2016 Glyptodon LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * Service for operating on HTML patches via the REST API. + */ +angular.module('rest').factory('patchService', ['$injector', + function patchService($injector) { + + // Required services + var $http = $injector.get('$http'); + var authenticationService = $injector.get('authenticationService'); + var cacheService = $injector.get('cacheService'); + + var service = {}; + + /** + * Makes a request to the REST API to get the list of patches, returning + * a promise that provides the array of all applicable patches if + * successful. Each patch is a string of raw HTML with meta information + * describing the patch operation stored within meta tags. + * + * @returns {Promise.} + * A promise which will resolve with an array of HTML patches upon + * success. + */ + service.getPatches = function getPatches() { + + // Build HTTP parameters set + var httpParameters = { + token : authenticationService.getCurrentToken() + }; + + // Retrieve all applicable HTML patches + return $http({ + cache : cacheService.patches, + method : 'GET', + url : 'api/patches', + params : httpParameters + }); + + }; + + return service; + +}]); From a66513b724a36603685ed395676c959e87c0cc38 Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Fri, 19 Feb 2016 00:23:39 -0800 Subject: [PATCH 11/11] GUAC-1378: Pull and apply patches from REST endpoint. --- .../index/config/templateRequestDecorator.js | 116 ++++++++++-------- 1 file changed, 64 insertions(+), 52 deletions(-) diff --git a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js index 07b669bce..d3eae07c3 100644 --- a/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js +++ b/guacamole/src/main/webapp/app/index/config/templateRequestDecorator.js @@ -81,19 +81,8 @@ angular.module('index').config(['$provide', function($provide) { function decorateTemplateRequest($delegate, $injector) { // Required services - var $q = $injector.get('$q'); - - /** - * Array of the raw HTML of all patches which should be applied to the - * HTML of retrieved templates. - * - * @type String[] - */ - var patches = [ - '

HELLO BEFORE

', - '

HELLO AFTER

', - '
:-)
' - ]; + var $q = $injector.get('$q'); + var patchService = $injector.get('patchService'); /** * Represents a single HTML patching operation which will be applied @@ -271,6 +260,59 @@ angular.module('index').config(['$provide', function($provide) { }; + /** + * Applies each of the given HTML patches to the given template. + * + * @param {Element[]} root + * The JQuery-wrapped root element of the template being + * patched. + * + * @param {String[]} patches + * An array of all HTML patches to be applied to the given + * template. + */ + var applyPatches = function applyPatches(root, patches) { + + // Apply all defined patches + angular.forEach(patches, function applyPatch(patch) { + + var elements = $(patch); + + // Filter out and parse all applicable meta tags + var operations = []; + elements = elements.filter(function filterMetaTags(index, element) { + + // Leave non-meta tags untouched + if (element.tagName !== 'META') + return true; + + // Only meta tags having a valid "name" attribute need + // to be filtered + var name = element.getAttribute('name'); + if (!name || !(name in PatchOperation.Operations)) + return true; + + // The "content" attribute must be present for any + // valid "name" meta tag + var content = element.getAttribute('content'); + if (!content) + return true; + + // Filter out and parse meta tag + operations.push(new PatchOperation(name, content)); + return false; + + }); + + // Apply each operation implied by the meta tags + angular.forEach(operations, function applyOperation(operation) { + operation.apply(root, elements); + }); + + }); + + }; + /** * Invokes $templateRequest() with all arguments exactly as provided, * applying all HTML patches from any installed Guacamole extensions @@ -297,49 +339,19 @@ angular.module('index').config(['$provide', function($provide) { // Resolve promise with patched template HTML $delegate.apply(this, arguments).then(function patchTemplate(data) { - // Parse HTML into DOM tree - var root = $('
').html(data); + // Retrieve and apply all patches + patchService.getPatches().success(function applyRetrievedPatches(patches) { - // Apply all defined patches - angular.forEach(patches, function applyPatch(patch) { + // Parse HTML into DOM tree + var root = $('
').html(data); - var elements = $(patch); + // Apply all HTML patches to the parsed DOM + applyPatches(root, patches); - // Filter out and parse all applicable meta tags - var operations = []; - elements = elements.filter(function filterMetaTags(index, element) { + // Transform back into HTML + deferred.resolve.call(this, root.html()); - // Leave non-meta tags untouched - if (element.tagName !== 'META') - return true; - - // Only meta tags having a valid "name" attribute need - // to be filtered - var name = element.getAttribute('name'); - if (!name || !(name in PatchOperation.Operations)) - return true; - - // The "content" attribute must be present for any - // valid "name" meta tag - var content = element.getAttribute('content'); - if (!content) - return true; - - // Filter out and parse meta tag - operations.push(new PatchOperation(name, content)); - return false; - - }); - - // Apply each operation implied by the meta tags - angular.forEach(operations, function applyOperation(operation) { - operation.apply(root, elements); - }); - - }); - - // Transform back into HTML - deferred.resolve.call(this, root.html()); + }, deferred.reject); }, deferred.reject);