diff --git a/modules/distribution/src/analytics/jaggeryapps/portal/designer.json b/modules/distribution/src/analytics/jaggeryapps/portal/designer.json deleted file mode 100644 index c0ec1196..00000000 --- a/modules/distribution/src/analytics/jaggeryapps/portal/designer.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "store": { - "types": ["fs"] - }, - "gadgetGeneration" :{ - "isCreateGadgetEnable": false, - "ignoreProviders": ["rt"] - }, - "authentication": { - "activeMethod": "sso", - "methods": { - "sso": { - "attributes": { - "issuer": "analyticsportal", - "identityProviderURL": "https://localhost:9443/samlsso", - "responseSigningEnabled": true, - "validateAssertionValidityPeriod": true, - "validateAudienceRestriction": true, - "assertionSigningEnabled": true, - "acs": "https://localhost:9445/portal/acs", - "identityAlias": "wso2carbon", - "defaultNameIDPolicy": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", - "useTenantKey": false, - "isPassive": false - } - }, - "basic": { - "attributes": {} - } - } - }, - "authorization": { - "activeMethod": "oauth", - "methods": { - "oauth": { - "attributes": { - "apimgt-gateway": true, - "oauthProvider": { - "appRegistration": { - "appType": "webapp", - "clientName": "analyticsportal", - "owner": "admin", - "password":"admin", - "dynamicClientAppRegistrationServiceURL": "https://localhost:9443/dynamic-client-web/register", - "apiManagerClientAppRegistrationServiceURL": "https://localhost:9443/api-application-registration/register/tenants", - "grantType": "urn:ietf:urn:ietf:params:oauth:grant-type:saml2-bearer", - "tokenScope": "admin", - "callbackUrl": "https://localhost:9445/portal", - "saasApp":true - - }, - "tokenServiceURL": "https://localhost:9443/oauth2/token" - }, - "adminUser":"admin@carbon.super", - "adminUserTenantId":"-1234", - "adminRole":"admin", - "scopes" : [ - "device:view" - ] - } - } - } - }, - "designers": [ - "Internal/everyone" - ], - "tenantPrefix": "/t", - "shareStore": false, - "theme": "basic", - "cacheTimeoutSeconds": "5", - "cacheSizeBytes": "1073741824", - "defaultDashboardRedirect": false, - "isCreateGadgetEnable": true, - "isSecureVaultEnabled" : false, - "assets": { - "gadget": { - "fileSizeLimit": 5 - }, - "layout": { - "fileSizeLimit": 1 - } - }, - "oauth": { - "username": "admin", - "password": "admin" - }, - "host": { - "hostname": "localhost", - "port": "", - "protocol": "" - }, - "queryParameters" : { - "passBetweenPages" : ["shared", "owner", "deviceId"] - } -} diff --git a/modules/distribution/src/analytics/jaggeryapps/portal/jaggery.conf b/modules/distribution/src/analytics/jaggeryapps/portal/jaggery.conf deleted file mode 100644 index 77030553..00000000 --- a/modules/distribution/src/analytics/jaggeryapps/portal/jaggery.conf +++ /dev/null @@ -1,187 +0,0 @@ -{ - "initScripts": [ - "js/dashboard-deployer.js" - ], - "welcomeFiles": [ - "routers/tenant.jag" - ], - "errorPages": { - "500": "/controllers/error-pages/error500.html", - "404": "/controllers/error-pages/error404.html", - "401": "/controllers/error-pages/error401.html", - "405": "/controllers/error-pages/error405.html", - "403": "/controllers/error-pages/error403.html", - "400": "/controllers/error-pages/error400.html" - }, - "urlMappings": [ - { - "url": "/login-controller", - "path": "/routers/tenant.jag" - }, - { - "url": "/login", - "path": "/routers/tenant.jag" - }, - { - "url": "/logout", - "path": "/routers/tenant.jag" - }, - { - "url": "/t/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/apis/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/dashboards/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/gadget/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/layout/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/assets/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/create-dashboard", - "path": "/routers/tenant.jag" - }, - { - "url": "/dashboard-settings/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/select-layout", - "path": "/routers/tenant.jag" - }, - { - "url": "/create-gadget", - "path": "/routers/tenant.jag" - }, - { - "url": "/upload-gadget", - "path": "/routers/tenant.jag" - }, - { - "url": "/upload-layout", - "path": "/routers/tenant.jag" - }, - { - "url": "/geojson/world/*", - "path": "/templates/geojson/world.json" - }, - { - "url": "/geojson/europe/*", - "path": "/templates/geojson/europe.json" - }, - { - "url": "/geojson/usa/*", - "path": "/templates/geojson/usa.json" - }, - { - "url": "/geojson/countryInfo/*", - "path": "/templates/geojson/countryInfo.json" - }, - { - "url": "/geojson/usaInfo/*", - "path": "/templates/geojson/usaInfo.json" - }, - { - "url": "/acs", - "path": "/controllers/acs.jag" - }, - { - "url": "/banners/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/gadgets/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/configs/designer.json", - "path": "/controllers/error-pages/error404.html" - } - ], - "listeners": [ - { - "class": "org.owasp.csrfguard.CsrfGuardServletContextListener" - }, - { - "class": "org.owasp.csrfguard.CsrfGuardHttpSessionListener" - } - ], - "servlets": [ - { - "name": "JavaScriptServlet", - "class": "org.owasp.csrfguard.servlet.JavaScriptServlet" - } - ], - "servletMappings": [ - { - "name": "JavaScriptServlet", - "url": "/csrf.js" - } - ], - "contextParams": [ - { - "name": "Owasp.CsrfGuard.Config", - "value": "repository/conf/security/Owasp.CsrfGuard.dashboard.properties" - } - ], - "filters": [ - { - "name": "ContentTypeBasedCachePreventionFilter", - "class": "org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter", - "params" : [ - {"name" : "patterns", "value" : "text/html\" ,application/json\" ,text/plain"}, - {"name" : "filterAction", "value" : "enforce"}, - {"name" : "httpHeaders", "value" : "Cache-Control: no-store, no-cache, must-revalidate, private"} - ] - }, - { - "name": "HttpHeaderSecurityFilter", - "class": "org.apache.catalina.filters.HttpHeaderSecurityFilter", - "params": [ - { - "name": "hstsEnabled", - "value": "false" - }, - { - "name": "antiClickJackingOption", - "value": "SAMEORIGIN" - } - ] - }, - { - "name": "TenantStoresFilter", - "class": "org.wso2.carbon.dashboard.store.filter.TenantStoreFilter" - } - ], - "filterMappings": [ - { - "name": "HttpHeaderSecurityFilter", - "url": "*" - }, - { - "name": "TenantStoresFilter", - "url": "/store/*" - }, - { - "name": "TenantStoresFilter", - "url": "/temp/*" - }, - { - "name":"ContentTypeBasedCachePreventionFilter", - "url":"*" - } - ] -} diff --git a/modules/distribution/src/analytics/jaggeryapps/portal/libs/VizGrammar_2.js b/modules/distribution/src/analytics/jaggeryapps/portal/libs/VizGrammar_2.js deleted file mode 100644 index 08c8292e..00000000 --- a/modules/distribution/src/analytics/jaggeryapps/portal/libs/VizGrammar_2.js +++ /dev/null @@ -1,2832 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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. - */ - -var arc = function(dataTable, config) { - this.metadata = dataTable[0].metadata; - var marks =[]; - this.spec = {}; - - config = checkConfig(config, this.metadata); - this.config = config; - dataTable[0].name= config.title; - - var summarize = {}; - summarize[this.metadata.names[config.x]] = "sum"; - - dataTable.push({ - "name": "summary", - "source": config.title, - "transform": [ - { - "type": "aggregate", - "summarize": summarize - } - ] - }); - - dataTable.push( { - "name": "layout", - "source": "table", - "transform": [ - {"type": "cross", "with": "summary"}, - {"type": "pie","field": "a." + this.metadata.names[config.x]}, - { - "type": "formula", - "field": "percentage", - "expr": "datum.a."+this.metadata.names[config.x] - +" / datum.b.sum_"+this.metadata.names[config.x]+" * 100" - } - ] - }); - - var scales = []; - - if (config.colorDomain == -1) { - config.colorDomain = {"data": config.title, "field": this.metadata.names[config.color]}; - } - - - var colorScale = { - "name": "color", - "type": "ordinal", - "domain": config.colorDomain, - "range": config.colorScale - }; - scales.push(colorScale); - - - if (config.percentage && - (config.mode == "pie" || config.mode == "donut")) { - marks.push(getPieText(config, this.metadata)); - } else if (config.percentage) { - //Push complimentary value to fill the arc - dataTable.push( - { - "name": "arc", - "values": [{"type": "YES"}] - }); - marks.push(getPieMidText(config, this.metadata)); - } - - marks.push(getPieMark(config, this.metadata)); - - var legendTitle = "Legend"; - - if (config.title != "table") { - legendTitle = config.title; - } - - if (this.config.legend) { - this.spec.legends = getLegend(this.config); - } - - this.spec.width = config.width; - this.spec.height = config.height; - this.spec.data = dataTable; - this.spec.scales = scales; - this.spec.padding = config.padding; - this.spec.marks = marks; -}; - -arc.prototype.draw = function(div, callbacks) { - - var viewUpdateFunction = (function(chart) { - if(this.config.tooltip.enabled){ - this.config.tooltip.type = "arc"; - createTooltip(div); - this.view = chart({el:div}).renderer(this.config.renderer).update(); - bindTooltip(div,this.view,this.config,this.metadata); - } else { - this.view = chart({el:div}).renderer(this.config.renderer).update(); - } - - if (callbacks != null) { - for (var i = 0; i= this.config.maxLength){ - var allowedDataSet = []; - var startingPoint = dataset.length - maxValue; - for(var i = startingPoint; i < dataset.length;i++){ - allowedDataSet.push(dataset[i]); - } - this.spec.data[0].values = allowedDataSet; - } - } - - vg.parse.spec(this.spec, viewUpdateFunction); -}; - -arc.prototype.insert = function(data) { - - var color = this.metadata.names[this.config.color]; - var x = this.metadata.names[this.config.x]; - var view =this.view; - - - - var updated = false; - - for (i = 0; i < data.length; i++) { - this.view.data(this.config.title) - .update( - function(d) { - return d[color] == data[i][color]; - }, - x, - function(d) { - updated = true; - return data[i][x]; - }); - } - - if (updated == false) { - view.data(this.config.title).insert(data); - } - - this.view.update({duration: 500}); -}; - -arc.prototype.getSpec = function() { - return this.spec; -}; - - -function getPieMark(config, metadata){ - var innerRadius; - if (config.mode == "donut") { - var innerRadius = config.height / 5 * ( 1 + config.innerRadius); - } else if (config.mode == "pie") { - var innerRadius = 0; - } else { - config.innerRadius += 0.5; - var innerRadius = config.height / 5 * ( 1 + config.innerRadius); - } - - var title = config.title; - var fieldAlias = "" - - if (config.type != null) { - title = "layout"; - fieldAlias = "a."; - } - - var mark = { - "type": "arc", - "from": {"data": title}, - "properties": { - "update": { - "x": {"field": {"group": "width"}, "mult": 0.5}, - "y": {"field": {"group": "height"}, "mult": 0.5}, - "startAngle": {"field": "layout_start"}, - "endAngle": {"field": "layout_end"}, - "innerRadius": {"value": innerRadius}, - "outerRadius": {"value": config.height * 0.4}, - "fill": {"scale": "color", "field": fieldAlias + metadata.names[config.color]}, - "fillOpacity": {"value": 1} - }, - - "hover": { - "fillOpacity": {"value": 0.8}, - "cursor": {"value": config.hoverCursor} - } - } - }; - - return mark; -}; -function getPieMidText(config, metadata){ - var mark = { - "type": "text", - "from": {"data": "layout"}, - "properties": { - "update": { - "x": {"field": {"group": "width"}, "mult": 0.5}, - "y": {"field": {"group": "height"}, "mult": 0.5}, - "radius": { "value": 0}, - "theta": {"field": "layout_mid"}, - "fill": [ - { - "test": "indata('arc', datum.a."+metadata.names[config.color]+", 'type')", - "scale": "color", "field": metadata.names[config.color] - }, - {} - ], - "fillOpacity": [ - { - "test": "indata('arc', datum.a."+metadata.names[config.color]+", 'type')", - "value": 1 - }, - {"value": 0} - ], - "align": {"value": "center"}, - "baseline": {"value": "middle"}, - "fontSize":{"value": config.height/9}, - "text": {"template": "{{datum.percentage | number:'.2f'}}%"} - - } - } - }; - return mark; -}; - - -function getPieText(config, metadata){ - var mark = { - "type": "text", - "from": {"data": "layout"}, - "properties": { - "update": { - "x": {"field": {"group": "width"}, "mult": 0.5}, - "y": {"field": {"group": "height"}, "mult": 0.5}, - "radius": { "value": config.height * 0.5}, - "theta": {"field": "layout_mid"}, - "fill": {"value": "#000"}, - "align": {"value": "center"}, - "baseline": {"value": "middle"}, - "text": {"template": "{{datum.percentage | number:'.2f'}}%"} - - } - } - }; - - return mark; -}; -; -var area = function(dataTable, config) { - this.metadata = dataTable[0].metadata; - var marks =[]; - var signals = []; - this.spec = {}; - - config = checkConfig(config, this.metadata); - this.config = config; - dataTable[0].name= config.title; - - var scales = getXYScales(config, this.metadata); - - if (config.mode == "stack") { - var aggregateData = { - "name": "stack", - "source": config.title, - "transform": [ - { - "type": "aggregate", - "groupby": [this.metadata.names[config.x]], - "summarize": [{"field": this.metadata.names[config.y], "ops": ["sum"]}] - } - ] - }; - - dataTable.push(aggregateData); - yColumn = "sum_"+ this.metadata.names[config.y]; - yDomain = "stack"; - - scales[1].domain = {"data": yDomain, "field": yColumn}; - - } - - - //Make Y scale zero false as area should filled to minimum value - delete scales[1].zero; - - if (config.color != -1) { - - if (config.colorDomain == -1) { - config.colorDomain = {"data": config.title, "field": this.metadata.names[config.color]}; - } - - var colorScale = { - "name": "color", - "type": "ordinal", - "domain": config.colorDomain, - "range": config.colorScale - }; - scales.push(colorScale); - - var legendTitle = "Legend"; - - if (config.title != "table") { - legendTitle = config.title; - } - - if (this.config.legend) { - this.spec.legends = getLegend(this.config); - } - } - - - var axes = getXYAxes(config, "x", "x", "y", "y"); - - - marks.push(getLineMark(config, this.metadata)); - - config.fillOpacity = 0.7; - marks.push(getAreaMark(config, this.metadata)); - config.fillOpacity = 0; - config.markSize = 1000; - marks.push(getSymbolMark(config, this.metadata)); - config.fillOpacity = 1; - config.markSize = 15; - marks.push(getSymbolMark(config, this.metadata)); - - if (config.range) { - signals = getRangeSignals(config, signals); - marks = getRangeMark(config, marks); - } - - this.spec.width = config.width; - this.spec.height = config.height; - this.spec.axes = axes; - this.spec.data = dataTable; - this.spec.scales = scales; - this.spec.padding = config.padding; - this.spec.marks = marks; - this.spec.signals = signals; -}; - -area.prototype.draw = function(div, callbacks) { - - if(this.config.maxLength != -1){ - var dataset = this.spec.data[0].values; - var maxValue = this.config.maxLength; - if(dataset.length >= this.config.maxLength){ - var allowedDataSet = []; - var startingPoint = dataset.length - maxValue; - for(var i = startingPoint; i < dataset.length;i++){ - allowedDataSet.push(dataset[i]); - } - this.spec.data[0].values = allowedDataSet; - } - } - - drawChart(div, this, callbacks); - -}; - -area.prototype.insert = function(data) { - //Removing events when max value is enabled - if (this.config.maxLength != -1 && this.config.maxLength < (this.view.data(this.config.title).values().length + data.length)) { - var removeFunction = (function(d) { - return d[this.metadata.names[this.config.x]] == oldData; - }).bind(this); - - for (i = 0; i < data.length; i++) { - var oldData = this.view.data(this.config.title).values()[i][this.metadata.names[this.config.x]]; - this.view.data(this.config.title).remove(removeFunction); - } - } - - this.view.data(this.config.title).insert(data); - this.view.update(); -}; - -area.prototype.getSpec = function() { - return this.spec; -}; - - -function getAreaMark(config, metadata){ - - var mark; - if (config.color != -1 && config.mode == "stack") { - mark = { - "type": "group", - "from": { - "data": config.title, - "transform": [ - {"type": "stack", "groupby": [metadata.names[config.x]], "sortby": [metadata.names[config.color]], "field": metadata.names[config.y]}, - {"type": "facet", "groupby": [metadata.names[config.color]]} - ] - }, - "marks": [ - { - "type": "area", - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": "layout_start"}, - "y2": {"scale": "y", "field": "layout_end"}, - "fill": {"scale": "color", "field": metadata.names[config.color]}, - "strokeWidth": {"value": 2}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "strokeOpacity": {"value": 0.5} - } - } - } - ] - }; - } else if (config.color != -1) { - mark = { - "type": "group", - "from": { - "data": config.title, - "transform": [{"type": "facet", "groupby": [metadata.names[config.color]]}] - }, - "marks": [ - { - "type": "area", - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "y2": {"scale": "y", "value": 0}, - "fill": {"scale": "color", "field": metadata.names[config.color]}, - "strokeWidth": {"value": 2}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "strokeOpacity": {"value": 0.5} - } - } - } - ] - }; - - } else{ - mark = { - "type": "area", - "from": {"data": config.title}, - "properties": { - "update": { - - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "y2": {"scale": "y", "value": 0}, - "fill": { "value": config.markColor}, - "strokeWidth": {"value": 2}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "fillOpacity": {"value": 0.5} - } - } - }; - } - - - return mark; -} - -; -var bar = function(dataTable, config) { - this.metadata = dataTable[0].metadata; - var marks =[]; - var scales =[]; - this.spec = {}; - var yColumn; - var yDomain; - - var xRange; - var yRange; - var xAxesType; - var yAxesType; - var signals = []; - - config = checkConfig(config, this.metadata); - this.config = config; - dataTable[0].name= config.title; - - if (config.orientation == "left") { - xRange = "height"; - yRange = "width"; - xAxesType = "y"; - yAxesType = "x"; - } else { - xRange = "width"; - yRange = "height"; - xAxesType = "x"; - yAxesType = "y"; - } - - if (config.color != -1) { - var legendTitle = "Legend"; - if (config.title != "table") { - legendTitle = config.title; - } - if (config.colorDomain == -1) { - config.colorDomain = {"data": config.title, "field": this.metadata.names[config.color]}; - } - - var colorScale = { - "name": "color", - "type": "ordinal", - "domain": config.colorDomain, - "range": config.colorScale - }; - - scales.push(colorScale); - - - - if (config.mode == "stack") { - var aggregateData = { - "name": "stack", - "source": config.title, - "transform": [ - { - "type": "aggregate", - "groupby": [this.metadata.names[config.x]], - "summarize": [{"field": this.metadata.names[config.y], "ops": ["sum"]}] - } - ] - }; - - dataTable.push(aggregateData); - yColumn = "sum_"+ this.metadata.names[config.y]; - yDomain = "stack"; - - } else { - yColumn = this.metadata.names[config.y]; - yDomain = config.title; - } - - if (this.config.legend) { - this.spec.legends = getLegend(this.config); - } - } else { - yColumn = this.metadata.names[config.y]; - yDomain = config.title; - } - - var xScale = { - "name": "x", - "type": "ordinal", - "range": xRange, - "domain": config.xScaleDomain - }; - - if (config.mode == "group") { - xScale.padding = 0.2; - } - - if (config.yScaleDomain.constructor !== Array) { - config.yScaleDomain = {"data": yDomain, "field": yColumn}; - } - - var yScale = { - "name": "y", - "type": this.metadata.types[config.y], - "range": yRange, - "domain": config.yScaleDomain - }; - - - - scales.push(xScale); - scales.push(yScale); - - var axes = getXYAxes(config, xAxesType, "x", yAxesType, "y"); - - if (config.color != -1 && config.mode == "stack") { - marks.push(getStackBarMark(config, this.metadata)); - } else if (config.color != -1 && config.mode == "group") { - marks.push(getGroupBarMark(config, this.metadata)); - } else { - marks.push(getBarMark(config, this.metadata)); - } - - if (config.range) { - signals = getRangeSignals(config, signals); - marks = getRangeMark(config, marks); - } - - if (config.orientation == "left" && config.text != null) { - - var xVal = {"value": 5}; - - if (config.textAlign == "right") { - var xVal = {"scale": "y","field": this.metadata.names[config.y], "offset": 2}; - } - - marks.push({ - "type": "text", - "from": {"data": "table"}, - "properties": { - "update": { - "x": xVal, - "dy": { - "scale": "x", - "band": true, - "mult": 0.5 - }, - "y": {"scale": "x","field": this.metadata.names[config.x]}, - "align":{"value": "left"}, - "text": {"field": this.metadata.names[config.text]}, - "fill": {"value": config.textColor} - } - } - }); - } - - if (config.highlight == "single" || config.highlight == "multi") { - - var multiTest; - - if (config.highlight == "multi") { - multiTest = "!multi"; - } else { - multiTest = "multi"; - } - - - dataTable.push( - { - "name": "selectedPoints", - "modify": [ - {"type": "clear", "test": multiTest}, - {"type": "toggle", "signal": "clickedPoint", "field": "id"} - ] - }); - - signals.push( { - "name": "clickedPoint", - "init": 0, - "verbose": true, - "streams": [{"type": "click", "expr": "datum._id"}] - }, - { - "name": "multi", - "init": false, - "verbose": true, - "streams": [{"type": "click", "expr": "datum._id"}] - }); - - if (config.selectionColor == "") { - marks[0].properties.update.fillOpacity = [ - { - "test": "indata('selectedPoints', datum._id, 'id')", - "value": 1 - },{"value":config.selectionOpacity} - ]; - } else { - marks[0].properties.update.fill = [ - { - "test": "indata('selectedPoints', datum._id, 'id')", - "value": config.selectionColor - },marks[0].properties.update.fill - ]; - } - } - - this.spec.width = config.width; - this.spec.height = config.height; - this.spec.axes = axes; - this.spec.data = dataTable; - this.spec.scales = scales; - this.spec.padding = config.padding; - this.spec.marks = marks; - this.spec.signals = signals; - - var specc = JSON.stringify(this.spec); -}; - -bar.prototype.draw = function(div, callbacks) { - if(this.config.maxLength != -1){ - var dataset = this.spec.data[0].values; - var maxValue = this.config.maxLength; - if(dataset.length >= this.config.maxLength){ - var allowedDataSet = []; - var startingPoint = dataset.length - maxValue; - for(var i = startingPoint; i < dataset.length;i++){ - allowedDataSet.push(dataset[i]); - } - this.spec.data[0].values = allowedDataSet; - } - } - this.config.tooltip.type = "rect"; - drawChart(div, this, callbacks); -}; - -bar.prototype.insert = function(data) { - - var xAxis = this.metadata.names[this.config.x]; - var yAxis = this.metadata.names[this.config.y]; - var size = this.metadata.names[this.config.size]; - var color = this.metadata.names[this.config.color]; - - if (this.config.maxLength != -1 && this.config.maxLength < (this.view.data(this.config.title).values().length + data.length)) { - - var allDataSet = this.view.data(this.config.title).values().concat(data); - var allowedRemovableDataSet = []; - for (i = 0; i < allDataSet.length - this.config.maxLength; i++) { - allowedRemovableDataSet.push(this.view.data(this.config.title).values()[i][xAxis]); - } - - for (i = 0; i < data.length; i++) { - var isValueMatched = false; - this.view.data(this.config.title).update(function(d) { - if (color == null) { - return d[xAxis] == data[i][xAxis]; - } else { - return d[xAxis] == data[i][xAxis] && d[color] == data[i][color]; - } - }, - yAxis, - function(d) { - isValueMatched = true; - return data[i][yAxis]; - }); - - if(isValueMatched){ - var isIndexRemoved = false; - - var index = allowedRemovableDataSet.indexOf(data[i][xAxis]); - if (index > -1) { - // updated value matched in allowed removable values - isIndexRemoved = true; - allowedRemovableDataSet.splice(index, 1); - } - - if(!isIndexRemoved){ - // updated value NOT matched in allowed removable values - allowedRemovableDataSet.splice((allowedRemovableDataSet.length - 1), 1); - } - - } else { - //insert the new data - this.view.data(this.config.title).insert([data[i]]); - this.view.update(); - } - } - - var oldData; - var removeFunction = function(d) { - return d[xAxis] == oldData; - }; - - for (i = 0; i < allowedRemovableDataSet.length; i++) { - oldData = allowedRemovableDataSet[i]; - this.view.data(this.config.title).remove(removeFunction); - } - } else{ - for (i = 0; i < data.length; i++) { - var isValueMatched = false; - this.view.data(this.config.title).update(function(d) { - if (color == null) { - return d[xAxis] == data[i][xAxis]; - } else { - return d[xAxis] == data[i][xAxis] && d[color] == data[i][color]; - } - }, - yAxis, - function(d) { - isValueMatched = true; - return data[i][yAxis]; - }); - - if(!isValueMatched){ - this.view.data(this.config.title).insert([data[i]]); - } - } - } - - //Group does not support duration update animation - if (this.config.mode == "group") { - this.view.update(); - } else { - this.view.update({duration: 200}); - } -}; - -bar.prototype.getSpec = function() { - return this.spec; -}; - -bar.prototype.setSpec = function(spec) { - this.spec = spec; -} - - -function getBarMark(config, metadata){ - var markContent; - if (config.orientation == "left") { - markContent = { - "y": {"scale": "x", "field": metadata.names[config.x]}, - "height": {"scale": "x", "band": true, "offset": calculateBarGap(config)}, - "x": {"scale": "y", "field": metadata.names[config.y]}, - "x2": {"scale": "y", "value": 0}, - "fill": {"value": config.markColor}, - "fillOpacity": {"value": config.fillOpacity} - }; - } else { - markContent = { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "width": {"scale": "x", "band": true, "offset": calculateBarGap(config)}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "y2": {"scale": "y", "value": 0}, - "fill": {"value": config.markColor}, - "fillOpacity": {"value": config.fillOpacity} - }; - } - - var mark = { - "name": "bars", - "type": "rect", - "from": {"data": config.title}, - "properties": { - "update": markContent, - "hover": { - "fillOpacity": {"value": 0.5}, - "cursor": {"value": config.hoverCursor} - } - } - }; - - - return mark; -} - -function getStackBarMark(config, metadata){ - var markContent; - if (config.orientation == "left") { - mark = { - "name": "bars", - "type": "rect", - "from": { - "data": config.title, - "transform": [ - { "type": "stack", - "groupby": [metadata.names[config.x]], - "sortby": [metadata.names[config.color]], - "field":metadata.names[config.y]} - ] - }, - "properties": { - "update": { - "y": {"scale": "x", "field": metadata.names[config.x]}, - "height": {"scale": "x", "band": true, "offset": calculateBarGap(config)}, - "x": {"scale": "y", "field": "layout_start"}, - "x2": {"scale": "y", "field": "layout_end"}, - "fill": {"scale": "color", "field": metadata.names[config.color]}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "fillOpacity": {"value": 0.5}, - "cursor": {"value": config.hoverCursor} - } - } - }; - } else { - - mark = { - "name": "bars", - "type": "rect", - "from": { - "data": config.title, - "transform": [ - { "type": "stack", - "groupby": [metadata.names[config.x]], - "sortby": [metadata.names[config.color]], - "field":metadata.names[config.y]} - ] - }, - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "width": {"scale": "x", "band": true, "offset": calculateBarGap(config)}, - "y": {"scale": "y", "field": "layout_start"}, - "y2": {"scale": "y", "field": "layout_end"}, - "fill": {"scale": "color", "field": metadata.names[config.color]}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "fillOpacity": {"value": 0.5}, - "cursor": {"value": config.hoverCursor} - } - } - }; - } - - - - - return mark; -} - -function getGroupBarMark(config, metadata){ - var mark; - if (config.orientation == "left") { - mark = { - "name": "bars", - "type": "group", - "from": { - "data": config.title, - "transform": [{"type":"facet", "groupby": [metadata.names[config.x]]}] - }, - "properties": { - "update": { - "y": {"scale": "x", "field": "key"}, - "height": {"scale": "x", "band": true} - } - }, - "scales": [ - { - "name": "pos", - "type": "ordinal", - "range": "height", - "domain": {"field": metadata.names[config.color]} - } - ], - "marks": [ - { - "name": "bar", - "type": "rect", - "properties": { - "update": { - "y": {"scale": "pos", "field": metadata.names[config.color]}, - "height": {"scale": "pos", "band": true, "offset": calculateBarGap(config)}, - "x": {"scale": "y", "field": metadata.names[config.y]}, - "x2": {"scale": "y", "value": 0}, - "fill": {"scale": "color", "field": metadata.names[config.color]}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "fillOpacity": {"value": 0.5}, - "cursor": {"value": config.hoverCursor} - } - } - } - ] - }; - } else { - mark = { - "name": "bars", - "type": "group", - "from": { - "data": config.title, - "transform": [{"type":"facet", "groupby": [metadata.names[config.x]]}] - }, - "properties": { - "update": { - "x": {"scale": "x", "field": "key"}, - "width": {"scale": "x", "band": true} - } - }, - "scales": [ - { - "name": "pos", - "type": "ordinal", - "range": "width", - "domain": {"field": metadata.names[config.color]} - } - ], - "marks": [ - { - "name": "bar", - "type": "rect", - "properties": { - "update": { - "x": {"scale": "pos", "field": metadata.names[config.color]}, - "width": {"scale": "pos", "band": true, "offset": calculateBarGap(config)}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "y2": {"scale": "y", "value": 0}, - "fill": {"scale": "color", "field": metadata.names[config.color]}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "fillOpacity": {"value": 0.5}, - "cursor": {"value": config.hoverCursor} - } - } - } - ] - }; - } - return mark; -} - -function calculateBarGap(config){ - - var xWidth; - var widthWeight = 30; - - if (config.orientation == "left") { - xWidth = config.height; - } else { - xWidth = config.width - } - - if (config.mode == "group") { - widthWeight = 80; - } - - return -config.barGap * (xWidth/widthWeight); - -};var vizg = function(dataTable, config) { - dataTable = buildTable(dataTable); - if (typeof config.charts !== "undefined" && config.charts.length == 1) { - //Set chart config properties for main - for (var property in config.charts[0]) { - if (config.charts[0].hasOwnProperty(property)) { - config[property] = config.charts[0][property]; - } - } - - this.chart = new window[config.type]([dataTable], config); - } -}; - -vizg.prototype.draw = function(div, callback) { - this.chart.draw(div, callback); -}; - -vizg.prototype.insert = function(data) { - this.chart.insert(buildData(data, this.chart.metadata)); -}; - -vizg.prototype.getSpec = function() { - return this.chart.getSpec(); -};; -var line = function(dataTable, config) { - this.metadata = dataTable[0].metadata; - var marks =[]; - var signals = []; - this.spec = {}; - - config = checkConfig(config, this.metadata); - this.config = config; - dataTable[0].name= config.title; - - var scales = getXYScales(config, this.metadata); - - if (config.mode == "stack") { - var aggregateData = { - "name": "stack", - "source": config.title, - "transform": [ - { - "type": "aggregate", - "groupby": [this.metadata.names[config.x]], - "summarize": [{"field": this.metadata.names[config.y], "ops": ["sum"]}] - } - ] - }; - - dataTable.push(aggregateData); - yColumn = "sum_"+ this.metadata.names[config.y]; - yDomain = "stack"; - - scales[1].domain = {"data": yDomain, "field": yColumn}; - - } - - - - if (config.color != -1) { - - if (config.colorDomain == -1) { - config.colorDomain = {"data": config.title, "field": this.metadata.names[config.color]}; - } - - var colorScale = { - "name": "color", - "type": "ordinal", - "domain": config.colorDomain, - "range": config.colorScale - }; - scales.push(colorScale); - - var legendTitle = "Legend"; - - if (config.title != "table") { - legendTitle = config.title; - } - - if (this.config.legend) { - this.spec.legends = getLegend(this.config); - } - } - - - var axes = getXYAxes(config, "x", "x", "y", "y"); - - - marks.push(getLineMark(config, this.metadata)); - config.fillOpacity = 0; - config.markSize = 1000; - marks.push(getSymbolMark(config, this.metadata)); - config.fillOpacity = 1; - config.markSize = 15; - marks.push(getSymbolMark(config, this.metadata)); - - if (config.range) { - signals = getRangeSignals(config, signals); - marks = getRangeMark(config, marks); - } - - this.spec.width = config.width; - this.spec.height = config.height; - this.spec.axes = axes; - this.spec.data = dataTable; - this.spec.scales = scales; - this.spec.padding = config.padding; - this.spec.marks = marks; - this.spec.signals = signals; -}; - -line.prototype.draw = function(div, callbacks) { - - if(this.config.maxLength != -1){ - var dataset = this.spec.data[0].values; - var maxValue = this.config.maxLength; - if(dataset.length >= this.config.maxLength){ - var allowedDataSet = []; - var startingPoint = dataset.length - maxValue; - for(var i = startingPoint; i < dataset.length;i++){ - allowedDataSet.push(dataset[i]); - } - this.spec.data[0].values = allowedDataSet; - } - } - - drawChart(div, this, callbacks); - -}; - -line.prototype.insert = function(data) { - //Removing events when max value is enabled - if (this.config.maxLength != -1 && this.config.maxLength < (this.view.data(this.config.title).values().length + data.length)) { - var removeFunction = (function(d) { - return d[this.metadata.names[this.config.x]] == oldData; - }).bind(this); - - for (i = 0; i < data.length; i++) { - var oldData = this.view.data(this.config.title).values()[i][this.metadata.names[this.config.x]]; - this.view.data(this.config.title).remove(removeFunction); - } - } - - this.view.data(this.config.title).insert(data); - this.view.update(); -}; - -line.prototype.getSpec = function() { - return this.spec; -}; - - -function getLineMark(config, metadata){ - - var mark; - if (config.color != -1 && config.mode == "stack") { - mark = { - "type": "group", - "from": { - "data": config.title, - "transform": [ - {"type": "stack", "groupby": [metadata.names[config.x]], "sortby": [metadata.names[config.color]], "field": metadata.names[config.y]}, - {"type": "facet", "groupby": [metadata.names[config.color]]} - ] - }, - "marks": [ - { - "type": "line", - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": "layout_start"}, - "y2": {"scale": "y", "field": "layout_end"}, - "stroke": {"scale": "color", "field": metadata.names[config.color]}, - "strokeWidth": {"value": 2} - }, - "hover": { - "strokeOpacity": {"value": 0.5} - } - } - } - ] - }; - } else if (config.color != -1) { - mark = { - "type": "group", - "from": { - "data": config.title, - "transform": [{"type": "facet", "groupby": [metadata.names[config.color]]}] - }, - "marks": [ - { - "type": "line", - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "y2": {"scale": "y", "value": 0}, - "stroke": {"scale": "color", "field": metadata.names[config.color]}, - "strokeWidth": {"value": 2} - }, - "hover": { - "strokeOpacity": {"value": 0.5} - } - } - } - ] - }; - - } else{ - mark = { - "type": "line", - "from": {"data": config.title}, - "properties": { - "update": { - - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "y2": {"scale": "y", "value": 0}, - "stroke": { "value": config.markColor}, - "strokeWidth": {"value": 2} - }, - "hover": { - "fillOpacity": {"value": 0.5} - } - } - }; - } - - - return mark; -} - -;var map = function(dataTable, config) { - - this.metadata = dataTable[0].metadata; - var marks ; - var signals ; - var predicates = []; - var legends = []; - this.spec = {}; - var geoInfoJson ; - - geoInfoJson = loadGeoMapCodes(config.helperUrl); - config = checkConfig(config, this.metadata); - this.config = config; - this.config.geoInfoJson = geoInfoJson; - - for (i = 0; i < dataTable[0].values.length; i++) { - for (var key in dataTable[0].values[i]) { - if(key == dataTable[0].metadata.names[config.x]){ - if (dataTable[0].values[i].hasOwnProperty(key)) { - dataTable[0].values[i].unitName = dataTable[0].values[i][key]; - dataTable[0].values[i][key] = getMapCode(dataTable[0].values[i][key], config.mapType,geoInfoJson); - break; - } - } - } - }; - - dataTable[0].name = config.title; - dataTable[0].transform = [ - { - "type": "formula", - "field": "v", - "expr": "datum."+this.metadata.names[config.y] - } - ]; - - if (config.tooltip.enabled) { - marks = getMapMark(config, this.metadata); - signals = getMapSignals(); - this.spec.signals = signals; - } - - dataTable.push(getTopoJson(config,this.metadata)); - predicates.push(getMapPredicates()); - - if (config.legend) { - legends.push(getMapLegends(config,this.metadata)); - } - - var cScale = { - "name": "color", - "type": "linear", - "domain": {"data": "geoData","field": "zipped.v"}, - "domainMin": 0.0, - "zero": false, - "range": config.colorScale - }; - - if (config.highlight == "single" || config.highlight == "multi") { - - var multiTest; - - if (config.highlight == "multi") { - multiTest = "!multi"; - } else { - multiTest = "multi"; - } - - - dataTable.push( - { - "name": "selectedPoints", - "modify": [ - {"type": "clear", "test": multiTest}, - {"type": "toggle", "signal": "clickedPoint", "field": "id"} - ] - }); - - signals.push( { - "name": "clickedPoint", - "init": 0, - "verbose": true, - "streams": [{"type": "click", "expr": "datum._id"}] - }, - { - "name": "multi", - "init": false, - "verbose": true, - "streams": [{"type": "click", "expr": "datum._id"}] - }); - - - marks[0].properties.update.fillOpacity = [ - { - "test": "indata('selectedPoints', datum._id, 'id')", - "value": 1 - },{"value":config.selectionOpacity} - ]; - - } - - var scales = [cScale]; - - this.spec.width = config.width; - this.spec.height = config.height; - this.spec.data = dataTable; - this.spec.scales = scales; - this.spec.padding = config.padding; - this.spec.marks = marks; - this.spec.predicates = predicates; - this.spec.legends = legends; - this.spec.signals = signals; - -}; - -map.prototype.draw = function(div, callbacks) { - var viewUpdateFunction = (function(chart) { - this.view = chart({el:div}).renderer(this.config.renderer).update(); - - if (callbacks != null) { - for (var i = 0; i" + this.config.title+ "

" - + "

" + textContent + "

" - + "

0

" - + "

0%

"; - - document.getElementById(div).innerHTML = divContent; - this.view = contentId; -}; - -number.prototype.insert = function(data) { - var current = data[data.length-1][this.metadata.names[this.config.x]]; - var previous = document.getElementById("val" + this.view).innerHTML; - var difference = current - previous; - var diffPercentage; - var sign = ""; - - if (previous != "" && previous != 0) { - diffPercentage = (difference / previous).toFixed(2) * 100 + "%"; - } else { - diffPercentage = ""; - } - - if (difference > 0) { - sign = "+"; - } - - document.getElementById("diffPercentage" + this.view).innerHTML = sign + diffPercentage; - document.getElementById("diff" + this.view).innerHTML = sign + difference; - document.getElementById("val" + this.view).innerHTML = current; - -}; - - - -;var scatter = function(dataTable, config) { - - this.metadata = dataTable[0].metadata; - var marks = []; - var signals ; - this.spec = {}; - - config = checkConfig(config, this.metadata); - this.config = config; - dataTable[0].name = config.title; - - var rScale = { - "name": "size", - "type": "linear", - "range": [0,576], - "domain": {"data": config.title, "field": this.metadata.names[config.size]} - }; - - var cScale = { - "name": "color", - "type": this.metadata.types[config.color], - "range": config.colorScale, - "domain": {"data": config.title, "field": this.metadata.names[config.color]} - }; - - var scales = getXYScales(config, this.metadata); - scales.push(rScale); - scales.push(cScale); - - var axes = getXYAxes(config, "x", "x", "y", "y"); - - marks.push(getScatterMark(config, this.metadata)); - - if (this.config.legend - && this.metadata.types[config.color] != "linear") { - this.spec.legends = getLegend(this.config); - } - - this.spec.width = config.width; - this.spec.height = config.height; - this.spec.axes = axes; - this.spec.data = dataTable; - this.spec.scales = scales; - this.spec.padding = config.padding; - this.spec.marks = marks; - -}; - -scatter.prototype.draw = function(div, callbacks) { - var viewUpdateFunction = (function(chart) { - if(this.config.tooltip.enabled){ - createTooltip(div); - this.view = chart({el:div}).renderer(this.config.renderer).update(); - bindTooltip(div,this.view,this.config,this.metadata); - } else { - this.view = chart({el:div}).renderer(this.config.renderer).update(); - } - if (callbacks != null) { - for (var i = 0; i= this.config.maxLength){ - var allowedDataSet = []; - var startingPoint = dataset.length - maxValue; - for(var i = startingPoint; i < dataset.length;i++){ - allowedDataSet.push(dataset[i]); - } - this.spec.data[0].values = allowedDataSet; - } - } - - vg.parse.spec(this.spec, viewUpdateFunction); -}; - -scatter.prototype.insert = function(data) { - - var xAxis = this.metadata.names[this.config.x]; - var yAxis = this.metadata.names[this.config.y]; - var size = this.metadata.names[this.config.size]; - var color = this.metadata.names[this.config.color]; - - if (this.config.maxLength != -1 && this.config.maxLength < (this.view.data(this.config.title).values().length + data.length)) { - - var allDataSet = this.view.data(this.config.title).values().concat(data); - var allowedRemovableDataSet = []; - for (i = 0; i < allDataSet.length - this.config.maxLength; i++) { - allowedRemovableDataSet.push(this.view.data(this.config.title).values()[i][xAxis]); - } - - for (i = 0; i < data.length; i++) { - var isValueMatched = false; - this.view.data(this.config.title).update(function(d) { - return d[xAxis] == data[i][xAxis]; }, - yAxis, - function(d) { - isValueMatched = true; - return data[i][yAxis]; - }); - - this.view.data(this.config.title).update(function(d) { - return d[xAxis] == data[i][xAxis]; }, - color, - function(d) { - isValueMatched = true; - return data[i][color]; - }); - - this.view.data(this.config.title).update(function(d) { - return d[xAxis] == data[i][xAxis]; }, - size, - function(d) { - isValueMatched = true; - return data[i][size]; - }); - - if(isValueMatched){ - var isIndexRemoved = false; - - var index = allowedRemovableDataSet.indexOf(data[i][xAxis]); - if (index > -1) { - // updated value matched in allowed removable values - isIndexRemoved = true; - allowedRemovableDataSet.splice(index, 1); - } - - if(!isIndexRemoved){ - // updated value NOT matched in allowed removable values - allowedRemovableDataSet.splice((allowedRemovableDataSet.length - 1), 1); - } - - } else { - //insert the new data - this.view.data(this.config.title).insert([data[i]]); - this.view.update(); - } - } - - var oldData; - var removeFunction = function(d) { - return d[xAxis] == oldData; - }; - - for (i = 0; i < allowedRemovableDataSet.length; i++) { - oldData = allowedRemovableDataSet[i]; - this.view.data(this.config.title).remove(removeFunction); - } - } else{ - for (i = 0; i < data.length; i++) { - var isValueMatched = false; - this.view.data(this.config.title).update(function(d) { - return d[xAxis] == data[i][xAxis]; }, - yAxis, - function(d) { - isValueMatched = true; - return data[i][yAxis]; - }); - - this.view.data(this.config.title).update(function(d) { - return d[xAxis] == data[i][xAxis]; }, - color, - function(d) { - isValueMatched = true; - return data[i][color]; - }); - - this.view.data(this.config.title).update(function(d) { - return d[xAxis] == data[i][xAxis]; }, - size, - function(d) { - isValueMatched = true; - return data[i][size]; - }); - - if(!isValueMatched){ - this.view.data(this.config.title).insert([data[i]]); - } - } - } - this.view.update({duration: 200}); -}; - -scatter.prototype.getSpec = function() { - return this.spec; -}; - - -function getScatterMark(config, metadata){ - var fill; - var size; - - if (config.color == -1) { - fill = {"value": config.markColor}; - } else { - fill = {"scale": "color", "field": metadata.names[config.color]}; - } - - if (config.size == -1) { - size = {"value": config.markSize * 50}; - } else { - size = {"scale":"size","field":metadata.names[config.size]}; - } - - var mark = { - - "type": "symbol", - "from": {"data": config.title}, - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "fill": fill, - "size": size, - "fillOpacity": {"value": 1} - }, - "hover": { - "fillOpacity": {"value": 0.5}, - "cursor": {"value": config.hoverCursor} - } - } - - } - ; - - - return mark; -} - -function getScatterToolTipMark(config, metadata) { - config.toolTip.height = 50; - config.toolTip.y = -50; - - var mark = getToolTipMark(config, metadata); - var sizeText = { - "type": "text", - "properties": { - "update": { - "x": {"value": 6}, - "y": {"value": 44}, - "text": {"template": "Size \t (" + metadata.names[config.size] + ") \t {{hover." + metadata.names[config.size] + "}}"}, - "fill": {"value": "black"} - } - } - }; - mark.marks.push(sizeText); - return mark; -} -; -var table = function(dataTable, config) { - this.metadata = dataTable[0].metadata; - this.data = dataTable[0].values - var marks =[]; - this.spec = {}; - config = checkConfig(config, this.metadata); - this.config = config; - dataTable[0].name= config.title; - - if (this.config.columnTitles == null) { - this.config.columnTitles = this.config.columns; - } - -}; - -table.prototype.draw = function(div) { - var table = d3.select(div).append("table") - .attr( "class", "table table-bordered") - .attr("id", this.config.title); - - // set up the table header - table.append('thead').attr("align", "center") - .append('tr') - .selectAll('th') - .data(this.config.columnTitles) - .enter() - .append('th') - .html(function (d) { return d }); - - table.append('tbody').attr("id", "tableChart-"+this.config.title); - this.setupData(this.data, this.config); - - table.selectAll("thead th") - .html(function(column) { - return column.charAt(0).toUpperCase() + column.substr(1); - }); - - -}; - -table.prototype.insert = function(data) { - this.setupData(data, this.config); -}; - - -table.prototype.setupData = function (dataset, config) { - var data = []; - var allColumns = this.metadata.names; - - //Select specified columns from dataset - for (var i = 0; i < dataset.length; i++) { - var row = {}; - - for (var x = 0; x < config.columns.length; x++) { - row[config.columns[x]] = dataset[i][config.columns[x]]; - } - data.push(row); - } - - //Select Rows by x Axis - var rows = d3.select('#tableChart-'+config.title) - .selectAll('tr') - .data(data, function(d) { return d[config.key]}) - - var entertd = rows.enter() - .append('tr') - .selectAll('td') - .data(function(row) { - return config.columns.map(function(column) { - return {column: column, value: row[column]}; - }); - }) - .enter() - .append('td') - - //Color cell background - if (config.color != -1) { - d3.select('#tableChart-'+config.title) - .selectAll('td') - .attr('bgcolor', - function(d) { - var column = d.key || d.column; - - var color; - if (typeof config.colorScale == "string") { - color = window["d3"]["scale"][config.colorScale]().range(); - } else { - color = config.colorScale; - } - - var colorIndex; - for(var i = 0; i < allColumns.length; i += 1) { - if(allColumns[i] === column) { - colorIndex = i; - } - } - - if (typeof d.value == "string" && (config.color == "*" || column == allColumns[config.color])) { - - var colorDomain; - - if (config.colorDomain == -1) { - colorDomain = [d3.min(d3.select('#tableChart-'+config.title) .selectAll('tr') .data(), function(d) { return d[column]; }), - d3.max(d3.select('#tableChart-'+config.title) .selectAll('tr') .data(), function(d) { return d[column]; })] - - } else { - colorDomain = config.colorDomain - } - - var color; - if (typeof config.colorScale == "string") { - color = window["d3"]["scale"][config.colorScale]().range(); - } else { - color = config.colorScale; - } - - var colorScale = d3.scale.ordinal() - .range(color) - .domain(colorDomain); - return colorScale(d.value); - - } else if (config.color == "*" || column == allColumns[config.color]){ - - var colorScale = d3.scale.linear() - .range(['#f2f2f2', color[colorIndex]]) - .domain([d3.min(d3.select('#tableChart-'+config.title) .selectAll('tr') .data(), function(d) { return d[column]; }), - d3.max(d3.select('#tableChart-'+config.title) .selectAll('tr') .data(), function(d) { return d[column]; })] - ); - - return colorScale(d.value); - } - - }); - } - - - - entertd.append('span') - var td = rows.selectAll('td') - .style({"padding": "0px 10px 0px 10px"}) - - .data(function(d) { return d3.map(d).entries() }) - .attr('class', function (d) { return d.key }) - - - - - td.select('span') - .html(function(d) { - return d.value - }) - //Remove data items when it hits maxLength - if (config.maxLength != -1 && d3.select('tbody').selectAll('tr').data().length > config.maxLength) { - var allowedDataset = d3.select('tbody').selectAll('tr').data().slice(d3.select('tbody').selectAll('tr').data().length- config.maxLength, config.maxLength); - d3.select('tbody').selectAll('tr').data(allowedDataset, - function(d) { - return(d); - }) - .remove(); - } -};var extend = function (defaults, options) { - var extended = {}; - var prop; - for (prop in defaults) { - if (Object.prototype.hasOwnProperty.call(defaults, prop)) { - extended[prop] = defaults[prop]; - } - } - for (prop in options) { - if (Object.prototype.hasOwnProperty.call(options, prop)) { - extended[prop] = options[prop]; - } - } - return extended; -}; - -function checkConfig(config, metadata){ - - if (config.color == null) { - config.color = -1; - } else if (config.color != "*"){ - config.color = metadata.names.indexOf(config.color); - } - - if (config.size == null) { - config.size = -1; - } else { - config.size = metadata.names.indexOf(config.size); - } - - var defaults = { - title: "table", - mapType: -1, - mode: "group", - //color hex array or string: category10, 10c, category20, category20b, category20c - colorScale: "category10", - colorDomain: -1, - maxLength: -1, - markSize: 2, - fillOpacity: 1, - innerRadius:0, - //string: canvas or svg - renderer: "svg", - padding: {"top": 10, "left": 50, "bottom": 40, "right": 0}, - dateFormat: "%x %X", - range:false, - rangeColor:"#222", - selectionColor:"#222", - selectionOpacity:0.6, - barGap:1, - mapColor:"#888", - hoverCursor:"pointer", - rangeCursor:"grab", - - textColor:"#888", - - //Tooltip Configs - tooltip: { - "enabled":true, - "bgColor":"#000", - "textColor":"#fff", - "opacity":"0.9", - "fontSize":"12px", - "type":"symbol" - }, - - //Legend Configs - legend:true, - legendTitle: "Legend", - legendTitleColor: "#222", - legendTitleFontSize: 13, - legendTextColor: "#888", - ledgendTextFontSize: 12, - - //Axes Configs - xTitle: config.x, - yTitle: config.y, - xAxisAngle:false, - yAxisAngle:false, - - xAxisStrokeSize:0, - xAxisColor:"#222", - xAxisSize:1, - xAxisFontSize:10, - xAxisTitleFontSize:12, - xAxisTitleFontColor:"#222", - - yAxisStrokeSize:0, - yAxisColor:"#222", - yAxisSize:1, - yAxisFontSize:10, - yAxisTitleFontSize:12, - yAxisTitleFontColor:"#222", - - grid: true, - zero: false, - xTicks: 10, - yTicks: 10, - xFormat: "", - yFormat: "", - - xScaleDomain: null, - yScaleDomain: null - - - }; - - if (typeof vizgSettings != 'undefined'){ - defaults = extend(defaults, vizgSettings); - } - - config = extend(defaults, config); - - if (config.legend && config.padding.right < 60) { - config.padding.right += 60; - } - - config.height = config.height - (config.padding.top + config.padding.bottom); - config.width = config.width - (config.padding.left + config.padding.right); - - if (typeof config.colorScale == "string") { - config.markColor = window["d3"]["scale"][config.colorScale]().range()[0]; - } else { - config.markColor = config.colorScale[0]; - } - - config.x = metadata.names.indexOf(config.x); - config.y = metadata.names.indexOf(config.y); - config.text = metadata.names.indexOf(config.text); - - if (config.xScaleDomain == null) { - config.xScaleDomain = {"data": config.title, "field": metadata.names[config.x]}; - } - - if (config.yScaleDomain == null) { - config.yScaleDomain = {"data": config.title, "field": metadata.names[config.y]}; - } - - return config; -} - -function buildTable(datatable) { - var chartDatatable = {}; - chartDatatable.metadata = datatable[0].metadata; - chartDatatable.values = buildData(datatable[0].data, datatable[0].metadata); - return chartDatatable; -} - - -function buildData(data, metadata) { - chartData = []; - for (i = 0; i < data.length; i++) { - var row = {}; - for (x = 0; x < metadata.names.length; x++) { - row[metadata.names[x]] = data[i][x]; - } - chartData.push(row); - } - return chartData; -} - -/* - General function used to draw circle symbols graphs - */ -function getSymbolMark(config, metadata) { - - var fill; - if (config.color != -1) { - fill = {"scale": "color", "field": metadata.names[config.color]}; - } else { - fill = {"value":config.markColor}; - } - - var mark; - - if (config.mode == "stack") { - mark = { - "type": "group", - "from": { - "data": config.title, - "transform": [ - {"type": "stack", "groupby": [metadata.names[config.x]], "sortby": [metadata.names[config.color]], "field": metadata.names[config.y]}, - {"type": "facet", "groupby": [metadata.names[config.color]]} - ] - }, - "marks": [ - { - "type": "symbol", - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": "layout_start"}, - "y2": {"scale": "y", "field": "layout_end"}, - "fill": {"scale": "color", "field": metadata.names[config.color]}, - "size": {"value": config.markSize}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover": { - "cursor": {"value": config.hoverCursor} - } - } - } - ] - }; - } else { - mark = { - "name": "points-group", - "type": "symbol", - "from": {"data": config.title}, - "properties": { - "update": { - "x": {"scale": "x", "field": metadata.names[config.x]}, - "y": {"scale": "y", "field": metadata.names[config.y]}, - "fill": fill, - "size": {"value": config.markSize}, - "fillOpacity": {"value": config.fillOpacity} - }, - "hover" : { - "cursor": {"value": config.hoverCursor} - } - } - } - } - return mark; -} - -function getSignals(config, metadata){ - - var signals = [{ - "name": "hover", - "init": {}, - "streams": [ - {"type": config.hoverType+":mouseover", "expr": "datum"}, - {"type": config.hoverType+":mouseout", "expr": "{}"} - ] - }]; - - return signals; - -} - -function bindTooltip(div,markType,eventObj, config, metaData, keyList){ - - eventObj.on("mouseover", function(event, item) { - - if (item != null && item.status != "exit" && item.mark.marktype == markType) { - var canvas = $(".marks")[0]; - if($("#wrapper #tip").length) { - $tip.remove(); - } - - $(div).wrap( "
" ); - - $("#wrapper").append("
"); - $tip=$('#tip'); - $tip.empty(); - - var dataObj = item.datum; - var dynamicContent = ""; - for (var key in dataObj) { - if (dataObj.hasOwnProperty(key)) { - if(keyList != undefined){ - for(var z=0;z"; - break; - } - } - } - }else{ - if(metaData.names[config.x] == key){ - dynamicContent += "

X ("+key+"):"+dataObj[key]+"

"; - } - if(metaData.names[config.y] == key){ - dynamicContent += "

Y ("+key+"):"+dataObj[key]+"

"; - } - } - } - } - - $tip.append(dynamicContent); - - var canvasWidth = canvas.width; - var canvasHeight = canvas.height; - - var el = $('.marks[style*="width"]'); - - if(el.length > 0){ - canvasWidth = parseFloat($(".marks")[0].style.width); - canvasHeight = parseFloat($(".marks")[0].style.height); - } - var dynamicWidth = $tip.width(); - var dynamicHeight = $tip.height(); - - var toolTipWidth = item.bounds.x2 + config.padding.left + dynamicWidth; - var toolTipHeight = (canvasHeight - item.bounds.y2) - config.padding.top + dynamicHeight; - var toolTipCalculatedXPosition; - var toolTipCalculatedYPosition = ((item.bounds.y2 + config.padding.top) - dynamicHeight); - - if(toolTipWidth > canvasWidth){ - toolTipCalculatedXPosition = ((item.bounds.x2 + config.padding.left) - dynamicWidth); - }else{ - toolTipCalculatedXPosition = (item.bounds.x2 + config.padding.left); - } - - if(toolTipHeight > canvasHeight){ - toolTipCalculatedYPosition = item.bounds.y2 + config.padding.top; - } - - $tip.css({left:toolTipCalculatedXPosition,top:toolTipCalculatedYPosition}).show(); - }else{ - - if($("#wrapper #tip").length) { - $tip.remove(); - } - if($(div).closest("#wrapper").length) { - $(div).unwrap(); - } - } - }) -}; - -function createTooltip(div) { - document.getElementById(div.replace("#", "")).innerHTML = document.getElementById(div.replace("#", "")).innerHTML - + "
"; -} - -function bindTooltip(div, view, config, metadata){ - - view.on("mouseover", function(event, item) { - if (item != null && item.mark.marktype == config.tooltip.type) { - var row = item.datum; - if (item.datum != null && item.datum.a != null) { - row = item.datum.a; - } - - var tooltipDiv = document.getElementById(div.replace("#", "")+"-tooltip"); - var tooltipContent = ""; - - if (row[metadata.names[config.x]]!= null) { - var content; - - //Default tooltip content if tooltip content is not defined - if (config.tooltip.content == null) { - if (metadata.types[config.x]== "time") { - var dFormat = d3.time.format(config.dateFormat); - content = dFormat(new Date(parseInt(row[metadata.names[config.x]]))); - } else { - content = row[metadata.names[config.x]]; - } - - tooltipContent += ""+ metadata.names[config.x] +" : "+content+"
" ; - - if (row[metadata.names[config.y]] != null) { - tooltipContent += ""+ metadata.names[config.y] + " : "+row[metadata.names[config.y]]+"
" - } - - } else { - //check all specified column and add them as tooltip content - for (var i = 0; i < config.tooltip.content.length; i++) { - if (metadata.types[metadata.names.indexOf(config.tooltip.content[i])]=== "time") { - var dFormat = d3.time.format(config.dateFormat); - content = dFormat(new Date(parseInt(row[metadata.names[config.x]]))); - } else { - content = row[config.tooltip.content[i]]; - } - - if (config.tooltip.label != false) { - tooltipContent += ""+ config.tooltip.content[i] +" : "+content+"
" ; - } else { - tooltipContent += content+"
" ; - } - }; - - } - - - } - - - if (tooltipContent != "") { - tooltipDiv.innerHTML = tooltipContent; - tooltipDiv.style.padding = "5px"; - tooltipDiv.style.backgroundColor = config.tooltip.bgColor; - tooltipDiv.style.color = config.tooltip.textColor; - tooltipDiv.style.fontSize = config.tooltip.fontSize; - tooltipDiv.style.opacity = config.tooltip.opacity; - tooltipDiv.style.opacity = config.tooltip.opacity; - tooltipDiv.className = "chart-tooltip"; - } - - window.onmousemove = function (e) { - tooltipDiv.style.top = (e.clientY + 15) + 'px'; - tooltipDiv.style.left = (e.clientX + 10) + 'px'; - tooltipDiv.style.zIndex = 1000; - tooltipDiv.style.backgroundColor = config.tooltip.color; - tooltipDiv.style.position = "fixed"; - - if (tooltipDiv.offsetWidth + e.clientX - (cumulativeOffset(document.getElementById(div.replace("#", ""))).left + config.padding.left) > document.getElementById(div.replace("#", "")).offsetWidth) { - tooltipDiv.style.left = (e.clientX - tooltipDiv.offsetWidth) + 'px'; - } - - if (e.clientY - (cumulativeOffset(document.getElementById(div.replace("#", ""))).top + 500) > document.getElementById(div.replace("#", "")).offsetHeight) { - tooltipDiv.style.top = (e.clientY - 400) + 'px'; - } - - }; - } - }) - .on("mouseout", function(event, item) { - var tooltipDiv = document.getElementById(div.replace("#", "")+"-tooltip"); - tooltipDiv.style.padding = "0px 0px 0px 0px"; - tooltipDiv.innerHTML = ""; - }).update(); -} - - -function cumulativeOffset(element) { - var top = 0, left = 0; - do { - top += element.offsetTop || 0; - left += element.offsetLeft || 0; - element = element.offsetParent; - } while(element); - - return { - top: top, - left: left - }; -}; - -function getXYAxes(config, xAxesType, xScale, yAxesType, yScale) { - var xProp = {"ticks": { - "stroke": {"value": config.xAxisColor}, - "strokeWidth":{"value":config.xAxisStrokeSize} - }, - "labels": { - "fill": {"value": config.xAxisColor}, - "fontSize": {"value": config.xAxisFontSize} - }, - "title": { - "fontSize": {"value": config.xAxisTitleFontSize}, - "fill": {"value": config.xAxisTitleFontColor} - }, - "axis": { - "stroke": {"value": config.xAxisColor}, - "strokeWidth": {"value": config.xAxisSize} - }}; - var yProp = {"ticks": { - "stroke": {"value": config.yAxisColor}, - "strokeWidth":{"value":config.yAxisStrokeSize} - }, - "labels": { - "fill": {"value": config.yAxisColor}, - "fontSize": {"value": config.yAxisFontSize} - }, - "title": { - "fontSize": {"value": config.yAxisTitleFontSize}, - "fill": {"value": config.yAxisTitleFontColor} - }, - "axis": { - "stroke": {"value": config.yAxisColor}, - "strokeWidth": {"value": config.yAxisSize} - }}; - - if (config.xAxisAngle) { - xProp.labels.angle = {"value": 45}; - xProp.labels.align = {"value": "left"}; - xProp.labels.baseline = {"value": "middle"}; - } - - if (config.yAxisAngle) { - yProp.labels.angle = {"value": 45}; - yProp.labels.align = {"value": "left"}; - yProp.labels.baseline = {"value": "middle"}; - } - - var axes = [ - { - "type": xAxesType, - "scale": xScale, - "grid": config.grid, - "format" : config.xFormat, - "ticks" : config.xTicks, - "title": config.xTitle, - "properties": xProp - }, - { - "type": yAxesType, - "scale": yScale, - "grid": config.grid, - "format" : config.yFormat, - "ticks" : config.yTicks, - "title": config.yTitle, - "properties": yProp - } - ]; - - return axes; -} - -function getXYScales(config, metadata) { - var xScale = { - "name": "x", - "type": metadata.types[config.x], - "range": "width", - "zero": config.zero, - "domain": config.xScaleDomain - }; - - var yScale = { - "name": "y", - "type": metadata.types[config.y], - "range": "height", - "zero": config.zero, - "domain": config.yScaleDomain - }; - - if (config.type != "bar") { - xScale.padding = 1; - yScale.padding = 1; - } - - return [xScale, yScale]; -} - -function getRangeSignals(config, signals) { - signals.push({ - "name": "range_start", - "streams": [{ - "type": "mousedown", - "expr": "eventX()", - "scale": {"name": "x", "invert": true} - }] - }); - signals.push( { - "name": "range_end", - "streams": [{ - "type": "mousedown, [mousedown, window:mouseup] > window:mousemove", - "expr": "clamp(eventX(), 0, "+config.width+")", - "scale": {"name": "x", "invert": true} - }] - }); - return signals; -} - -function getRangeMark(config, marks) { - marks.push({ - "type": "rect", - "properties":{ - "enter":{ - "y": {"value": 0}, - "height": {"value":config.height}, - "fill": {"value": config.rangeColor}, - "fillOpacity": {"value":0.3} - }, - "update":{ - "x": {"scale": "x", "signal": "range_start"}, - "x2": {"scale": "x", "signal": "range_end"} - } - } - }); - - return marks; -} - -function getLegend(config) { - var legends = [ - { - "name": "legend", - "fill": "color", - "title": config.legendTitle, - "offset": config.legendOffset, - "properties": { - "symbols": { - "stroke": {"value": "transparent"} - }, - "title": { - "fill": {"value": config.legendTitleColor}, - "fontSize": {"value": config.legendTitleFontSize} - }, - "labels": { - "fill": {"value": config.legendTextColor}, - "fontSize": {"value": config.ledgendTextFontSize} - } - } - } - ]; - - return legends; -} - -function drawChart(div, obj, callbacks) { - var viewUpdateFunction = (function(chart) { - if(obj.config.tooltip.enabled){ - createTooltip(div); - obj.view = chart({el:div}).renderer(obj.config.renderer).update(); - bindTooltip(div,obj.view,obj.config,obj.metadata); - } else { - obj.view = chart({el:div}).renderer(obj.config.renderer).update(); - } - - if (callbacks != null) { - for (var i = 0; i 0){ - //More than 1 day - time = day +' day : '; - durationInMS = durationInMS - (day * 86400000); - } - var hour = Math.floor(durationInMS/3600000); - if (hour > 0){ - //More than 1 hour - time = time + hour + ' hour : '; - durationInMS = durationInMS - (hour * 3600000); - } - - var minutes = Math.floor(durationInMS/60000); - if (minutes > 0){ - //More than 1 minute - time = time + minutes + ' minutes : '; - durationInMS = durationInMS - (minutes * 60000); - } - - var seconds = Math.ceil(durationInMS/1000); - if (seconds > 0){ - //More than 1 minute - time = time + seconds + ' seconds : '; - } - time = time.slice(0, -2); - return time; - }; -}()); diff --git a/modules/distribution/src/analytics/jaggeryapps/portal/modules/oauth/token-handler-utils.js b/modules/distribution/src/analytics/jaggeryapps/portal/modules/oauth/token-handler-utils.js deleted file mode 100644 index c6a8aab5..00000000 --- a/modules/distribution/src/analytics/jaggeryapps/portal/modules/oauth/token-handler-utils.js +++ /dev/null @@ -1,598 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var utils = function () { - var log = new Log("/modules/oauth/token-handler-utils.js"); - - var configs = require('/configs/portal.js').config(); - var constants = require("/modules/constants.js"); - var carbon = require("carbon"); - - //noinspection JSUnresolvedVariable - var Base64 = Packages.org.apache.commons.codec.binary.Base64; - //noinspection JSUnresolvedVariable - var String = Packages.java.lang.String; - - var publicMethods = {}; - var privateMethods = {}; - - publicMethods["encode"] = function (payload) { - return String(Base64.encodeBase64(String(payload).getBytes())); - }; - - publicMethods["decode"] = function (payload) { - return String(Base64.decodeBase64(String(payload).getBytes())); - }; - - /** - * Check whether this application is oauth enable or not - * @returns boolean if oauth enable - */ - publicMethods["checkOAuthEnabled"] = function () { - if (constants.AUTHORIZATION_TYPE_OAUTH === configs["authorization"]["activeMethod"]) { - return true; - } - return false; - }; - - /** - * Set access token into xml http request header - * @param xhr xml http request - * @returns {*} xhr which has access token it's header - */ - publicMethods["setAccessToken"] = function (xhr, callback) { - var accessToken; - if (publicMethods.checkOAuthEnabled()) { - try { - accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"]; - xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BEARER_PREFIX + accessToken); - } catch (exception) { - log.error("Access token hasn't been set yet, " + exception); - } finally { - callback(xhr); - } - } - callback(xhr); - }; - - /** - * Get access token of current logged user - * @param callBack response with access token - */ - publicMethods["getAccessToken"] = function (callBack) { - var accessToken = null; - if (publicMethods.checkOAuthEnabled()) { - try { - accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"]; - } catch (exception) { - log.error("Access token hasn't been set yet, " + exception); - } finally { - callBack(accessToken); - } - } - callBack(accessToken); - }; - - /** - * Create error message which adhere to xml http response object - * @param statusCode response status code - * @param status response status - * @param responseText response message - * @returns {{statusCode: *, status: *, responseText: *}} - */ - publicMethods["createXHRObject"] = function (statusCode, status, responseText) { - return {"statusCode": statusCode, "status": status, "responseText": responseText}; - }; - - /** - * check whether user already logged to system before invoking any apis - * @param callBack - */ - publicMethods["isUserAuthorized"] = function (callBack) { - if (session.get("Loged") !== constants.LOGIN_MESSAGE) { - callBack(false); - } else { - callBack(true); - } - }; - - /** - * Get identity provider uir - * @returns {*} - */ - publicMethods["getIdPServerURL"] = function () { - return configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["tokenServiceURL"]; - }; - - /** - * Get an Access token pair based on client secret - * @param encodedClientKeys {{clientId:"", clientSecret:""}} - * @param scope eg: PRODUCTION - * @param idPServer identity provider url - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenWithClientSecretType"] = function (encodedClientKeys, scope, idPServer) { - var xhr = new XMLHttpRequest(); - var tokenEndpoint = idPServer; - xhr.open(constants.HTTP_POST, tokenEndpoint, false); - xhr.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, constants.APPLICATION_X_WWW_FOR_URLENCODED); - xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BASIC_PREFIX + encodedClientKeys); - xhr.send("grant_type=client_credentials&scope=" + scope); - var tokenPair = {}; - if (xhr.status == constants.HTTP_ACCEPTED) { - var data = parse(xhr.responseText); - tokenPair.refreshToken = data.refresh_token; - tokenPair.accessToken = data.access_token; - } else if (xhr.status == constants.HTTP_USER_NOT_AUTHENTICATED) { - log.error("Error in obtaining token with client secret grant type, You are not authenticated yet"); - return null; - } else { - log.error("Error in obtaining token with client secret grant type, This might be a problem with client meta " + - "data which required for client secret grant type"); - return null; - } - return tokenPair; - }; - - - /** - * This will create client id and client secret for a given application - * @param properties "callbackUrl": "", - * "clientName": "", - * "owner": "", - * "applicationType": "", - * "grantType": "", - * "saasApp" :"", - * "dynamicClientRegistrationEndPoint" : "" - * - * @returns {{clientId:*, clientSecret:*}} - */ - publicMethods["getDynamicClientAppCredentials"] = function (username) { - // setting up dynamic client application properties - var dcAppProperties = { - "applicationType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["appType"], - "clientName": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["clientName"], - "owner": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["owner"], - "tokenScope": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["tokenScope"], - "grantType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["grantType"], - "callbackUrl": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["callbackUrl"], - "saasApp" : configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["saasApp"] - }; - - var tenantDomain = carbon.server.tenantDomain({username: username}); - if (!tenantDomain) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials. Unable to obtain a valid tenant domain for provided username "+ - username +"- getDynamicClientAppCredentials(x)"); - return null; - } else { - var cachedTenantBasedClientAppCredentials = privateMethods. - getCachedTenantBasedClientAppCredentials(tenantDomain); - if (cachedTenantBasedClientAppCredentials) { - return cachedTenantBasedClientAppCredentials; - } else { - // calling dynamic client app registration service endpoint - var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"] - ["dynamicClientAppRegistrationServiceURL"]; - var requestPayload = dcAppProperties; - var token = publicMethods.encode(configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["appRegistration"]["owner"] + ":" + configs["authorization"]["methods"]["oauth"]["attributes"] - ["oauthProvider"]["appRegistration"]["password"]); - var xhr = new XMLHttpRequest(); - xhr.open("POST", requestURL, false); - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Authorization", "Basic "+ token); - xhr.send(stringify(requestPayload)); - var dynamicClientAppCredentials = {}; - if (xhr["status"] == 201 || xhr["status"] == 200 && xhr["responseText"]) { - var responsePayload = parse(xhr["responseText"]); - var clientId = responsePayload["client_id"]; - var clientSecret = responsePayload["client_secret"]; - if(typeof clientId == "undefined"){ - clientId = responsePayload["clientId"]; - } - if(typeof clientSecret == "undefined"){ - clientSecret = responsePayload["clientSecret"]; - } - dynamicClientAppCredentials["clientId"] = clientId; - dynamicClientAppCredentials["clientSecret"] = clientSecret; - privateMethods. - setCachedTenantBasedClientAppCredentials(tenantDomain, dynamicClientAppCredentials); - } else if (xhr["status"] == 400) { - log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + - "Bad request. Invalid data provided as dynamic client application properties."); - dynamicClientAppCredentials = null; - } else { - log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + - "Error in retrieving dynamic client credentials."); - dynamicClientAppCredentials = null; - } - // returning dynamic client credentials - return dynamicClientAppCredentials; - } - } - }; - - /** - * If gateway is enable, apiManagerClientAppRegistrationServiceURL is used to create oauth application - * @param username username of current logged user - * @returns {{clientId:*, clientSecret:*}} - */ - publicMethods["getTenantBasedClientAppCredentials"] = function (username) { - if (!username) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client app credentials. No username " + - "as input - getTenantBasedClientAppCredentials(x)"); - return null; - } else { - //noinspection JSUnresolvedFunction, JSUnresolvedVariable - var tenantDomain = carbon.server.tenantDomain({username: username}); - - if (!tenantDomain) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials. Unable to obtain a valid tenant domain for provided " + - "username - getTenantBasedClientAppCredentials(x, y)"); - return null; - } else { - var cachedTenantBasedClientAppCredentials = privateMethods. - getCachedTenantBasedClientAppCredentials(tenantDomain); - if (cachedTenantBasedClientAppCredentials) { - return cachedTenantBasedClientAppCredentials; - } else { - var adminUsername = configs["authorization"]["methods"]["oauth"]["attributes"]["adminUser"]; - var adminUserTenantId = configs["authorization"]["methods"]["oauth"]["attributes"] - ["adminUserTenantId"]; - //claims required for jwtAuthenticator. - var claims = {"http://wso2.org/claims/enduserTenantId": adminUserTenantId, - "http://wso2.org/claims/enduser": adminUsername}; - var jwtToken = publicMethods.getJwtToken(adminUsername, claims); - // register a tenant based client app at API Manager - var applicationName = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["appRegistration"]["clientName"] + "_" + tenantDomain; - var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["appRegistration"]["apiManagerClientAppRegistrationServiceURL"] + - "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; - var xhr = new XMLHttpRequest(); - xhr.open("POST", requestURL, false); - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken); - xhr.send(); - if ((xhr["status"] == 201 || xhr["status"] == 200) && xhr["responseText"]) { - var responsePayload = parse(xhr["responseText"]); - var tenantBasedClientAppCredentials = {}; - var clientId = responsePayload["client_id"]; - var clientSecret = responsePayload["client_secret"]; - if(typeof clientId == "undefined"){ - clientId = responsePayload["clientId"]; - } - if(typeof clientSecret == "undefined"){ - clientSecret = responsePayload["clientSecret"]; - } - tenantBasedClientAppCredentials["clientId"] = clientId; - tenantBasedClientAppCredentials["clientSecret"] = clientSecret; - privateMethods. - setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); - return tenantBasedClientAppCredentials; - } else { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials from API " + - "Manager - getTenantBasedClientAppCredentials(x, y)"); - return null; - } - } - } - } - }; - - /** - * Caching oauth application credentials - * @param tenantDomain tenant domain where application is been created - * @param clientAppCredentials {{clientId:*, clientSecret:*}} - */ - privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) { - var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]); - if (!cachedTenantBasedClientAppCredentialsMap) { - cachedTenantBasedClientAppCredentialsMap = {}; - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; - application.put(constants["CACHED_CREDENTIALS_PORTAL_APP"], cachedTenantBasedClientAppCredentialsMap); - } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; - } - }; - - /** - * Get oauth application credentials from cache - * @param tenantDomain tenant domain where application is been created - * @returns {{clientId:*, clientSecret:*}} - */ - privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) { - var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]); - if (!cachedTenantBasedClientAppCredentialsMap || - !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { - return null; - } else { - return cachedTenantBasedClientAppCredentialsMap[tenantDomain]; - } - }; - - /** - * Get access token and refresh token using password grant type - * @param username username of the logged user - * @param password password of the logged user - * @param encodedClientAppCredentials {{clientId:*, clientSecret:*}} - * @param scopes scopes list - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenPairAndScopesByPasswordGrantType"] = function (username, password - , encodedClientAppCredentials, scopes) { - if (!username || !password || !encodedClientAppCredentials || !scopes) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " + - "grant type. No username, password, encoded client app credentials or scopes are " + - "found - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)"); - return null; - } else { - // calling oauth provider token service endpoint - var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["tokenServiceURL"]; - var requestPayload = "grant_type=password&username=" + - username + "&password=" + password + "&scope=" + scopes; - - var xhr = new XMLHttpRequest(); - xhr.open("POST", requestURL, false); - xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials); - xhr.send(requestPayload); - - if (xhr["status"] == 200 && xhr["responseText"]) { - var responsePayload = parse(xhr["responseText"]); - var tokenData = {}; - tokenData["accessToken"] = responsePayload["access_token"]; - tokenData["refreshToken"] = responsePayload["refresh_token"]; - tokenData["scopes"] = responsePayload["scope"]; - return tokenData; - } else { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token " + - "by password grant type - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)"); - return null; - } - } - }; - - /** - * Get access token and refresh token using SAML grant type - * @param assertion - * @param encodedClientAppCredentials - * @param scopes - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenPairAndScopesByJWTGrantType"] = function (username, encodedClientAppCredentials, scopes) { - if (!username || !encodedClientAppCredentials || !scopes) { - log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by jwt " + - "grant type. No assertion, encoded client app credentials or scopes are " + - "found - getTokenPairAndScopesByJWTGrantType(x, y, z)"); - return null; - } else { - var JWTClientManagerServicePackagePath = - "org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService"; - //noinspection JSUnresolvedFunction, JSUnresolvedVariable - var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath); - //noinspection JSUnresolvedFunction - var jwtClient = JWTClientManagerService.getJWTClient(); - // returning access token by JWT grant type - var tokenInfo = jwtClient.getAccessToken(encodedClientAppCredentials, - username, scopes); - var tokenData = {}; - tokenData["accessToken"] = tokenInfo.getAccessToken(); - tokenData["refreshToken"] = tokenInfo.getRefreshToken(); - tokenData["scopes"] = tokenInfo.getScopes(); - return tokenData; - } - }; - - /** - * Get access token and refresh token using SAML grant type - * @param assertion - * @param encodedClientAppCredentials - * @param scopes - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenPairAndScopesBySAMLGrantType"] = function (assertion, encodedClientAppCredentials, scopes) { - if (!assertion || !encodedClientAppCredentials || !scopes) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " + - "grant type. No assertion, encoded client app credentials or scopes are " + - "found - getTokenPairAndScopesBySAMLGrantType(x, y, z)"); - return null; - } else { - - var assertionXML = publicMethods.decode(assertion); - /* - TODO: make assertion extraction with proper parsing. - Since Jaggery XML parser seem to add formatting which causes signature verification to fail. - */ - var assertionStartMarker = "**/conf/tomcat/carbon/WEB-INF/web.xml **/bin/wso2server.sh **/bin/wso2server.bat - - **/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handler-utils.js - - **/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handlers.js - @@ -518,35 +513,6 @@ */** - - - - ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/jaggeryapps/portal - - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal - - - **/* - - - **/configs/designer.json - **/jaggery.conf - - - - - - - src/core/jaggeryapps/portal/themes/analytics - - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/extensions/themes/analytics - - - **/* - - @@ -829,30 +795,6 @@ - - - ../p2-profile/analytics-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/jaggeryapps/portal - - - ${pom.artifactId}-${pom.version}/wso2/analytics/repository/deployment/server/jaggeryapps/portal - - - **/configs/designer.json - - - - - - src/analytics/jaggeryapps/portal/libs/ - - - ${pom.artifactId}-${pom.version}/wso2/analytics/repository/deployment/server/jaggeryapps/portal/analytics-wso2-2.0.0 - - - **/* - - - ../p2-profile/analytics-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/carbonapps/ @@ -1159,28 +1101,6 @@ src/core/conf/tomcat/webapp-classloading-environments.xml ${pom.artifactId}-${pom.version}/conf/tomcat - - src/core/jaggeryapps/portal/configs/designer.json - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/configs - - 755 - - - src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth - - 755 - - - src/core/jaggeryapps/portal/modules/oauth/token-handlers.js - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth - - 755 - - @@ -1537,20 +1457,6 @@ 755 - - src/core/jaggeryapps/portal/jaggery.conf - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/ - - 755 - - - - - - - - src/core/jaggeryapps/privacy-policies/jaggery.conf @@ -1560,45 +1466,6 @@ 755 - - - - - - - - - - - - - - - - - src/core/cloud/portal/common.css - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/css - - - - - - src/core/cloud/portal/portal.js - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/js - - - - - - src/core/cloud/portal/global-navigation.jag - - - ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/theme/templates - - - ../scripts/change-ip.sh @@ -1740,33 +1607,6 @@ - - - - src/analytics/jaggeryapps/portal/designer.json - - - ${pom.artifactId}-${pom.version}/wso2/analytics/repository/deployment/server/jaggeryapps/portal/configs/ - - true - 644 - - - src/analytics/jaggeryapps/portal/modules/oauth/token-handler-utils.js - - ${pom.artifactId}-${pom.version}/wso2/analytics/repository/deployment/server/jaggeryapps/portal/modules/oauth - - 755 - - - src/analytics/jaggeryapps/portal/modules/oauth/token-handlers.js - - ${pom.artifactId}-${pom.version}/wso2/analytics/repository/deployment/server/jaggeryapps/portal/modules/oauth - - 755 - - - src/analytics/resources/geodashboard/events.csv @@ -1783,14 +1623,6 @@ true 644 - - - src/analytics/jaggeryapps/portal/jaggery.conf - - ${pom.artifactId}-${pom.version}/wso2/analytics/repository/deployment/server/jaggeryapps/portal/ - - 755 - diff --git a/modules/distribution/src/core/cloud/portal/common.css b/modules/distribution/src/core/cloud/portal/common.css deleted file mode 100644 index 091a6501..00000000 --- a/modules/distribution/src/core/cloud/portal/common.css +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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. - */ - -.truncate { - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -/** - * Validation messages - */ -.required { - color: #e74c3c; -} - -.required-error { - background: #a94442; - border: 1px solid #a94442; - padding: 6px 12px; - color: #fff; -} - -/** - * Theme overrides - */ -.breadcrumb li .fw-home { - float: left; - padding-top: 2px; - margin-right: 5px; -} - -/** - * Auth menu - */ -.auth .hidden-xs { - line-height: 38px; -} - -.auth-xs { - color: #fff; -} - -.auth-xs ul { - list-style: none; - padding: 0; - margin: 0; - line-height: 28px; - background-color: #2a80b9; -} - -.auth-xs li { - color: #ccc; -} - -.auth-xs li a { - display: block; - color: #fff; -} - -.auth-xs li a:hover { - background-color: #499dd5; -} - -ul.dropdown-menu.more-actions-button { - list-style-type: none; - margin: 0; - padding: 0; - overflow: hidden; - width: 40px; - background: #F9F9F9; - border-bottom: 1px solid #EFEFEF; - min-width: 45px; - -} - -ul.dropdown-menu.more-actions-button > li { - height: 40px; - width: 40px; - border: 1px; -} - -ul.dropdown-menu.more-actions-button > li > button { - border-bottom: 1px solid #e4e4e4; - border-top: 1px solid darkred; -} - -.btn-group.open .dropdown-toggle { - -webkit-box-shadow: none; - box-shadow: none; - border: 0px; -} - -.btn-custom { - border-width: 1px; -} - - -.cloud-menu .popover { - border-radius: 0px; - width: 24em; - left: -21.1em !important; - max-width: 32em; - background-color: #006690 -} -.cloud-menu .popover-title,.navbar-header .popover-title { - background-color: #006690; - font-size: 16px; - border-bottom: none; - font-weight: 400; -} -.cloud-menu .popover.bottom>.arrow{ - margin-left:-2px; -} -.cloud-menu .popover.bottom>.arrow:after,.navbar-header .popover.bottom>.arrow:after{ - border-bottom-color: #006690; -} -.cloud-block { - float: left; - width: 8.2em; - height: 8.2em; - background-color: #fff; - margin: 0.5em 0em 0.5em 0.5em; - text-align: center; - vertical-align: middle; -} -.cloud-name { - font-size:14px; - margin-top: .5em; - font-weight: 400; -} -.cloud-menu-popover { - position: relative; - float: right; - padding: 0px 8px; - background-color: transparent; - background-image: none; - border: 1px solid transparent; - border-radius: 4px; - color: #fff; - cursor: pointer; -} -#cloud-menu-popover-xs { - color: #fff; - line-height:24px; - border: none; - margin-right: 15px!important; -} -.navbar-toggle{ - border:none; - border-radius: 0px; -} -.navbar-header .popover { - border-radius: 0px; - width: 21em; - max-width:32em; - background-color: #006690; -} -.navbar-header .popover .popover-content{ - padding:0px; -} -.cloud-menu .popover-content { - padding: 0px; -} -.cloud-actions { - background-color: #005578; - float: left; - position: absolute; - width: 100%; - left: 0px; - overflow:hidden; -} -.cloud-actions h3 { - font-size: 16px; - font-weight: 400; - padding-left: 14px; - margin-top: 10px; -} -.cloud-block-invert { - color: #fff; - float: left; - width: 8.2em; - height: 8.2em; - background-color: #1f1f1f; - margin: 0.5em 0em 0.5em 0.5em; - text-align: center; - cursor: pointer; -} - -.cloud-block-default { - color: #006690; - background-color: #fff; - cursor: pointer; -} -.cloud-actions a:hover { - color: #d7d5d5; - background-color: #3d3d3d; - text-decoration: none -} -.cloud-apps a { - text-decoration: none; - color: #006690 !important; - cursor: pointer -} -.cloud-apps a:hover { - text-decoration: none; - color: #006690; - background-color: #c5c5c5; -} -.cloud-apps .cloud-actions a { - color: #fff -} - -.add-padding-top-3x { - padding-top: 15px !important; -} - -.nav li a{ - color: #fff; -} - -.cloud-menu-content li a{ - color:inherit; -} - -html{ - height: 100%; -} - -body{ - height: calc(100% - 50px); -} \ No newline at end of file diff --git a/modules/distribution/src/core/cloud/portal/global-navigation.jag b/modules/distribution/src/core/cloud/portal/global-navigation.jag deleted file mode 100644 index 84e47f93..00000000 --- a/modules/distribution/src/core/cloud/portal/global-navigation.jag +++ /dev/null @@ -1,329 +0,0 @@ -<% -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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. - */ -%> -<% -var query = request.getQueryString(); -var dest = encodeURIComponent(originalURI + (query ? '?' + query : '')); -var configs = require('/configs/portal.js').config(); -var isCloud = configs.isCloud; -%> -
- - - -
-
Navigate to Cloud
- -
- - <% } else { %> -
- <% if (user) { %> - -
- -
- -
-
- <% } else { %> - - <%= i18n.localize("login.label")%> - - <% } %> -
- <% } %> - -
\ No newline at end of file diff --git a/modules/distribution/src/core/cloud/portal/portal.js b/modules/distribution/src/core/cloud/portal/portal.js deleted file mode 100644 index 3d03a903..00000000 --- a/modules/distribution/src/core/cloud/portal/portal.js +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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. - */ -$(function () { - - var dashboardsApi = ues.utils.tenantPrefix() + 'apis/dashboards'; - var dashboards = []; - var isStillLoading = false; - var nextStart = 0; - var hasMore = true; - - /** - * Page count. - * @const - */ - var PAGE_COUNT = 10; - - // Pre-compiling handlebar templates - var dashboardsListHbs = Handlebars.compile($("#ues-dashboards-list-hbs").html()); - var dashboardThumbnailHbs = Handlebars.compile($("#ues-dashboard-thumbnail-hbs").html()); - var dashboardConfirmHbs = Handlebars.compile($("#ues-dashboard-confirm-hbs").html()); - var dashboardsEmptyHbs = Handlebars.compile($("#ues-dashboards-empty-hbs").html()); - Handlebars.registerPartial('ues-dashboard-thumbnail-hbs', dashboardThumbnailHbs); - - /** - * Find the dashboard using dashboard id. - * @param id - * @return {object} - * @private - * */ - var findDashboard = function (id) { - var i; - var dashboard; - var length = dashboards.length; - for (i = 0; i < length; i++) { - dashboard = dashboards[i]; - if (dashboard.id === id) { - return dashboard; - } - } - }; - - /** - * Delete the selected dashboard - * @param el:-selected dashboard element - * @private - * */ - var deleteDashboard = function (el) { - var button = Ladda.create(el[0]); - button.start(); - var id = el.closest('.ues-dashboard').data('id'); - $.ajax({ - url: dashboardsApi + '/' + id, - method: 'DELETE', - async : false, - success: function () { - button.stop(); - location.reload(); - }, - error: function () { - button.stop(); - } - }); - }; - - /** - * Load the list of dashboards available. - * @private - * */ - var loadDashboards = function () { - isStillLoading = true; - - if (!hasMore) { - isStillLoading = false; - $('.ues-dashboard').each(function (i, obj) { - if ($(this).find('.ues-dashboard-share').length) { - $(this).addClass("shared"); - } - }); - return; - } - ues.store.assets('dashboard', { - start: nextStart, - count: PAGE_COUNT - }, function (err, data) { - var dashboardsEl = $('#ues-portal').find('.ues-dashboards'); - hasMore = data.length; - if (!hasMore && nextStart === 0) { - dashboardsEl.append(dashboardsEmptyHbs()); - return; - } - - nextStart += PAGE_COUNT; - dashboards = dashboards.concat(data); - dashboardsEl.append(dashboardsListHbs(data)); - - var win = $(window); - var doc = $(document); - isStillLoading = false; - if (doc.height() > win.height()) { - return; - } - - loadDashboards(); - - $(".disable").on('click', function (event) { - event.preventDefault(); - }); - }); - }; - - /** - * Initialize the UI functionality such as binding events. - * @private - * */ - var initUI = function () { - var portal = $('#ues-portal'); - portal.on('click', '.ues-dashboards .ues-dashboard-trash-handle', function (e) { - e.preventDefault(); - var thiz = $(this); - var dashboardEl = thiz.closest('.ues-dashboard'); - var id = dashboardEl.data('id'); - var dashboard = findDashboard(id); - dashboardEl.html(dashboardConfirmHbs(dashboard)); - }); - - portal.on('click', '.ues-dashboards .ues-dashboard-trash-confirm', function (e) { - e.preventDefault(); - deleteDashboard($(this)); - }); - - portal.on('click', '.ues-dashboards .ues-dashboard-trash-cancel', function (e) { - e.preventDefault(); - var thiz = $(this); - var dashboardEl = thiz.closest('.ues-dashboard'); - var id = dashboardEl.data('id'); - var dashboard = findDashboard(id); - dashboardEl.html(dashboardThumbnailHbs(dashboard)); - }); - - portal.on('click', '.ues-view:not(.disable)', function(e) { - e.preventDefault(); - window.open($(this).attr('href'), '_blank'); - }); - - $('#filter-dashboards a').on('click', function () { - $('#filter').html($(this).text()); - var filter = $(this).data('filter'); - - $('.ues-dashboard-container').each(function (i, obj) { - if (filter === "All") { - $(this).show(); - } else { - if ($(this).find('.ues-dashboard-share').length) { - filter === "Shared" ? $(this).show() : $(this).hide(); - } else { - filter === "Shared" ? $(this).hide() : $(this).show(); - } - } - }); - }); - - $(window).scroll(function () { - var win = $(window); - var doc = $(document); - if (win.scrollTop() + win.height() < doc.height() - 100) { - return; - } - - if (!isStillLoading) { - loadDashboards(); - } - }); - }; - - $(document).ready(function () { - if($('#cloud-menu-popover').length) { - $('#cloud-menu-popover i.fw-tiles').popover({ - html: true, - trigger:'click', - title: function() { - return $("#popover-head").html(); - }, - content: function() { - return $("#popover-content").html(); - } - }); - } - }); - initUI(); - loadDashboards(); -}); \ No newline at end of file diff --git a/modules/distribution/src/core/conf/identity/service-providers/portal.xml b/modules/distribution/src/core/conf/identity/service-providers/portal.xml deleted file mode 100644 index e6ada3a0..00000000 --- a/modules/distribution/src/core/conf/identity/service-providers/portal.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - 9 - portal - Carbon Dashboards Portal - - - - portal - samlsso - - - - - - - - - 1 - - - BasicAuthenticator - basicauth - true - - - true - true - - - true - true - - - - - - - - - true - - - - diff --git a/modules/distribution/src/core/conf/identity/sso-idp-config.xml b/modules/distribution/src/core/conf/identity/sso-idp-config.xml index 9e74221e..64cf71dc 100755 --- a/modules/distribution/src/core/conf/identity/sso-idp-config.xml +++ b/modules/distribution/src/core/conf/identity/sso-idp-config.xml @@ -84,37 +84,5 @@ carbonServer - - portal - - https://localhost:9443/portal/acs - - https://localhost:9443/portal/acs - true - true - true - - https://localhost:9443/oauth2/token - - - https://localhost:9443/oauth2/token - - - - analyticsportal - - https://localhost:9445/portal/acs - - https://localhost:9445/portal/acs - true - true - true - - https://localhost:9443/oauth2/token - - - https://localhost:9443/oauth2/token - - \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/portal/configs/designer.json b/modules/distribution/src/core/jaggeryapps/portal/configs/designer.json deleted file mode 100644 index a123514e..00000000 --- a/modules/distribution/src/core/jaggeryapps/portal/configs/designer.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "isCloud" : false, - "store": { - "types": ["fs"] - }, - "gadgetGeneration" :{ - "isCreateGadgetEnable": false, - "ignoreProviders": ["rt"] - }, - "authentication": { - "activeMethod": "sso", - "methods": { - "sso": { - "attributes": { - "issuer": "portal", - "identityProviderURL": "%https.host%/samlsso", - "responseSigningEnabled": true, - "validateAssertionValidityPeriod": true, - "validateAudienceRestriction": true, - "assertionSigningEnabled": true, - "acs": "%https.host%/portal/acs", - "identityAlias": "wso2carbon", - "defaultNameIDPolicy": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", - "useTenantKey": false, - "isPassive": false - } - }, - "basic": { - "attributes": {} - } - } - }, - "authorization": { - "activeMethod": "oauth", - "methods": { - "oauth": { - "attributes": { - "apimgt-gateway": true, - "oauthProvider": { - "appRegistration": { - "appType": "webapp", - "clientName": "portal", - "owner": "admin", - "password":"admin", - "dynamicClientAppRegistrationServiceURL": "https://localhost:9443/dynamic-client-web/register", - "apiManagerClientAppRegistrationServiceURL": "%https.host%/api-application-registration/register/tenants", - "grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer urn:ietf:params:oauth:grant-type:jwt-bearer", - "tokenScope": "admin", - "callbackUrl": "%https.host%/portal", - "saasApp":true, - "samlGrantTypeName":"urn:ietf:params:oauth:grant-type:saml2-bearer" - }, - "tokenServiceURL": "https://localhost:9443/oauth2/token" - }, - "adminUser":"admin@carbon.super", - "adminUserTenantId":"-1234", - "adminRole":"admin", - "scopes" : [ - "device:view" - ] - } - } - } - }, - "designers": [ - "Internal/everyone" - ], - "tenantPrefix": "/t", - "shareStore": false, - "theme": "basic", - "cacheTimeoutSeconds": "5", - "cacheSizeBytes": "1073741824", - "defaultDashboardRedirect": false, - "isCreateGadgetEnable": true, - "isSecureVaultEnabled" : false, - "assets": { - "gadget": { - "fileSizeLimit": 5 - }, - "layout": { - "fileSizeLimit": 1 - } - }, - "oauth": { - "username": "admin", - "password": "admin" - }, - "host": { - "hostname": "localhost", - "port": "", - "protocol": "" - }, - "queryParameters" : { - "passBetweenPages" : ["shared"] - } -} diff --git a/modules/distribution/src/core/jaggeryapps/portal/jaggery.conf b/modules/distribution/src/core/jaggeryapps/portal/jaggery.conf deleted file mode 100644 index 30af6585..00000000 --- a/modules/distribution/src/core/jaggeryapps/portal/jaggery.conf +++ /dev/null @@ -1,195 +0,0 @@ -{ - "initScripts": [ - "js/dashboard-deployer.js" - ], - "welcomeFiles": [ - "routers/tenant.jag" - ], - "errorPages": { - "500": "/controllers/error-pages/error500.html", - "404": "/controllers/error-pages/error404.html", - "401": "/controllers/error-pages/error401.html", - "405": "/controllers/error-pages/error405.html", - "403": "/controllers/error-pages/error403.html", - "400": "/controllers/error-pages/error400.html" - }, - "urlMappings": [ - { - "url": "/login-controller", - "path": "/routers/tenant.jag" - }, - { - "url": "/login", - "path": "/routers/tenant.jag" - }, - { - "url": "/logout", - "path": "/routers/tenant.jag" - }, - { - "url": "/t/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/apis/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/dashboards/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/gadget/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/layout/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/assets/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/create-dashboard", - "path": "/routers/tenant.jag" - }, - { - "url": "/dashboard-settings/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/select-layout", - "path": "/routers/tenant.jag" - }, - { - "url": "/create-gadget", - "path": "/routers/tenant.jag" - }, - { - "url": "/upload-gadget", - "path": "/routers/tenant.jag" - }, - { - "url": "/upload-layout", - "path": "/routers/tenant.jag" - }, - { - "url": "/geojson/world/*", - "path": "/templates/geojson/world.json" - }, - { - "url": "/geojson/europe/*", - "path": "/templates/geojson/europe.json" - }, - { - "url": "/geojson/usa/*", - "path": "/templates/geojson/usa.json" - }, - { - "url": "/geojson/countryInfo/*", - "path": "/templates/geojson/countryInfo.json" - }, - { - "url": "/geojson/usaInfo/*", - "path": "/templates/geojson/usaInfo.json" - }, - { - "url": "/acs", - "path": "/controllers/acs.jag" - }, - { - "url": "/banners/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/gadgets/*", - "path": "/routers/tenant.jag" - }, - { - "url": "/configs/designer.json", - "path": "/controllers/error-pages/error404.html" - } - ], - "listeners": [ - { - "class": "org.owasp.csrfguard.CsrfGuardServletContextListener" - }, - { - "class": "org.owasp.csrfguard.CsrfGuardHttpSessionListener" - } - ], - "servlets": [ - { - "name": "JavaScriptServlet", - "class": "org.owasp.csrfguard.servlet.JavaScriptServlet" - } - ], - "servletMappings": [ - { - "name": "JavaScriptServlet", - "url": "/csrf.js" - } - ], - "contextParams": [ - { - "name": "Owasp.CsrfGuard.Config", - "value": "repository/conf/security/Owasp.CsrfGuard.dashboard.properties" - } - ], - "filters": [ - { - "name": "ContentTypeBasedCachePreventionFilter", - "class": "org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter", - "params" : [ - {"name" : "patterns", "value" : "text/html\" ,application/json\" ,text/plain"}, - {"name" : "filterAction", "value" : "enforce"}, - {"name" : "httpHeaders", "value" : "Cache-Control: no-store, no-cache, must-revalidate, private"} - ] - }, - { - "name": "HttpHeaderSecurityFilter", - "class": "org.apache.catalina.filters.HttpHeaderSecurityFilter", - "params": [ - { - "name": "hstsEnabled", - "value": "false" - }, - { - "name": "antiClickJackingOption", - "value": "SAMEORIGIN" - } - ] - }, - { - "name": "TenantStoresFilter", - "class": "org.wso2.carbon.dashboard.store.filter.TenantStoreFilter" - }, - { - "name" : "CSRFGuard", - "class" : "org.owasp.csrfguard.CsrfGuardFilter" - } - ], - "filterMappings": [ - { - "name": "HttpHeaderSecurityFilter", - "url": "*" - }, - { - "name": "TenantStoresFilter", - "url": "/store/*" - }, - { - "name": "TenantStoresFilter", - "url": "/temp/*" - }, - { - "name" : "CSRFGuard", - "url" : "/*" - }, - { - "name":"ContentTypeBasedCachePreventionFilter", - "url":"*" - } - ] -} diff --git a/modules/distribution/src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js b/modules/distribution/src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js deleted file mode 100644 index c6a8aab5..00000000 --- a/modules/distribution/src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js +++ /dev/null @@ -1,598 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var utils = function () { - var log = new Log("/modules/oauth/token-handler-utils.js"); - - var configs = require('/configs/portal.js').config(); - var constants = require("/modules/constants.js"); - var carbon = require("carbon"); - - //noinspection JSUnresolvedVariable - var Base64 = Packages.org.apache.commons.codec.binary.Base64; - //noinspection JSUnresolvedVariable - var String = Packages.java.lang.String; - - var publicMethods = {}; - var privateMethods = {}; - - publicMethods["encode"] = function (payload) { - return String(Base64.encodeBase64(String(payload).getBytes())); - }; - - publicMethods["decode"] = function (payload) { - return String(Base64.decodeBase64(String(payload).getBytes())); - }; - - /** - * Check whether this application is oauth enable or not - * @returns boolean if oauth enable - */ - publicMethods["checkOAuthEnabled"] = function () { - if (constants.AUTHORIZATION_TYPE_OAUTH === configs["authorization"]["activeMethod"]) { - return true; - } - return false; - }; - - /** - * Set access token into xml http request header - * @param xhr xml http request - * @returns {*} xhr which has access token it's header - */ - publicMethods["setAccessToken"] = function (xhr, callback) { - var accessToken; - if (publicMethods.checkOAuthEnabled()) { - try { - accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"]; - xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BEARER_PREFIX + accessToken); - } catch (exception) { - log.error("Access token hasn't been set yet, " + exception); - } finally { - callback(xhr); - } - } - callback(xhr); - }; - - /** - * Get access token of current logged user - * @param callBack response with access token - */ - publicMethods["getAccessToken"] = function (callBack) { - var accessToken = null; - if (publicMethods.checkOAuthEnabled()) { - try { - accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"]; - } catch (exception) { - log.error("Access token hasn't been set yet, " + exception); - } finally { - callBack(accessToken); - } - } - callBack(accessToken); - }; - - /** - * Create error message which adhere to xml http response object - * @param statusCode response status code - * @param status response status - * @param responseText response message - * @returns {{statusCode: *, status: *, responseText: *}} - */ - publicMethods["createXHRObject"] = function (statusCode, status, responseText) { - return {"statusCode": statusCode, "status": status, "responseText": responseText}; - }; - - /** - * check whether user already logged to system before invoking any apis - * @param callBack - */ - publicMethods["isUserAuthorized"] = function (callBack) { - if (session.get("Loged") !== constants.LOGIN_MESSAGE) { - callBack(false); - } else { - callBack(true); - } - }; - - /** - * Get identity provider uir - * @returns {*} - */ - publicMethods["getIdPServerURL"] = function () { - return configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["tokenServiceURL"]; - }; - - /** - * Get an Access token pair based on client secret - * @param encodedClientKeys {{clientId:"", clientSecret:""}} - * @param scope eg: PRODUCTION - * @param idPServer identity provider url - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenWithClientSecretType"] = function (encodedClientKeys, scope, idPServer) { - var xhr = new XMLHttpRequest(); - var tokenEndpoint = idPServer; - xhr.open(constants.HTTP_POST, tokenEndpoint, false); - xhr.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, constants.APPLICATION_X_WWW_FOR_URLENCODED); - xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BASIC_PREFIX + encodedClientKeys); - xhr.send("grant_type=client_credentials&scope=" + scope); - var tokenPair = {}; - if (xhr.status == constants.HTTP_ACCEPTED) { - var data = parse(xhr.responseText); - tokenPair.refreshToken = data.refresh_token; - tokenPair.accessToken = data.access_token; - } else if (xhr.status == constants.HTTP_USER_NOT_AUTHENTICATED) { - log.error("Error in obtaining token with client secret grant type, You are not authenticated yet"); - return null; - } else { - log.error("Error in obtaining token with client secret grant type, This might be a problem with client meta " + - "data which required for client secret grant type"); - return null; - } - return tokenPair; - }; - - - /** - * This will create client id and client secret for a given application - * @param properties "callbackUrl": "", - * "clientName": "", - * "owner": "", - * "applicationType": "", - * "grantType": "", - * "saasApp" :"", - * "dynamicClientRegistrationEndPoint" : "" - * - * @returns {{clientId:*, clientSecret:*}} - */ - publicMethods["getDynamicClientAppCredentials"] = function (username) { - // setting up dynamic client application properties - var dcAppProperties = { - "applicationType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["appType"], - "clientName": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["clientName"], - "owner": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["owner"], - "tokenScope": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["tokenScope"], - "grantType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["grantType"], - "callbackUrl": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["callbackUrl"], - "saasApp" : configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["saasApp"] - }; - - var tenantDomain = carbon.server.tenantDomain({username: username}); - if (!tenantDomain) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials. Unable to obtain a valid tenant domain for provided username "+ - username +"- getDynamicClientAppCredentials(x)"); - return null; - } else { - var cachedTenantBasedClientAppCredentials = privateMethods. - getCachedTenantBasedClientAppCredentials(tenantDomain); - if (cachedTenantBasedClientAppCredentials) { - return cachedTenantBasedClientAppCredentials; - } else { - // calling dynamic client app registration service endpoint - var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"] - ["dynamicClientAppRegistrationServiceURL"]; - var requestPayload = dcAppProperties; - var token = publicMethods.encode(configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["appRegistration"]["owner"] + ":" + configs["authorization"]["methods"]["oauth"]["attributes"] - ["oauthProvider"]["appRegistration"]["password"]); - var xhr = new XMLHttpRequest(); - xhr.open("POST", requestURL, false); - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Authorization", "Basic "+ token); - xhr.send(stringify(requestPayload)); - var dynamicClientAppCredentials = {}; - if (xhr["status"] == 201 || xhr["status"] == 200 && xhr["responseText"]) { - var responsePayload = parse(xhr["responseText"]); - var clientId = responsePayload["client_id"]; - var clientSecret = responsePayload["client_secret"]; - if(typeof clientId == "undefined"){ - clientId = responsePayload["clientId"]; - } - if(typeof clientSecret == "undefined"){ - clientSecret = responsePayload["clientSecret"]; - } - dynamicClientAppCredentials["clientId"] = clientId; - dynamicClientAppCredentials["clientSecret"] = clientSecret; - privateMethods. - setCachedTenantBasedClientAppCredentials(tenantDomain, dynamicClientAppCredentials); - } else if (xhr["status"] == 400) { - log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + - "Bad request. Invalid data provided as dynamic client application properties."); - dynamicClientAppCredentials = null; - } else { - log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + - "Error in retrieving dynamic client credentials."); - dynamicClientAppCredentials = null; - } - // returning dynamic client credentials - return dynamicClientAppCredentials; - } - } - }; - - /** - * If gateway is enable, apiManagerClientAppRegistrationServiceURL is used to create oauth application - * @param username username of current logged user - * @returns {{clientId:*, clientSecret:*}} - */ - publicMethods["getTenantBasedClientAppCredentials"] = function (username) { - if (!username) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client app credentials. No username " + - "as input - getTenantBasedClientAppCredentials(x)"); - return null; - } else { - //noinspection JSUnresolvedFunction, JSUnresolvedVariable - var tenantDomain = carbon.server.tenantDomain({username: username}); - - if (!tenantDomain) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials. Unable to obtain a valid tenant domain for provided " + - "username - getTenantBasedClientAppCredentials(x, y)"); - return null; - } else { - var cachedTenantBasedClientAppCredentials = privateMethods. - getCachedTenantBasedClientAppCredentials(tenantDomain); - if (cachedTenantBasedClientAppCredentials) { - return cachedTenantBasedClientAppCredentials; - } else { - var adminUsername = configs["authorization"]["methods"]["oauth"]["attributes"]["adminUser"]; - var adminUserTenantId = configs["authorization"]["methods"]["oauth"]["attributes"] - ["adminUserTenantId"]; - //claims required for jwtAuthenticator. - var claims = {"http://wso2.org/claims/enduserTenantId": adminUserTenantId, - "http://wso2.org/claims/enduser": adminUsername}; - var jwtToken = publicMethods.getJwtToken(adminUsername, claims); - // register a tenant based client app at API Manager - var applicationName = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["appRegistration"]["clientName"] + "_" + tenantDomain; - var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["appRegistration"]["apiManagerClientAppRegistrationServiceURL"] + - "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; - var xhr = new XMLHttpRequest(); - xhr.open("POST", requestURL, false); - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken); - xhr.send(); - if ((xhr["status"] == 201 || xhr["status"] == 200) && xhr["responseText"]) { - var responsePayload = parse(xhr["responseText"]); - var tenantBasedClientAppCredentials = {}; - var clientId = responsePayload["client_id"]; - var clientSecret = responsePayload["client_secret"]; - if(typeof clientId == "undefined"){ - clientId = responsePayload["clientId"]; - } - if(typeof clientSecret == "undefined"){ - clientSecret = responsePayload["clientSecret"]; - } - tenantBasedClientAppCredentials["clientId"] = clientId; - tenantBasedClientAppCredentials["clientSecret"] = clientSecret; - privateMethods. - setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); - return tenantBasedClientAppCredentials; - } else { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials from API " + - "Manager - getTenantBasedClientAppCredentials(x, y)"); - return null; - } - } - } - } - }; - - /** - * Caching oauth application credentials - * @param tenantDomain tenant domain where application is been created - * @param clientAppCredentials {{clientId:*, clientSecret:*}} - */ - privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) { - var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]); - if (!cachedTenantBasedClientAppCredentialsMap) { - cachedTenantBasedClientAppCredentialsMap = {}; - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; - application.put(constants["CACHED_CREDENTIALS_PORTAL_APP"], cachedTenantBasedClientAppCredentialsMap); - } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; - } - }; - - /** - * Get oauth application credentials from cache - * @param tenantDomain tenant domain where application is been created - * @returns {{clientId:*, clientSecret:*}} - */ - privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) { - var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]); - if (!cachedTenantBasedClientAppCredentialsMap || - !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { - return null; - } else { - return cachedTenantBasedClientAppCredentialsMap[tenantDomain]; - } - }; - - /** - * Get access token and refresh token using password grant type - * @param username username of the logged user - * @param password password of the logged user - * @param encodedClientAppCredentials {{clientId:*, clientSecret:*}} - * @param scopes scopes list - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenPairAndScopesByPasswordGrantType"] = function (username, password - , encodedClientAppCredentials, scopes) { - if (!username || !password || !encodedClientAppCredentials || !scopes) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " + - "grant type. No username, password, encoded client app credentials or scopes are " + - "found - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)"); - return null; - } else { - // calling oauth provider token service endpoint - var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] - ["tokenServiceURL"]; - var requestPayload = "grant_type=password&username=" + - username + "&password=" + password + "&scope=" + scopes; - - var xhr = new XMLHttpRequest(); - xhr.open("POST", requestURL, false); - xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials); - xhr.send(requestPayload); - - if (xhr["status"] == 200 && xhr["responseText"]) { - var responsePayload = parse(xhr["responseText"]); - var tokenData = {}; - tokenData["accessToken"] = responsePayload["access_token"]; - tokenData["refreshToken"] = responsePayload["refresh_token"]; - tokenData["scopes"] = responsePayload["scope"]; - return tokenData; - } else { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token " + - "by password grant type - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)"); - return null; - } - } - }; - - /** - * Get access token and refresh token using SAML grant type - * @param assertion - * @param encodedClientAppCredentials - * @param scopes - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenPairAndScopesByJWTGrantType"] = function (username, encodedClientAppCredentials, scopes) { - if (!username || !encodedClientAppCredentials || !scopes) { - log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by jwt " + - "grant type. No assertion, encoded client app credentials or scopes are " + - "found - getTokenPairAndScopesByJWTGrantType(x, y, z)"); - return null; - } else { - var JWTClientManagerServicePackagePath = - "org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService"; - //noinspection JSUnresolvedFunction, JSUnresolvedVariable - var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath); - //noinspection JSUnresolvedFunction - var jwtClient = JWTClientManagerService.getJWTClient(); - // returning access token by JWT grant type - var tokenInfo = jwtClient.getAccessToken(encodedClientAppCredentials, - username, scopes); - var tokenData = {}; - tokenData["accessToken"] = tokenInfo.getAccessToken(); - tokenData["refreshToken"] = tokenInfo.getRefreshToken(); - tokenData["scopes"] = tokenInfo.getScopes(); - return tokenData; - } - }; - - /** - * Get access token and refresh token using SAML grant type - * @param assertion - * @param encodedClientAppCredentials - * @param scopes - * @returns {{accessToken: *, refreshToken: *}} - */ - publicMethods["getTokenPairAndScopesBySAMLGrantType"] = function (assertion, encodedClientAppCredentials, scopes) { - if (!assertion || !encodedClientAppCredentials || !scopes) { - log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " + - "grant type. No assertion, encoded client app credentials or scopes are " + - "found - getTokenPairAndScopesBySAMLGrantType(x, y, z)"); - return null; - } else { - - var assertionXML = publicMethods.decode(assertion); - /* - TODO: make assertion extraction with proper parsing. - Since Jaggery XML parser seem to add formatting which causes signature verification to fail. - */ - var assertionStartMarker = " h1 { - padding: 15px 15px 0 15px; - font-weight: 100; - text-transform: uppercase; - font-size: 18px; -} - -.dashboard .page-header .page-title > h1 > .icon { - font-size: 24px; - margin-top: -5px; - margin-right: 5px; -} - -.dashboard .page-header .navbar-header { - margin-right: 15px; - margin-left: 15px; - float: none; -} - -@media (min-width: 768px) { - .dashboard .page-header .navbar-collapse.collapse { - display: none !important; - } - .page-header .container-fluid { - padding: 0 15px; - } - .navbar-nav > li > a { - padding: 10px 0; - } -} - -.nav > li > a > .icon { - margin-right: 8px; -} - -.nav > li > a > .badge { - position: absolute; - top: 5px; - right: 5px; - background: #ff124a; -} - -.dashboard .page-header .auth { - margin-bottom: 0; - padding: 6px 0; -} - -.dashboard .page-content { - overflow: inherit; -} - -.dashboard .footer { - background: #0d1219; -} - -.dashboard .gadget-wrapper { - border: 1px dashed #e4e4e4; -} - -.dashboard .gadget .gadget-heading { - background: transparent; - border-bottom: none; - color: #29313e; -} - -.gadget .gadget-heading > .gadget-title { - font-size: 20px; -} - -.gadget .gadget-heading > .gadget-actions button { - border: none; -} - -.sidebar-wrapper hr { - border-top-color: #ebeced; -} - -.sidebar-toggle-button { - float: left; - height: 50px; - line-height: 50px; - font-size: 18px; - background: #438cad; - color: #ffffff; - margin-left: -15px; -} - -.sidebar-toggle-button > .icon { - line-height: 48px; -} - -.sidebar-nav { - background: #29313e; - color: #e3e5e6; -} - -.nav.pages { - text-transform: uppercase; -} - -.nav.pages > li { - line-height: 20px; -} - -.nav > li { - text-indent: 0; - line-height: 10px; -} - -.nav > li > a { - border-radius: 0; - color: #e3e5e6; - background: transparent; -} - -.collapse-nav-sub > li > a { - padding: 4px 10px; - font-size: 21px; -} - -.collapse-nav-sub > li > a > .icon { - margin: 0; -} - -.page-header .fw-inverse { - color: #29313e; -} - -.nav li:hover > a, -.nav li.open > a, -.nav li.open > a:focus, -.nav li.open > a:hover { - background: #1a2332; -} - -.nav > li > a:focus { - background: transparent; -} - -.nav.pages > li.active a { - background: #121822; - border-left: 5px solid #438cad; -} - -.navbar-collapse { - padding: 15px; - background: #1A2331; -} - -.navbar-collapse li:hover > a { - background: #29313E; -} - -.sidebar-nav .user { - text-align: center; - margin: 20px auto; -} - -.sidebar-nav .user > .user-image { - margin-bottom: 10px; -} - -.sidebar-nav .user > .user-image > .default .icon { - font-size: 25px; -} - -.sidebar-nav .user > .user-image > .default .icon .fw-inverse, -.sidebar-nav .user > .user-image > .default .icon .fa-inverse { - color: #29313e; -} - -.widget .gadget-wrapper { - border: none; -} - -.widget .ues-component-heading { - display: none !important; - height: 0; -} - -.widget .ues-component { - height: auto; -} - -.widget.form-control-widget { - height: 35px !important; -} - -.dropdown-menu.arrow.arrow-top-right:before { - right: 20px; -} - -.dropdown-menu.arrow:before, -.dropdown-menu.arrow.arrow-top-left:before { - top: -10px; - border-right: 10px solid transparent; - border-bottom: 10px solid #e4e4e4; - border-left: 10px solid transparent; -} - -.dropdown-menu.alerts { - min-width: 400px; - max-width: 100%; - line-height: 1.2; -} - -ul.sidebar-messages > li:first-child { - margin-top: 0; -} - -ul.sidebar-messages > li:last-child { - margin-bottom: 0; -} \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/VizGrammarSettings.js b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/VizGrammarSettings.js deleted file mode 100644 index e1b44c83..00000000 --- a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/VizGrammarSettings.js +++ /dev/null @@ -1,12 +0,0 @@ -var vizgSettings = { - colorScale: colorbrewer.RdYlBu[4].reverse(), - colors: { - green:"#5FCE9B", - blue:"#438CAD", - red:"#E87352", - yellow:"#EECA5A", - purple:"#B6688F", - grey:"434343", - brown:"#C59787" - } -} \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/colorbrewer.js b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/colorbrewer.js deleted file mode 100644 index 5266d212..00000000 --- a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/colorbrewer.js +++ /dev/null @@ -1,303 +0,0 @@ -// This product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/). -// JavaScript specs as packaged in the D3 library (d3js.org). Please see license at http://colorbrewer.org/export/LICENSE.txt -var colorbrewer = {YlGn: { -3: ["#f7fcb9","#addd8e","#31a354"], -4: ["#ffffcc","#c2e699","#78c679","#238443"], -5: ["#ffffcc","#c2e699","#78c679","#31a354","#006837"], -6: ["#ffffcc","#d9f0a3","#addd8e","#78c679","#31a354","#006837"], -7: ["#ffffcc","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"], -8: ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"], -9: ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"] -},YlGnBu: { -3: ["#edf8b1","#7fcdbb","#2c7fb8"], -4: ["#ffffcc","#a1dab4","#41b6c4","#225ea8"], -5: ["#ffffcc","#a1dab4","#41b6c4","#2c7fb8","#253494"], -6: ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#2c7fb8","#253494"], -7: ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"], -8: ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"], -9: ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"] -},GnBu: { -3: ["#e0f3db","#a8ddb5","#43a2ca"], -4: ["#f0f9e8","#bae4bc","#7bccc4","#2b8cbe"], -5: ["#f0f9e8","#bae4bc","#7bccc4","#43a2ca","#0868ac"], -6: ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#43a2ca","#0868ac"], -7: ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"], -8: ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"], -9: ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"] -},BuGn: { -3: ["#e5f5f9","#99d8c9","#2ca25f"], -4: ["#edf8fb","#b2e2e2","#66c2a4","#238b45"], -5: ["#edf8fb","#b2e2e2","#66c2a4","#2ca25f","#006d2c"], -6: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#2ca25f","#006d2c"], -7: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"], -8: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"], -9: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"] -},PuBuGn: { -3: ["#ece2f0","#a6bddb","#1c9099"], -4: ["#f6eff7","#bdc9e1","#67a9cf","#02818a"], -5: ["#f6eff7","#bdc9e1","#67a9cf","#1c9099","#016c59"], -6: ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#1c9099","#016c59"], -7: ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"], -8: ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"], -9: ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"] -},PuBu: { -3: ["#ece7f2","#a6bddb","#2b8cbe"], -4: ["#f1eef6","#bdc9e1","#74a9cf","#0570b0"], -5: ["#f1eef6","#bdc9e1","#74a9cf","#2b8cbe","#045a8d"], -6: ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#2b8cbe","#045a8d"], -7: ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"], -8: ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"], -9: ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"] -},BuPu: { -3: ["#e0ecf4","#9ebcda","#8856a7"], -4: ["#edf8fb","#b3cde3","#8c96c6","#88419d"], -5: ["#edf8fb","#b3cde3","#8c96c6","#8856a7","#810f7c"], -6: ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8856a7","#810f7c"], -7: ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"], -8: ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"], -9: ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"] -},RdPu: { -3: ["#fde0dd","#fa9fb5","#c51b8a"], -4: ["#feebe2","#fbb4b9","#f768a1","#ae017e"], -5: ["#feebe2","#fbb4b9","#f768a1","#c51b8a","#7a0177"], -6: ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#c51b8a","#7a0177"], -7: ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"], -8: ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"], -9: ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"] -},PuRd: { -3: ["#e7e1ef","#c994c7","#dd1c77"], -4: ["#f1eef6","#d7b5d8","#df65b0","#ce1256"], -5: ["#f1eef6","#d7b5d8","#df65b0","#dd1c77","#980043"], -6: ["#f1eef6","#d4b9da","#c994c7","#df65b0","#dd1c77","#980043"], -7: ["#f1eef6","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"], -8: ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"], -9: ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"] -},OrRd: { -3: ["#fee8c8","#fdbb84","#e34a33"], -4: ["#fef0d9","#fdcc8a","#fc8d59","#d7301f"], -5: ["#fef0d9","#fdcc8a","#fc8d59","#e34a33","#b30000"], -6: ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#e34a33","#b30000"], -7: ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"], -8: ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"], -9: ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"] -},YlOrRd: { -3: ["#ffeda0","#feb24c","#f03b20"], -4: ["#ffffb2","#fecc5c","#fd8d3c","#e31a1c"], -5: ["#ffffb2","#fecc5c","#fd8d3c","#f03b20","#bd0026"], -6: ["#ffffb2","#fed976","#feb24c","#fd8d3c","#f03b20","#bd0026"], -7: ["#ffffb2","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"], -8: ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"], -9: ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"] -},YlOrBr: { -3: ["#fff7bc","#fec44f","#d95f0e"], -4: ["#ffffd4","#fed98e","#fe9929","#cc4c02"], -5: ["#ffffd4","#fed98e","#fe9929","#d95f0e","#993404"], -6: ["#ffffd4","#fee391","#fec44f","#fe9929","#d95f0e","#993404"], -7: ["#ffffd4","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"], -8: ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"], -9: ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"] -},Purples: { -3: ["#efedf5","#bcbddc","#756bb1"], -4: ["#f2f0f7","#cbc9e2","#9e9ac8","#6a51a3"], -5: ["#f2f0f7","#cbc9e2","#9e9ac8","#756bb1","#54278f"], -6: ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#756bb1","#54278f"], -7: ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"], -8: ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"], -9: ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"] -},Blues: { -3: ["#deebf7","#9ecae1","#3182bd"], -4: ["#eff3ff","#bdd7e7","#6baed6","#2171b5"], -5: ["#eff3ff","#bdd7e7","#6baed6","#3182bd","#08519c"], -6: ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#3182bd","#08519c"], -7: ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"], -8: ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"], -9: ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"] -},Greens: { -3: ["#e5f5e0","#a1d99b","#31a354"], -4: ["#edf8e9","#bae4b3","#74c476","#238b45"], -5: ["#edf8e9","#bae4b3","#74c476","#31a354","#006d2c"], -6: ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#31a354","#006d2c"], -7: ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"], -8: ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"], -9: ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"] -},Oranges: { -3: ["#fee6ce","#fdae6b","#e6550d"], -4: ["#feedde","#fdbe85","#fd8d3c","#d94701"], -5: ["#feedde","#fdbe85","#fd8d3c","#e6550d","#a63603"], -6: ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#e6550d","#a63603"], -7: ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"], -8: ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"], -9: ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"] -},Reds: { -3: ["#fee0d2","#fc9272","#de2d26"], -4: ["#fee5d9","#fcae91","#fb6a4a","#cb181d"], -5: ["#fee5d9","#fcae91","#fb6a4a","#de2d26","#a50f15"], -6: ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#de2d26","#a50f15"], -7: ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"], -8: ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"], -9: ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"] -},Greys: { -3: ["#f0f0f0","#bdbdbd","#636363"], -4: ["#f7f7f7","#cccccc","#969696","#525252"], -5: ["#f7f7f7","#cccccc","#969696","#636363","#252525"], -6: ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#636363","#252525"], -7: ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"], -8: ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"], -9: ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"] -},PuOr: { -3: ["#f1a340","#f7f7f7","#998ec3"], -4: ["#e66101","#fdb863","#b2abd2","#5e3c99"], -5: ["#e66101","#fdb863","#f7f7f7","#b2abd2","#5e3c99"], -6: ["#b35806","#f1a340","#fee0b6","#d8daeb","#998ec3","#542788"], -7: ["#b35806","#f1a340","#fee0b6","#f7f7f7","#d8daeb","#998ec3","#542788"], -8: ["#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788"], -9: ["#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788"], -10: ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"], -11: ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"] -},BrBG: { -3: ["#d8b365","#f5f5f5","#5ab4ac"], -4: ["#a6611a","#dfc27d","#80cdc1","#018571"], -5: ["#a6611a","#dfc27d","#f5f5f5","#80cdc1","#018571"], -6: ["#8c510a","#d8b365","#f6e8c3","#c7eae5","#5ab4ac","#01665e"], -7: ["#8c510a","#d8b365","#f6e8c3","#f5f5f5","#c7eae5","#5ab4ac","#01665e"], -8: ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e"], -9: ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e"], -10: ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"], -11: ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"] -},PRGn: { -3: ["#af8dc3","#f7f7f7","#7fbf7b"], -4: ["#7b3294","#c2a5cf","#a6dba0","#008837"], -5: ["#7b3294","#c2a5cf","#f7f7f7","#a6dba0","#008837"], -6: ["#762a83","#af8dc3","#e7d4e8","#d9f0d3","#7fbf7b","#1b7837"], -7: ["#762a83","#af8dc3","#e7d4e8","#f7f7f7","#d9f0d3","#7fbf7b","#1b7837"], -8: ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837"], -9: ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837"], -10: ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"], -11: ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"] -},PiYG: { -3: ["#e9a3c9","#f7f7f7","#a1d76a"], -4: ["#d01c8b","#f1b6da","#b8e186","#4dac26"], -5: ["#d01c8b","#f1b6da","#f7f7f7","#b8e186","#4dac26"], -6: ["#c51b7d","#e9a3c9","#fde0ef","#e6f5d0","#a1d76a","#4d9221"], -7: ["#c51b7d","#e9a3c9","#fde0ef","#f7f7f7","#e6f5d0","#a1d76a","#4d9221"], -8: ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221"], -9: ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221"], -10: ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"], -11: ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"] -},RdBu: { -3: ["#ef8a62","#f7f7f7","#67a9cf"], -4: ["#ca0020","#f4a582","#92c5de","#0571b0"], -5: ["#ca0020","#f4a582","#f7f7f7","#92c5de","#0571b0"], -6: ["#b2182b","#ef8a62","#fddbc7","#d1e5f0","#67a9cf","#2166ac"], -7: ["#b2182b","#ef8a62","#fddbc7","#f7f7f7","#d1e5f0","#67a9cf","#2166ac"], -8: ["#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac"], -9: ["#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac"], -10: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"], -11: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"] -},RdGy: { -3: ["#ef8a62","#ffffff","#999999"], -4: ["#ca0020","#f4a582","#bababa","#404040"], -5: ["#ca0020","#f4a582","#ffffff","#bababa","#404040"], -6: ["#b2182b","#ef8a62","#fddbc7","#e0e0e0","#999999","#4d4d4d"], -7: ["#b2182b","#ef8a62","#fddbc7","#ffffff","#e0e0e0","#999999","#4d4d4d"], -8: ["#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d"], -9: ["#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d"], -10: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"], -11: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"] -},RdYlBu: { -3: ["#fc8d59","#ffffbf","#91bfdb"], -4: ["#d7191c","#fdae61","#abd9e9","#2c7bb6"], -5: ["#d7191c","#fdae61","#ffffbf","#abd9e9","#2c7bb6"], -6: ["#d73027","#fc8d59","#fee090","#e0f3f8","#91bfdb","#4575b4"], -7: ["#d73027","#fc8d59","#fee090","#ffffbf","#e0f3f8","#91bfdb","#4575b4"], -8: ["#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4"], -9: ["#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4"], -10: ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"], -11: ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"] -},Spectral: { -3: ["#fc8d59","#ffffbf","#99d594"], -4: ["#d7191c","#fdae61","#abdda4","#2b83ba"], -5: ["#d7191c","#fdae61","#ffffbf","#abdda4","#2b83ba"], -6: ["#d53e4f","#fc8d59","#fee08b","#e6f598","#99d594","#3288bd"], -7: ["#d53e4f","#fc8d59","#fee08b","#ffffbf","#e6f598","#99d594","#3288bd"], -8: ["#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd"], -9: ["#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd"], -10: ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"], -11: ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"] -},RdYlGn: { -3: ["#fc8d59","#ffffbf","#91cf60"], -4: ["#d7191c","#fdae61","#a6d96a","#1a9641"], -5: ["#d7191c","#fdae61","#ffffbf","#a6d96a","#1a9641"], -6: ["#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"], -7: ["#d73027","#fc8d59","#fee08b","#ffffbf","#d9ef8b","#91cf60","#1a9850"], -8: ["#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850"], -9: ["#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850"], -10: ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"], -11: ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"] -},Accent: { -3: ["#7fc97f","#beaed4","#fdc086"], -4: ["#7fc97f","#beaed4","#fdc086","#ffff99"], -5: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0"], -6: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f"], -7: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17"], -8: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"] -},Dark2: { -3: ["#1b9e77","#d95f02","#7570b3"], -4: ["#1b9e77","#d95f02","#7570b3","#e7298a"], -5: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e"], -6: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02"], -7: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d"], -8: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"] -},Paired: { -3: ["#a6cee3","#1f78b4","#b2df8a"], -4: ["#a6cee3","#1f78b4","#b2df8a","#33a02c"], -5: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99"], -6: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c"], -7: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f"], -8: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00"], -9: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6"], -10: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a"], -11: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99"], -12: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"] -},Pastel1: { -3: ["#fbb4ae","#b3cde3","#ccebc5"], -4: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4"], -5: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6"], -6: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc"], -7: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd"], -8: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec"], -9: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"] -},Pastel2: { -3: ["#b3e2cd","#fdcdac","#cbd5e8"], -4: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4"], -5: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9"], -6: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae"], -7: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc"], -8: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"] -},Set1: { -3: ["#e41a1c","#377eb8","#4daf4a"], -4: ["#e41a1c","#377eb8","#4daf4a","#984ea3"], -5: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"], -6: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33"], -7: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628"], -8: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf"], -9: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"] -},Set2: { -3: ["#66c2a5","#fc8d62","#8da0cb"], -4: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3"], -5: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854"], -6: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f"], -7: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494"], -8: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"] -},Set3: { -3: ["#8dd3c7","#ffffb3","#bebada"], -4: ["#8dd3c7","#ffffb3","#bebada","#fb8072"], -5: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3"], -6: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462"], -7: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69"], -8: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5"], -9: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9"], -10: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd"], -11: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5"], -12: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"] -}}; \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/templates/dashboard.jag b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/templates/dashboard.jag deleted file mode 100644 index be15e2cb..00000000 --- a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/templates/dashboard.jag +++ /dev/null @@ -1,447 +0,0 @@ - -<% - // i18n - var i18n = require("i18n"); - i18n.init(request, utils.getLocaleResourcePath()); - - // If the pageId is null, render the landing page - pageId = pageId || dashboard.landing; - - var usr = require('/modules/user.js'), - user = usr.current(), - isAnonView = request.getParameter('isAnonView'); - - // Get the anon view - if (!user) { - if (isAnonView) { - response.sendRedirect(request.getRequestURL()); - } - isAnonView = true; - } else { - isAnonView = JSON.parse(isAnonView); - - if((user.domain != urlDomain && urlDomain) || - (dashboard.isanon && !utils.allowed(user.roles, dashboard.permissions.editors) && !utils.allowed(user.roles, dashboard.permissions.viewers))) { - isAnonView = true; - } - } - - // Get the current page - var pages = dashboard.pages, - page; - pages.forEach(function(p) { - if (p.id == pageId) { - page = p; - } - }); -%> - - - - - - - <%= i18n.localize("dashboard.server.label")%> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- - - - -
- -
- -
- <%=renderEngine.getDashboardContent(pageId || dashboard.landing, isAnonView)%> -
-
-
- -
-
-
- - -
-
-

WSO2 Dashboard Server 2.0.0 | © Inc.

-
-
- - - - - - - - - - - - - - - - - - - - - <% include('/controllers/includes/common-scripts.jag'); %> - <% include('/controllers/includes/dashboard-scripts.jag'); %> - - - - - - - - - - - <% include('/controllers/includes/theme-dashboard-scripts.jag'); %> - - - - - - - - - - - - - - - diff --git a/modules/distribution/src/core/jaggeryapps/portal/uipublisher/websocketSubscriptionEndpoint.jag b/modules/distribution/src/core/jaggeryapps/portal/uipublisher/websocketSubscriptionEndpoint.jag deleted file mode 100644 index 3f8fa1d4..00000000 --- a/modules/distribution/src/core/jaggeryapps/portal/uipublisher/websocketSubscriptionEndpoint.jag +++ /dev/null @@ -1,52 +0,0 @@ -<% -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -var user = session.get('user'); -var streamName; -var streamVersion; -var log = new Log(); -var JaggeryWebSocketHelper = Packages.org.wso2.carbon.event.output.adapter.ui.JaggeryWebSocketHelper; - -webSocket.onopen = function () { - if (user == null) { - this.close(); - } -}; - -webSocket.ontext = function (data) { - log.info(data); - var dataObj = parse(data); - streamName = dataObj.streamName; - streamVersion = dataObj.streamVersion; - JaggeryWebSocketHelper.subscribeWebSocket(streamName, streamVersion, stringify(dataObj.filterProps), - user.username, session.getId(), user.tenantId, this); -}; - -webSocket.onclose = function () { - if (user != null && streamName != null && streamVersion != null) { //onclose may get invoked when an invalid user (user==null case) closes the connection. Hence this check is required. - JaggeryWebSocketHelper.unsubscribeWebsocket(streamName, streamVersion, session.getId(), user.tenantId); - } -}; - -webSocket.onerror = function () { - if (user != null) { - JaggeryWebSocketHelper.unsubscribeWebsocket(streamId.split(":")[0], streamId.split(":")[1], session.getId(), user.tenantId); - } -}; - -%> diff --git a/modules/distribution/src/core/samples/connectedcup-samples-deployer.xml b/modules/distribution/src/core/samples/connectedcup-samples-deployer.xml deleted file mode 100644 index 28f0dc98..00000000 --- a/modules/distribution/src/core/samples/connectedcup-samples-deployer.xml +++ /dev/null @@ -1,249 +0,0 @@ - - - - - org.wso2 - wso2 - 1 - - - - connectedcup - ../wso2/analytics/samples/connected-cup - - - 4.0.0 - org.wso2.iot.devicemgt-plugins - iot-devicetype-samples - 1.0.0 - pom - Install Connected Cup Device Types - IoT Core - http://wso2.org - - - - - org.wso2.maven - carbon-p2-plugin - 1.5.4 - - - 2-p2-repo-generation - package - - p2-repo-gen - - - file:\${basedir}/target/p2-repo - file:\${basedir}/target/p2-repo - true - true - - - org.coffeeking:org.coffeeking.connectedcup.backend.feature:\${org.coffeeking.version} - - - org.coffeeking:org.coffeeking.connectedcup.ui.feature:\${org.coffeeking.version} - - - - - - default-feature-install - package - - p2-profile-gen - - - default - file:\${basedir}/target/p2-repo - file:\${basedir}/target/p2-repo - \${basedir}/../wso2/components - false - - - - org.coffeeking.connectedcup.ui.feature.group - \${org.coffeeking.version} - - - org.coffeeking.connectedcup.backend.feature.group - \${org.coffeeking.version} - - - - - - manager-feature-install - package - - p2-profile-gen - - - device-manager - file:\${basedir}/target/p2-repo - file:\${basedir}/target/p2-repo - \${basedir}/../wso2/components - false - - - - org.coffeeking.connectedcup.ui.feature.group - \${org.coffeeking.version} - - - - - - backend-feature-install - package - - p2-profile-gen - - - device-backend - file:\${basedir}/target/p2-repo - file:\${basedir}/target/p2-repo - \${basedir}/../wso2/components - false - - - - org.coffeeking.connectedcup.backend.feature.group - \${org.coffeeking.version} - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.1 - - - default-feature-install - package - - - - - - - - - - - - - - - run - - - - - - - - - - wso2.releases - WSO2 internal Repository - http://maven.wso2.org/nexus/content/repositories/releases/ - - true - daily - ignore - - - - wso2.snapshots - Apache Snapshot Repository - http://maven.wso2.org/nexus/content/repositories/snapshots/ - - true - daily - - - false - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - - - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - wso2.releases - WSO2 internal Repository - http://maven.wso2.org/nexus/content/repositories/releases/ - - true - daily - ignore - - - - wso2.snapshots - WSO2 Snapshot Repository - http://maven.wso2.org/nexus/content/repositories/snapshots/ - - true - daily - - - false - - - - - ${carbon.device.mgt.plugin.version} - 1.0.0 - - \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/pom.xml b/modules/distribution/src/core/samples/connectedcup/component/agent/pom.xml deleted file mode 100644 index 8a225f88..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - - - device-mgt-iot-connectedcup - org.coffeeking - 1.0.0 - ../pom.xml - - 4.0.0 - org.coffeeking.connectedcup.agent - war - 1.0.0 - WSO2 IoTS(Device Types) - Connected Cup Agent Web app - http://maven.apache.org - - - - junit - junit - 3.8.1 - test - - - org.json - json - 20151123 - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - commons-logging - commons-logging - 1.1.1 - provided - - - org.eclipse.paho - org.eclipse.paho.client.mqttv3 - 1.0.2 - - - - - connected-cup-agent - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - - wso2.releases - WSO2 internal Repository - http://maven.wso2.org/nexus/content/repositories/releases/ - - true - daily - ignore - - - - wso2.snapshots - Apache Snapshot Repository - http://maven.wso2.org/nexus/content/repositories/snapshots/ - - true - daily - - - false - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - - - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - wso2.releases - WSO2 internal Repository - http://maven.wso2.org/nexus/content/repositories/releases/ - - true - daily - ignore - - - - wso2.snapshots - WSO2 Snapshot Repository - http://maven.wso2.org/nexus/content/repositories/snapshots/ - - true - daily - - - false - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/datasense/PushLevel.java b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/datasense/PushLevel.java deleted file mode 100644 index 7d3cc0af..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/datasense/PushLevel.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.agent.datasense; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.agent.transport.TransportHandlerException; -import org.coffeeking.agent.transport.mqtt.ConnectedCupMQttTransportHandler; -import org.json.JSONObject; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.StreamCorruptedException; - -public class PushLevel extends HttpServlet { - private static final Log log = LogFactory.getLog(PushLevel.class); - private ConnectedCupMQttTransportHandler connectedCupMQttTransportHandler; - - public PushLevel() { - connectedCupMQttTransportHandler = ConnectedCupMQttTransportHandler.getInstance(); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String deviceId = req.getParameter("deviceId"); - String tenantDomain = req.getParameter("tenantDomain"); - String deviceOwner = req.getParameter("deviceOwner"); - String payload = req.getParameter("payload"); - payload = " {\"event\": {\"metaData\": {\"owner\": \"" + deviceOwner + - "\", \"type\": \"coffeelevel\",\"deviceId\": " + - "\"" + deviceId + "\",\"timestamp\": " + System.currentTimeMillis() + - "},\"payloadData\": { \"coffeelevel\": " + Float.parseFloat(payload) + ", \"temperature\": 0} }}"; - String token = (String) req.getSession().getAttribute("token"); - if (!connectedCupMQttTransportHandler.isConnected()) { - connectedCupMQttTransportHandler.setToken(token); - connectedCupMQttTransportHandler.connect(); - } - try { - if (connectedCupMQttTransportHandler.isConnected()) { - connectedCupMQttTransportHandler.publishToConnectedCup(deviceOwner, deviceId, payload, tenantDomain, 0, - true); - } - } catch (TransportHandlerException e) { - log.error(e); - resp.sendError(500); - } - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/datasense/PushTemperature.java b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/datasense/PushTemperature.java deleted file mode 100644 index f4f33de4..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/datasense/PushTemperature.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.agent.datasense; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.agent.transport.TransportHandlerException; -import org.coffeeking.agent.transport.mqtt.ConnectedCupMQttTransportHandler; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -public class PushTemperature extends HttpServlet { - private static final Log log = LogFactory.getLog(PushTemperature.class); - private ConnectedCupMQttTransportHandler connectedCupMQttTransportHandler; - - public PushTemperature() { - connectedCupMQttTransportHandler = ConnectedCupMQttTransportHandler.getInstance(); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String deviceId = req.getParameter("deviceId"); - String tenantDomain = req.getParameter("tenantDomain"); - String payload = req.getParameter("payload"); - String deviceOwner = req.getParameter("deviceOwner"); - payload = " {\"event\": {\"metaData\": {\"owner\": \"" + deviceOwner + - "\", \"type\": \"temperature\",\"deviceId\": " + - "\"" + deviceId + "\",\"timestamp\": " + System.currentTimeMillis() + - "},\"payloadData\": { \"temperature\": " + Float.parseFloat(payload) + ", \"coffeelevel\": 0} }}"; - String token = (String) req.getSession().getAttribute("token"); - if (!connectedCupMQttTransportHandler.isConnected()) { - connectedCupMQttTransportHandler.setToken(token); - connectedCupMQttTransportHandler.connect(); - } - try { - if (connectedCupMQttTransportHandler.isConnected()) { - connectedCupMQttTransportHandler.publishToConnectedCup(deviceOwner, deviceId, payload, tenantDomain, 0, - true); - } - } catch (TransportHandlerException e) { - log.error(e); - resp.sendError(500); - } - } - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/TransportHandler.java b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/TransportHandler.java deleted file mode 100644 index c00b7f02..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/TransportHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.agent.transport; - -/** - * This interface consists of the core functionality related to the transport between any device and the server. The - * interface is an abstraction, regardless of the underlying protocol used for the transport. Implementation of this - * interface by any class that caters a specific protocol (ex: HTTP, XMPP, MQTT, CoAP) would ideally have methods - * specific to the protocol used for communication and thees methods that implement the logic related to the devices - * using the protocol. - * - * @param a message type specific to the protocol implemented - */ -public interface TransportHandler { - int DEFAULT_TIMEOUT_INTERVAL = 5000; // millis ~ 10 sec - - void connect(); - - boolean isConnected(); - - void processIncomingMessage() throws TransportHandlerException; - - void processIncomingMessage(T message) throws TransportHandlerException; - - void processIncomingMessage(T message, String... messageParams) throws TransportHandlerException; - - void publishDeviceData() throws TransportHandlerException; - - void publishDeviceData(T publishData) throws TransportHandlerException; - - void publishDeviceData(String... publishData) throws TransportHandlerException; - - void disconnect(); -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/TransportHandlerException.java b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/TransportHandlerException.java deleted file mode 100644 index ee21bacc..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/TransportHandlerException.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.agent.transport; - -public class TransportHandlerException extends Exception { - private static final long serialVersionUID = 2736466230451105440L; - - private String errorMessage; - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public TransportHandlerException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public TransportHandlerException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public TransportHandlerException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public TransportHandlerException() { - super(); - } - - public TransportHandlerException(Throwable cause) { - super(cause); - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/mqtt/ConnectedCupMQttTransportHandler.java b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/mqtt/ConnectedCupMQttTransportHandler.java deleted file mode 100644 index b6aac275..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/mqtt/ConnectedCupMQttTransportHandler.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.agent.transport.mqtt; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.agent.transport.TransportHandlerException; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.eclipse.paho.client.mqttv3.MqttMessage; - -import java.io.File; -import java.util.UUID; -import java.util.concurrent.ScheduledFuture; - -public class ConnectedCupMQttTransportHandler extends MQTTTransportHandler { - - private static Log log = LogFactory.getLog(ConnectedCupMQttTransportHandler.class); - - private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); - - private static final String DEVICE_TYPE = "connectedcup"; - - private static ConnectedCupMQttTransportHandler connectedCupMQttTransportHandler; - - private static String publishTopic = "%s/" + DEVICE_TYPE + "/%s"; - - protected ConnectedCupMQttTransportHandler() { - super(iotServerSubscriber, DEVICE_TYPE, "tcp://localhost:1886", ""); - } - - private ScheduledFuture dataPushServiceHandler; - - public ScheduledFuture getDataPushServiceHandler() { - return dataPushServiceHandler; - } - - public void setToken(String token) { - setUsernameAndPassword(token, ""); - } - - @Override - public void connect() { - Runnable connect = new Runnable() { - @Override - public void run() { - log.info("Trying to connect.."); - while (!isConnected()) { - try { - connectToQueue(); - } catch (TransportHandlerException e) { - log.warn("Connection to MQTT Broker at: " + - mqttBrokerEndPoint + " failed"); - - try { - Thread.sleep(timeoutInterval); - } catch (InterruptedException ex) { - log.error("MQTT-Subscriber: Thread Sleep Interrupt Exception"); - } - } - } - - log.info("Connected.."); - - } - }; - - Thread connectorThread = new Thread(connect); - connectorThread.start(); - - } - - @Override - public void processIncomingMessage(MqttMessage message, String... messageParams) { - } - - public void publishToConnectedCup(String deviceOwner , String deviceId, String payLoad, String tenantDomain, int qos, boolean retained) - throws TransportHandlerException{ - String topic = String.format(publishTopic, tenantDomain, deviceId); - publishToQueue(topic, payLoad, qos, retained); - } - - @Override - public void disconnect() { - Runnable stopConnection = new Runnable() { - public void run() { - while (isConnected()) { - try { - dataPushServiceHandler.cancel(true); - closeConnection(); - - } catch (MqttException e) { - if (log.isDebugEnabled()) { - log.warn("Unable to 'STOP' MQTT connection at broker at: " + - mqttBrokerEndPoint); - } - - try { - Thread.sleep(timeoutInterval); - } catch (InterruptedException e1) { - log.error("MQTT-Terminator: Thread Sleep Interrupt Exception"); - } - } - } - } - }; - - Thread terminatorThread = new Thread(stopConnection); - terminatorThread.start(); - } - - - @Override - public void publishDeviceData() throws TransportHandlerException { - - } - - @Override - public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException { - - } - - @Override - public void publishDeviceData(String... publishData) throws TransportHandlerException { - - } - - @Override - public void processIncomingMessage() { - - } - - @Override - public void processIncomingMessage(MqttMessage message) throws TransportHandlerException { - - } - - public static ConnectedCupMQttTransportHandler getInstance(){ - if(connectedCupMQttTransportHandler == null){ - connectedCupMQttTransportHandler = new ConnectedCupMQttTransportHandler(); - } - return connectedCupMQttTransportHandler; - } - -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/mqtt/MQTTTransportHandler.java b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/mqtt/MQTTTransportHandler.java deleted file mode 100644 index afb4c610..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/java/org/coffeeking/agent/transport/mqtt/MQTTTransportHandler.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.agent.transport.mqtt; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.agent.transport.TransportHandler; -import org.coffeeking.agent.transport.TransportHandlerException; -import org.eclipse.paho.client.mqttv3.*; -import java.io.File; -import java.nio.charset.StandardCharsets; - -/** - * This is an abstract class that implements the "TransportHandler" interface. The interface is an abstraction for - * the core functionality with regards to device-server communication regardless of the Transport protocol. This - * specific class contains the HTTP-Transport specific implementations. The class implements utility methods for the - * case of a HTTP communication. However, this "abstract class", even-though it implements the "TransportHandler" - * interface, does not contain the logic relevant to the interface methods. The specific functionality of the - * interface methods are intended to be implemented by the concrete class that extends this abstract class and - * utilizes the HTTP specific functionality (ideally a device API writer who would like to communicate to the device - * via HTTP Protocol). - *

- * This class contains the Device-Management specific implementation for all the MQTT functionality. This includes - * connecting to a MQTT Broker & subscribing to the appropriate MQTT-topic, action plan upon losing connection or - * successfully delivering a message to the broker and processing incoming messages. Makes use of the 'Paho-MQTT' - * library provided by Eclipse Org. - */ -public abstract class MQTTTransportHandler - implements MqttCallback, TransportHandler { - private static final Log log = LogFactory.getLog(MQTTTransportHandler.class); - - public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; - - private MqttClient client; - private String clientId; - private MqttConnectOptions options; - private String clientWillTopic; - - protected String mqttBrokerEndPoint; - protected int timeoutInterval; - protected String subscribeTopic; - - /** - * Constructor for the MQTTTransportHandler which takes in the owner, type of the device - * and the MQTT Broker URL and the topic to subscribe. - * - * @param deviceOwner the owner of the device. - * @param deviceType the CDMF Device-Type of the device. - * @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint. - * @param subscribeTopic the MQTT topic to which the client is to be subscribed - */ - protected MQTTTransportHandler(String deviceOwner, String deviceType, - String mqttBrokerEndPoint, - String subscribeTopic) { - this.clientId = deviceOwner + ":" + deviceType; - this.subscribeTopic = subscribeTopic; - this.clientWillTopic = deviceType + File.separator + "disconnection"; - this.mqttBrokerEndPoint = mqttBrokerEndPoint; - this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL; - this.initSubscriber(); - } - - /** - * Constructor for the MQTTTransportHandler which takes in the owner, type of the device - * and the MQTT Broker URL and the topic to subscribe. Additionally this constructor takes in - * the reconnection-time interval between successive attempts to connect to the broker. - * - * @param deviceOwner the owner of the device. - * @param deviceType the CDMF Device-Type of the device. - * @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint. - * @param subscribeTopic the MQTT topic to which the client is to be subscribed - * @param intervalInMillis the time interval in MILLI-SECONDS between successive - * attempts to connect to the broker. - */ - protected MQTTTransportHandler(String deviceOwner, String deviceType, - String mqttBrokerEndPoint, String subscribeTopic, - int intervalInMillis) { - this.clientId = deviceOwner + ":" + deviceType; - this.subscribeTopic = subscribeTopic; - //TODO:: Use constant strings - this.clientWillTopic = deviceType + File.separator + "disconnection"; - this.mqttBrokerEndPoint = mqttBrokerEndPoint; - this.timeoutInterval = intervalInMillis; - this.initSubscriber(); - } - - public void setUsernameAndPassword (String username, String password) { - options.setUserName(username); - options.setPassword(password.toCharArray()); - } - - public void setTimeoutInterval(int timeoutInterval) { - this.timeoutInterval = timeoutInterval; - } - - /** - * Initializes the MQTT-Client. Creates a client using the given MQTT-broker endpoint and the - * clientId (which is constructed by a concatenation of [deviceOwner]:[deviceType]). Also sets - * the client's options parameter with the clientWillTopic (in-case of connection failure) and - * other info. Also sets the call-back this current class. - */ - private void initSubscriber() { - try { - client = new MqttClient(this.mqttBrokerEndPoint, clientId, null); - //TODO:: Need to check for debug - log.info("MQTT subscriber was created with ClientID : " + clientId); - } catch (MqttException ex) { - //TODO:: Remove unnecessary formatting and print exception - String errorMsg = "MQTT Client Error\n" + "\tReason: " + ex.getReasonCode() + - "\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " + - ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() + - "\n\tException: " + ex; - log.error(errorMsg); - //TODO:: Throw the error out - } - - options = new MqttConnectOptions(); - options.setCleanSession(true); - //TODO:: Use constant strings - options.setWill(clientWillTopic, "Connection-Lost".getBytes(StandardCharsets.UTF_8), 2, - true); - client.setCallback(this); - } - - /** - * Checks whether the connection to the MQTT-Broker persists. - * - * @return true if the client is connected to the MQTT-Broker, else false. - */ - @Override - public boolean isConnected() { - return client.isConnected(); - } - - - /** - * Connects to the MQTT-Broker and if successfully established connection. - * - * @throws TransportHandlerException in the event of 'Connecting to' the MQTT broker fails. - */ - protected void connectToQueue() throws TransportHandlerException { - try { - client.connect(options); - - if (log.isDebugEnabled()) { - log.debug("Subscriber connected to queue at: " + this.mqttBrokerEndPoint); - } - } catch (MqttSecurityException ex) { - String errorMsg = "MQTT Security Exception when connecting to queue\n" + "\tReason: " + - " " + - ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() + - "\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " + - ex.getCause() + "\n\tException: " + ex; - //TODO:: Compulsory log of errors and remove formatted error - if (log.isDebugEnabled()) { - log.debug(errorMsg); - } - throw new TransportHandlerException(errorMsg, ex); - - } catch (MqttException ex) { - //TODO:: Compulsory log of errors and remove formatted error - String errorMsg = "MQTT Exception when connecting to queue\n" + "\tReason: " + - ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() + - "\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " + - ex.getCause() + "\n\tException: " + ex; - if (log.isDebugEnabled()) { - log.debug(errorMsg); - } - throw new TransportHandlerException(errorMsg, ex); - } - } - - /** - * Subscribes to the MQTT-Topic specific to this MQTT Client. (The MQTT-Topic specific to the - * device is taken in as a constructor parameter of this class) . - * - * @throws TransportHandlerException in the event of 'Subscribing to' the MQTT broker - * fails. - */ - protected void subscribeToQueue() throws TransportHandlerException { - try { - //TODO:: QoS Level take it from a variable - client.subscribe(subscribeTopic, 0); - if (log.isDebugEnabled()) { - log.debug("Subscriber '" + clientId + "' subscribed to topic: " + subscribeTopic); - } - } catch (MqttException ex) { - //TODO:: Compulsory log of errors and remove formatted error - String errorMsg = "MQTT Exception when trying to subscribe to topic: " + - subscribeTopic + "\n\tReason: " + ex.getReasonCode() + - "\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " + - ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() + - "\n\tException: " + ex; - if (log.isDebugEnabled()) { - log.debug(errorMsg); - } - - throw new TransportHandlerException(errorMsg, ex); - } - } - - - /** - * This method is used to publish reply-messages for the control signals received. - * Invocation of this method calls its overloaded-method with a QoS equal to that of the - * default value. - * - * @param topic the topic to which the reply message is to be published. - * @param payLoad the reply-message (payload) of the MQTT publish action. - */ - protected void publishToQueue(String topic, String payLoad) - throws TransportHandlerException { - publishToQueue(topic, payLoad, DEFAULT_MQTT_QUALITY_OF_SERVICE, false); - } - - /** - * This is an overloaded method that publishes MQTT reply-messages for control signals - * received form the IoT-Server. - * - * @param topic the topic to which the reply message is to be published - * @param payLoad the reply-message (payload) of the MQTT publish action. - * @param qos the Quality-of-Service of the current publish action. - * Could be 0(At-most once), 1(At-least once) or 2(Exactly once) - */ - protected void publishToQueue(String topic, String payLoad, int qos, boolean retained) - throws TransportHandlerException { - try { - client.publish(topic, payLoad.getBytes(StandardCharsets.UTF_8), qos, retained); - if (log.isDebugEnabled()) { - log.debug("Message: " + payLoad + " to MQTT topic [" + topic + - "] published successfully"); - } - } catch (MqttException ex) { - String errorMsg = - "MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() + "\n\tMessage: " + - ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() + - "\n\tCause: " + ex.getCause() + "\n\tException: " + ex; - log.info(errorMsg); - throw new TransportHandlerException(errorMsg, ex); - } - } - - - protected void publishToQueue(String topic, MqttMessage message) - throws TransportHandlerException { - try { - client.publish(topic, message); - if (log.isDebugEnabled()) { - log.debug("Message: " + message.toString() + " to MQTT topic [" + topic + - "] published successfully"); - } - } catch (MqttException ex) { - //TODO:: Compulsory log of errors and remove formatted error - String errorMsg = - "MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() + "\n\tMessage: " + - ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() + - "\n\tCause: " + ex.getCause() + "\n\tException: " + ex; - log.info(errorMsg); - throw new TransportHandlerException(errorMsg, ex); - } - } - - - /** - * Callback method which is triggered once the MQTT client losers its connection to the broker. - * Spawns a new thread that executes necessary actions to try and reconnect to the endpoint. - * - * @param throwable a Throwable Object containing the details as to why the failure occurred. - */ - @Override - public void connectionLost(Throwable throwable) { - if (log.isDebugEnabled()) { - log.warn("Lost Connection for client: " + this.clientId + " to " + this.mqttBrokerEndPoint + "." + - "\nThis was due to - " + throwable.getMessage()); - } - - Thread reconnectThread = new Thread() { - public void run() { - connect(); - } - }; - reconnectThread.setDaemon(true); - reconnectThread.start(); - } - - /** - * Callback method which is triggered upon receiving a MQTT Message from the broker. Spawns a - * new thread that executes any actions to be taken with the received message. - * - * @param topic the MQTT-Topic to which the received message was published to and the - * client was subscribed to. - * @param mqttMessage the actual MQTT-Message that was received from the broker. - */ - @Override - public void messageArrived(final String topic, final MqttMessage mqttMessage) { - if (log.isDebugEnabled()) { - log.debug("Got an MQTT message '" + mqttMessage.toString() + "' for topic '" + topic + "'."); - } - - Thread messageProcessorThread = new Thread() { - public void run() { - try { - processIncomingMessage(mqttMessage, topic); - } catch (TransportHandlerException e) { - log.error("An error occurred when trying to process received MQTT message [" + mqttMessage + "] " + - "for topic [" + topic + "].", e); - } - } - }; - messageProcessorThread.setDaemon(true); - messageProcessorThread.start(); - } - - /** - * Callback method which gets triggered upon successful completion of a message delivery to - * the broker. - * - * @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the - * specific message delivery. - */ - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - String topic = iMqttDeliveryToken.getTopics()[0]; - String client = iMqttDeliveryToken.getClient().getClientId(); - - try { - if (iMqttDeliveryToken.isComplete()) { - if (log.isDebugEnabled()) { - if (iMqttDeliveryToken.getMessage() != null) { - String message = iMqttDeliveryToken.getMessage().toString(); - log.debug("Message to client [" + client + "] under topic (" + topic + - ") was delivered successfully with the delivery message: '" + message + "'"); - } else { - log.debug("Message to client [" + client + "] under topic (" + topic + - ") was delivered successfully."); - } - } - } else { - log.warn("FAILED: Delivery of MQTT message to [" + client + "] under topic [" + topic + "] failed."); - } - } catch (MqttException e) { - //TODO:: Throw errors - log.error("Error occurred whilst trying to read the message from the MQTT delivery token."); - } - } - - /** - * Closes the connection to the MQTT Broker. - */ - public void closeConnection() throws MqttException { - if (client != null && isConnected()) { - client.disconnect(); - } - } -} - diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index ab7e3b42..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,27 +0,0 @@ - - ConnectedCup-Webapp - - - PushTemperature - org.coffeeking.agent.datasense.PushTemperature - 1 - - - PushTemperature - /push_temperature - - - - PushLevel - org.coffeeking.agent.datasense.PushLevel - 1 - - - PushLevel - /push_level - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/css/coffee.css b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/css/coffee.css deleted file mode 100644 index 29cb7bfd..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/css/coffee.css +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -input[type=range][orient=vertical] -{ - writing-mode: bt-lr; /* IE */ - -webkit-appearance: slider-vertical; /* WebKit */ - width: 8px; - height: 175px; - padding: 0 5px; -} - -h1 { - padding-top: 10px; - text-align: center; -} - -.left-pane{ - float: left; - width: 30%; - text-align: center; - min-width: 325px; -} -.right-pane{ - float: right; - background-color: rgba(204, 204, 204, 0.61); - width: 70%; -} -.coffee-wrapper{ - margin: 10% 0 5% 10%; - text-align: center; -} -.coffee-top{ - position: absolute; - bottom: 10px; - height: 30px; - width: 100%; - z-index: 99; - background-color: aquamarine; -} -.coffee-bottom{ - position: absolute; - bottom: 0px; - height: 10px; - width: 100%; - z-index: 98; - background-color: aqua; -} - -.handle { - position: absolute; - height: 200px; - width: 97px; - top: 39px; - left: -111px; - border-top-left-radius: 75px 100px; - border-bottom-left-radius: 75px 100px; - border-top-right-radius: 50% 20px; - border-bottom-right-radius: 50% 20px; - background: linear-gradient(to left, rgba(0, 0, 0, 0.01) 0%, rgba(0, 0, 0, 0.01) 100%); - background-color: rgba(255, 255, 255, 0.28); - border: 1px solid rgba(255, 255, 255, 0.25); -} -.handle:after { - content: ""; - position: absolute; - height: 167px; - width: 76px; - top: 15px; - right: 0; - border-top-left-radius: 45px 70px; - border-bottom-left-radius: 45px 70px; - border-top-right-radius: 45px 35px; - border-bottom-right-radius: 45px 35px; - background: rgba(204, 204, 204, 0.3); -} - -:before, :after { - content: ''; - display: block; - position: absolute; -} - -html, body { - height: 100%; -} - -.coffee { - display: inline-block; - position: relative; - width: 300px; - margin: 0 20px 50px 0; -} - -.coffee:after { - height: 14px; - width: 300px; - border-radius: 46px/10px; - box-shadow: 0px 1px 4px -2px rgba(0, 0, 0, 0.2), 0px 2px 10px -3px rgba(0, 0, 0, 0.1); - bottom: -7.6px; - z-index: 0; -} - -.coffee:before { - height: 14px; - width: 300px; - border-radius: 46px/10px; - box-shadow: 0px 2px 10px -2px rgba(0, 204, 255, 0.3), 0px 2px 15px -2px rgba(0, 204, 255, 0.4); - bottom: -7.6px; - z-index: 0; -} - -.coffee_main { - height: 300px; - position: relative; - width: 298px; - background: none; - border: 1px solid rgba(255, 255, 255, 0.5); - border-top: none; - border-bottom: none; -} - -.coffee_main:after, .coffee_main:before { - height: 12px; - width: 296px; - border-radius: 46px/10px; - border: 2px solid rgba(255, 255, 255, 0.5); - border-bottom: 2px solid rgba(255, 255, 255, 0.7); - border-top: 1px solid rgba(255, 255, 255, 0.3); - left: -1px; -} - -.coffee_main:after { - top: -7px; - box-shadow: 0px 0px 6px rgba(255, 255, 255, 0.6) inset, 0px 3px 3px -1px rgba(255, 255, 255, 0.4), 0px 0px 3px rgba(0, 0, 0, 0.05) inset, 0px 0px 6px rgba(255, 255, 255, 0.7) inset, 0px 0px 3px rgba(0, 0, 0, 0.15) inset; -} - -.coffee_main:before { - top: 294px; - box-shadow: 0px 0px 6px rgba(255, 255, 255, 0.7) inset, 0px 0px 3px rgba(0, 0, 0, 0.15) inset; -} - -.coffee_mouth { - height: 52px; - width: 44px; - margin: 0px auto; - position: relative; - background: none; - border: 1px solid rgba(0, 0, 0, 0.04); - border-top: none; - border-bottom: none; - background: linear-gradient(to right, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 5%, rgba(255, 255, 255, 0) 95%, rgba(255, 255, 255, 0.3)); - box-shadow: 0px 0px 6px rgba(255, 255, 255, 0.3); -} - -.coffee_mouth:after { - height: 6px; - width: 44px; - border-radius: 25px/6px; - border: 1px solid rgba(255, 255, 255, 0.4); - left: -1px; - top: -4px; - z-index: 1; - box-shadow: 0px 0px 3px rgba(255, 255, 255, 0.3); -} - -.coffee_inner { - height: 295px; - width: 92%; - margin: 0px auto; - border-radius: 10px 10px 20px 20px/10px; - border: 1px solid rgba(0, 0, 0, 0.01); - border-top: 1px solid rgba(255, 255, 255, 0.3); - border-bottom-width: 0.5px; - position: relative; - box-shadow: 0px 0px 2px rgba(255, 255, 255, 0.5) inset, 0px 0px 8px rgba(255, 255, 255, 0.6) inset, 0px 0px 5px rgba(255, 255, 255, 0.5); - position: relative; - top: 1px; -} - -.coffee_inner:before { - border-radius: 40px/4px; - top: 140px; - width: 90%; - left: 3px; - height: 9px; -} - -.coffee_top .highlight { - display: block; - height: 30px; - width: 20px; - position: absolute; - left: 5px; - top: 5px; - transform: skew(0deg, 5deg); - background: linear-gradient(to right, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.6) 4%, rgba(255, 255, 255, 0.2) 98%, rgba(255, 255, 255, 0)); -} - -.coffee_top .highlight:after { - height: 30px; - width: 2px; - left: -3px; - top: -1px; - transform: skew(0deg, 5deg); - background: rgba(255, 255, 255, 0.3); -} - -.coffee_main .highlight { - display: block; - height: 301px; - width: 25px; - position: absolute; - left: 10px; - top: 6px; - transform: skew(0deg, 6deg); - background: linear-gradient(to right, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.5) 4%, rgba(255, 255, 255, 0.2) 98%, rgba(255, 255, 255, 0)); - z-index: 2; -} - -.coffee_main .highlight:after { - height: 150px; - width: 4px; - left: -6px; - top: 0px; - transform: skew(0deg, 3deg); - background: linear-gradient(to bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 80%); -} - -.coffee_neck .highlight { - display: block; - height: 20px; - width: 25px; - position: absolute; - left: 2px; - top: 6px; - transform: skew(0deg, 6deg); - background: linear-gradient(to right, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.3) 4%, rgba(255, 255, 255, 0.1) 98%, rgba(255, 255, 255, 0)); -} - -.water { - background: linear-gradient(-85deg, rgba(167, 92, 24, 0.35), rgba(169, 108, 52, 0.55) 70%, rgba(185, 128, 76, 0.4)); - width: 99%; - height: 80px; - position: absolute; - left: 1px; - bottom: 1px; - border-radius: 50px 50px 20px 20px/8px 8px 10px 10px; - box-shadow: 0px 0px 6px rgba(165, 117, 73, 0.5) inset, 0px 0.2px 3px -1px rgba(0, 0, 0, 0.3) inset, 0px 2px 6px -1px rgba(0, 0, 0, 0.1) inset, 0px 2px 5px rgba(190,155,123,0.3), 0px 1px 3px rgba(190,155,123,0.2); -} - -.water:after { - height: 10px; - width: 100%; - left: -1px; - top: 0px; - background: linear-gradient(to right, rgba(255, 255, 255, 0.4), rgba(255, 127, 0, 0.05) 50%, rgba(251, 148, 0, 0.1) 80%, rgba(255, 255, 255, 0.3)); - border-radius: 50px/8px; - border: 1px solid rgba(255, 255, 255, 0.2); - border-bottom-color: rgba(255, 255, 255, 0.4); - box-shadow: 0px 1px 2px -1px rgba(165, 90, 26, 0.35); -} - -.water:before { - height: 10px; - width: 100%; - left: 2px; - bottom: -1px; - background: linear-gradient(to right, rgba(190,155,123,0.2), rgba(190,155,123,0.1) 50%, rgba(190,155,123,0.2) 80%, rgba(190,155,123,0.3)); - border-radius: 50px/10px; - border: 1px solid rgba(255, 255, 255, 0.1); - border-bottom: none; - box-shadow: 0px -2px 3px -1px rgba(190,155,123,0.25); -} - -.water { - height: 0px; - -webkit-transition: all 3s ease-out; - -moz-transition: all 3s ease-out; - -o-transition: all 3s ease-out; - transition: all 3s ease-out; - -webkit-border-radius: 10px; - -moz-border-radius: 10px; -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/index.jsp b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/index.jsp deleted file mode 100644 index 5c9425b3..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/index.jsp +++ /dev/null @@ -1,134 +0,0 @@ -<%-- - ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - ~ - ~ WSO2 Inc. licenses this file to you under the Apache License, - ~ Version 2.0 (the "License"); you may not use this file except - ~ in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - - - - Connected Coffee Cup - - - - - -<% - String deviceId = request.getParameter("deviceId"); - if (deviceId != null) { - request.getSession().setAttribute("deviceId", deviceId); - } - - String deviceOwner = request.getParameter("deviceOwner"); - if (deviceOwner != null) { - request.getSession().setAttribute("deviceOwner", deviceOwner); - } - - String tenantDomain = request.getParameter("tenantDomain"); - if (tenantDomain != null) { - request.getSession().setAttribute("tenantDomain", tenantDomain); - } - - String token = request.getParameter("token"); - if (token != null) { - request.getSession().setAttribute("token", token); - } -%> - -

-

Coffee Cup - Demo

-
- - - - - - - - - - - - - - -
Temperature:0 CCoffee Level:0%
-
-
- -
- -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/js/coffee.js b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/js/coffee.js deleted file mode 100644 index 294a15b6..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/js/coffee.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var temperature = 0; -var coffee_amount = 0; - -function updateCoffee(newValue) { - var coffee_level = document.getElementById('coffee_level'); - coffee_level.innerHTML = newValue + '%'; - coffee_amount = newValue; - - var coffee = document.getElementById('water'); - if (newValue == 0) { - coffee.style.height = (newValue * 3) + 'px'; - } else { - coffee.style.height = (newValue * 3) - 3 + 'px'; - } -} - -function updateTemperature(newValue) { - temperature = newValue; - var temperature_level = document.getElementById('temperature_level'); - temperature_level.innerHTML = newValue + ' C'; -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/js/libs/htmlpreview.min.js b/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/js/libs/htmlpreview.min.js deleted file mode 100644 index 58db9038..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/agent/src/main/webapp/js/libs/htmlpreview.min.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var HTMLPreview={content:"",previewform:document.getElementById("previewform"),file:function(){return location.search.substring(1)},raw:function(){return HTMLPreview.file().replace(/\/\/github\.com/,"//raw.githubusercontent.com").replace(/\/blob\//,"/")},replaceAssets:function(){var a,b,c;a=document.querySelectorAll("iframe[src],frame[src]");for(b=0;ba[b].innerHTML.indexOf("HTMLPreview")&&document.write(a[b].outerHTML)}},loadHTML:function(a){a&&a.query&&a.query.diagnostics&&a.query.diagnostics.redirect?HTMLPreview.send(a.query.diagnostics.redirect.content,"loadHTML"):a&&a.query&&a.query.results&&a.query.results.resources&&a.query.results.resources.content&&200==a.query.results.resources.status?(HTMLPreview.content=a.query.results.resources.content.replace(//i,'').replace(/<\/body>/i,' - 0 0/3 * * * ? - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_store/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_store/artifact.xml deleted file mode 100644 index 2aeb6edf..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_store/artifact.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - org_wso2_iot_devices_coffeelevel.xml - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_store/org_wso2_iot_devices_coffeelevel.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_store/org_wso2_iot_devices_coffeelevel.xml deleted file mode 100644 index 1253864f..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_store/org_wso2_iot_devices_coffeelevel.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - org.wso2.iot.devices.coffeelevel:1.0.0 - - EVENT_STORE - - - meta_owner - true - true - false - STRING - - - meta_deviceType - true - true - false - STRING - - - meta_deviceId - true - true - false - STRING - - - meta_time - true - true - false - LONG - - - coffeelevel - false - false - false - FLOAT - - - \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_stream/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_stream/artifact.xml deleted file mode 100644 index 14ed35ee..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_stream/artifact.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - org.wso2.iot.devices.coffeelevel_1.0.0.json - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_stream/org.wso2.iot.devices.coffeelevel_1.0.0.json b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_stream/org.wso2.iot.devices.coffeelevel_1.0.0.json deleted file mode 100644 index abcace4e..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/coffee_level_stream/org.wso2.iot.devices.coffeelevel_1.0.0.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "org.wso2.iot.devices.coffeelevel", - "version": "1.0.0", - "nickName": "CoffeeLevel", - "description": "Coffee Level data received from the Device", - "metaData": [ - {"name":"owner","type":"STRING"}, - {"name":"deviceType","type":"STRING"}, - {"name":"deviceId","type":"STRING"}, - {"name":"time","type":"LONG"} - ], - "payloadData": [ - { - "name": "coffeelevel","type": "FLOAT" - } - ] -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_publisher/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_publisher/artifact.xml deleted file mode 100644 index 9803a168..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_publisher/artifact.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - temperature_level_publisher.xml - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_publisher/temperature_level_publisher.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_publisher/temperature_level_publisher.xml deleted file mode 100644 index 16a0bce0..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_publisher/temperature_level_publisher.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_receiver/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_receiver/artifact.xml deleted file mode 100644 index 5647c8e1..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_receiver/artifact.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - temperature_level_receiver.xml - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_receiver/temperature_level_receiver.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_receiver/temperature_level_receiver.xml deleted file mode 100644 index 4e36e4c7..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_receiver/temperature_level_receiver.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - false - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_script/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_script/artifact.xml deleted file mode 100644 index fdd524ed..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_script/artifact.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - temperature_level_script.xml - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_script/temperature_level_script.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_script/temperature_level_script.xml deleted file mode 100644 index 60d79d3f..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_script/temperature_level_script.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - temperature_level_script - - 0 0/3 * * * ? - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_store/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_store/artifact.xml deleted file mode 100644 index cdf54780..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_store/artifact.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - org_wso2_iot_devices_temperature.xml - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_store/org_wso2_iot_devices_temperature.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_store/org_wso2_iot_devices_temperature.xml deleted file mode 100644 index bc448459..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_store/org_wso2_iot_devices_temperature.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - meta_owner - true - true - false - STRING - - - meta_deviceType - true - true - false - STRING - - - meta_deviceId - true - true - false - STRING - - - meta_time - true - true - false - LONG - - - temperature - false - false - false - FLOAT - - - - org.wso2.iot.devices.temperature:1.0.0 - - - EVENT_STORE - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_stream/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_stream/artifact.xml deleted file mode 100644 index 841c1d4f..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_stream/artifact.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - org.wso2.iot.devices.temperature_1.0.0.json - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_stream/org.wso2.iot.devices.temperature_1.0.0.json b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_stream/org.wso2.iot.devices.temperature_1.0.0.json deleted file mode 100644 index c2e3ada2..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/coffee_level/temperature_level_stream/org.wso2.iot.devices.temperature_1.0.0.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "org.wso2.iot.devices.temperature", - "version": "1.0.0", - "nickName": "TemperatureLevel", - "description": "Temperature Level data received from the Device", - "metaData": [ - {"name":"owner","type":"STRING"}, - {"name":"deviceType","type":"STRING"}, - {"name":"deviceId","type":"STRING"}, - {"name":"time","type":"LONG"} - ], - "payloadData": [ - { - "name": "temperature","type": "FLOAT" - } - ] -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/artifacts.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/artifacts.xml deleted file mode 100644 index f5ef3482..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/artifacts.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_execution/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_execution/artifact.xml deleted file mode 100644 index b20dcc84..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_execution/artifact.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - connected_cup_execution.siddhiql - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_execution/connected_cup_execution.siddhiql b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_execution/connected_cup_execution.siddhiql deleted file mode 100644 index 51552f2b..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_execution/connected_cup_execution.siddhiql +++ /dev/null @@ -1,24 +0,0 @@ -/* Enter a unique ExecutionPlan */ -@Plan:name('connected_cup_execution') - -/* Enter a unique description for ExecutionPlan */ --- @Plan:description('connected_cup_execution') - -/* define streams/tables and write queries here ... */ - -@Export('org.wso2.iot.devices.temperature:1.0.0') -define stream temperature (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, temperature float); - -@Export('org.wso2.iot.devices.coffeelevel:1.0.0') -define stream coffeelevel (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, coffeelevel float); - -@Import('org.wso2.iot.connectedcup:1.0.0') -define stream connectedcup (meta_owner string, meta_deviceId string, meta_type string, meta_timestamp long, temperature float, coffeelevel float); - -from connectedcup[meta_type == 'coffeelevel'] -select meta_owner, 'connectedcup' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, coffeelevel -insert into coffeelevel; - -from connectedcup[meta_type == 'temperature'] -select meta_owner, 'connectedcup' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, temperature -insert into temperature; \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_publisher/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_publisher/artifact.xml deleted file mode 100644 index 354893d8..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_publisher/artifact.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - connected_cup_publisher.xml - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_publisher/connected_cup_publisher.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_publisher/connected_cup_publisher.xml deleted file mode 100644 index 597b9661..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_publisher/connected_cup_publisher.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_receiver/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_receiver/artifact.xml deleted file mode 100644 index fc46f231..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_receiver/artifact.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - connected_cup_receiver.xml - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_receiver/connected_cup_receiver.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_receiver/connected_cup_receiver.xml deleted file mode 100644 index 229ae2dd..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_receiver/connected_cup_receiver.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - carbon.super/connectedcup/# - deviceid-topic-content-validator - default - true - - - - \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_stream/artifact.xml b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_stream/artifact.xml deleted file mode 100644 index 7d5f267f..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_stream/artifact.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - org.wso2.iot.connectedcup_1.0.0.json - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_stream/org.wso2.iot.connectedcup_1.0.0.json b/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_stream/org.wso2.iot.connectedcup_1.0.0.json deleted file mode 100644 index a93e29e0..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/analytics/src/main/resources/carbonapps/connected_cup/connected_cup_stream/org.wso2.iot.connectedcup_1.0.0.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "org.wso2.iot.connectedcup", - "version": "1.0.0", - "nickName": "connectedcup", - "description": "This hold the device type stream of connectedcup", - "metaData": [ - {"name": "owner", "type": "STRING"}, - {"name": "deviceId", "type": "STRING"}, - {"name": "type", "type": "STRING"}, - {"name": "timestamp", "type": "LONG"} - ], - "payloadData": [ - {"name": "temperature", "type": "FLOAT"}, - {"name": "coffeelevel", "type": "FLOAT"} - ] -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/pom.xml b/modules/distribution/src/core/samples/connectedcup/component/api/pom.xml deleted file mode 100644 index 448654e3..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/pom.xml +++ /dev/null @@ -1,162 +0,0 @@ - - - - - - device-mgt-iot-connectedcup - org.coffeeking - 1.0.0 - ../pom.xml - - - 4.0.0 - org.coffeeking.connectedcup.api - 1.0.0 - war - WSO2 IoTS(Device Types) - Connected Cup API - WSO2 IoTS(Device Types) - Connected Cup API - http://wso2.org - - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - provided - - - org.apache.axis2.wso2 - axis2-client - - - - - - - org.apache.cxf - cxf-rt-frontend-jaxws - provided - - - org.apache.cxf - cxf-rt-frontend-jaxrs - provided - - - org.apache.cxf - cxf-rt-transports-http - provided - - - - - org.eclipse.paho - org.eclipse.paho.client.mqttv3 - provided - - - - - org.apache.httpcomponents - httpasyncclient - 4.1 - provided - - - org.coffeeking - org.coffeeking.connectedcup.plugin - provided - - - - - org.codehaus.jackson - jackson-core-asl - - - org.codehaus.jackson - jackson-jaxrs - - - javax - javaee-web-api - provided - - - javax.ws.rs - jsr311-api - provided - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.data.publisher - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.annotations - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.webapp.publisher - provided - - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.api - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.extensions - provided - - - - - ${basedir}/src/main/java - - - - maven-compiler-plugin - - 1.8 - 1.8 - - 2.3.2 - - - maven-war-plugin - - connectedcup - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupService.java b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupService.java deleted file mode 100644 index 7b868612..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupService.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.api; - -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; -import org.wso2.carbon.apimgt.annotations.api.Scope; -import org.wso2.carbon.apimgt.annotations.api.Scopes; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - - -@SwaggerDefinition( - info = @Info( - version = "1.0.0", - title = "", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = "name", value = "connectedcup"), - @ExtensionProperty(name = "context", value = "/connectedcup"), - }) - } - ), - tags = { - @Tag(name = "connectedcup,device_management", description = "") - } -) -@Scopes( - scopes = { - @Scope( - name = "Enroll device", - description = "", - key = "perm:connectedcup:enroll", - permissions = {"/device-mgt/devices/enroll/connectedcup"} - ) - } -) -public interface ConnectedCupService { - - String SCOPE = "scope"; - - @Path("device/ordercoffee") - @POST - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Order Coffee", - notes = "", - response = Response.class, - tags = "connectedcup", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:connectedcup:enroll") - }) - } - ) - Response orderCoffee(@QueryParam("deviceId") String deviceId); - - /** - * Retrieve Sensor data for the device type - */ - @Path("stats/{deviceId}/sensors/{sensorName}") - @GET - @Consumes("application/json") - @Produces("application/json") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Retrieve Sensor data for the device type", - notes = "", - response = Response.class, - tags = "connectedcup", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:connectedcup:enroll") - }) - } - ) - Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor, - @QueryParam("from") long from, @QueryParam("to") long to); - - @Path("device/register") - @POST - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Enroll Cup", - notes = "", - response = Response.class, - tags = "connectedcup", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:connectedcup:enroll") - }) - } - ) - boolean register(@QueryParam("name") String name); - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupServiceImpl.java b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupServiceImpl.java deleted file mode 100644 index b20e11a2..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupServiceImpl.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.api; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.api.util.APIUtil; -import org.coffeeking.api.util.SensorRecord; -import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; -import org.wso2.carbon.analytics.dataservice.commons.SortByField; -import org.wso2.carbon.analytics.dataservice.commons.SortType; -import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -public class ConnectedCupServiceImpl implements ConnectedCupService { - - private static Log log = LogFactory.getLog(ConnectedCupServiceImpl.class); - - private static String shortUUID() { - UUID uuid = UUID.randomUUID(); - long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); - return Long.toString(l, Character.MAX_RADIX); - } - - @Path("device/ordercoffee") - @POST - public Response orderCoffee(@QueryParam("deviceId") String deviceId) { - try { - if (!APIUtil.getDeviceAccessAuthorizationService() - .isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE), - DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - log.info("Coffee ordered....!"); - if (log.isDebugEnabled()) { - log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT"); - } - return Response.ok().entity("Coffee ordered.").build(); - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - - @Path("stats/{deviceId}/sensors/{sensorName}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor, - @QueryParam("from") long from, @QueryParam("to") long to) { - String fromDate = String.valueOf(from); - String toDate = String.valueOf(to); - String query = " deviceId:" + deviceId + " AND deviceType:" + - ConnectedCupConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; - String sensorTableName = getSensorEventTableName(sensor); - - try { - if (!APIUtil.getDeviceAccessAuthorizationService() - .isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE), - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - List sensorDatas; - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField("time", SortType.ASC); - sortByFields.add(sortByField); - sensorDatas = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields); - return Response.ok().entity(sensorDatas).build(); - } catch (AnalyticsException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - - /** - * get the event table from the sensor name. - */ - private String getSensorEventTableName(String sensorName) { - String sensorEventTableName; - switch (sensorName) { - case "temperature": - sensorEventTableName = "DEVICE_TEMPERATURE_SUMMARY"; - break; - case "coffeelevel": - sensorEventTableName = "DEVICE_COFFEELEVEL_SUMMARY"; - break; - default: - sensorEventTableName = ""; - } - return sensorEventTableName; - } - - @Path("device/register") - @POST - public boolean register(@QueryParam("name") String name) { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - String deviceId = shortUUID(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); - if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { - return false; - } - Device device = new Device(); - device.setDeviceIdentifier(deviceId); - EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setDateOfEnrolment(new Date().getTime()); - enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); - enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - device.setName(name); - device.setType(ConnectedCupConstants.DEVICE_TYPE); - enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); - device.setEnrolmentInfo(enrolmentInfo); - return APIUtil.getDeviceManagementService().enrollDevice(device); - } catch (DeviceManagementException e) { - log.error("Failed to enroll device with device name :" + name, e); - return false; - } - } - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/exception/ConnectedCupException.java b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/exception/ConnectedCupException.java deleted file mode 100644 index a4afadd5..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/exception/ConnectedCupException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.api.exception; - -public class ConnectedCupException extends Exception { - - private static final long serialVersionUID = 118512086957330189L; - - public ConnectedCupException(String errorMessage) { - super(errorMessage); - } - - public ConnectedCupException(String errorMessage, Throwable throwable) { - super(errorMessage, throwable); - } - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/APIUtil.java b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/APIUtil.java deleted file mode 100644 index efb120c7..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/APIUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.api.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; -import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; -import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; -import org.wso2.carbon.analytics.dataservice.commons.SortByField; -import org.wso2.carbon.analytics.datasource.commons.Record; -import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * This class provides utility functions used by REST-API. - */ -public class APIUtil { - - private static Log log = LogFactory.getLog(APIUtil.class); - - public static String getAuthenticatedUser() { - PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - String username = threadLocalCarbonContext.getUsername(); - String tenantDomain = threadLocalCarbonContext.getTenantDomain(); - if (username.endsWith(tenantDomain)) { - return username.substring(0, username.lastIndexOf("@")); - } - return username; - } - - public static DeviceManagementProviderService getDeviceManagementService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceManagementProviderService deviceManagementProviderService = - (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); - if (deviceManagementProviderService == null) { - throw new IllegalStateException("Device Management service has not initialized"); - } - return deviceManagementProviderService; - } - - public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceAccessAuthorizationService deviceAccessAuthorizationService = - (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null); - if (deviceAccessAuthorizationService == null) { - throw new IllegalStateException("Device Authorization service has not initialized"); - } - return deviceAccessAuthorizationService; - } - - public static AnalyticsDataAPI getAnalyticsDataAPI() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - AnalyticsDataAPI analyticsDataAPI = - (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); - if (analyticsDataAPI == null) { - throw new IllegalStateException("Analytics api service has not initialized"); - } - return analyticsDataAPI; - } - - public static List getAllEventsForDevice(String tableName, String query, - List sortByFields) throws AnalyticsException { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); - int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); - // limiting the data read from the server - int start = 0; - int dataCount = 100; - if (eventCount == 0) { - return null; - } else if (eventCount >= dataCount){ - start = eventCount - dataCount; - } - - List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, start, eventCount, - sortByFields); - List recordIds = getRecordIds(resultEntries); - AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); - Map sensorDatas = createSensorData(AnalyticsDataAPIUtil.listRecords( - analyticsDataAPI, response)); - List sortedSensorData = getSortedSensorData(sensorDatas, resultEntries); - return sortedSensorData; - } - - - private static List getRecordIds(List searchResults) { - List ids = new ArrayList<>(); - for (SearchResultEntry searchResult : searchResults) { - ids.add(searchResult.getId()); - } - return ids; - } - - public static List getSortedSensorData(Map sensorDatas, - List searchResults) { - List sortedRecords = new ArrayList<>(); - for (SearchResultEntry searchResultEntry : searchResults) { - sortedRecords.add(sensorDatas.get(searchResultEntry.getId())); - } - return sortedRecords; - } - - /** - * Creates the SensorDatas from records. - * - * @param records the records - * @return the Map of SensorRecord - */ - public static Map createSensorData(List records) { - Map sensorDatas = new HashMap<>(); - for (Record record : records) { - SensorRecord sensorData = createSensorData(record); - sensorDatas.put(sensorData.getId(), sensorData); - } - return sensorDatas; - } - - /** - * Create a SensorRecord object out of a Record object - * - * @param record the record object - * @return SensorRecord object - */ - public static SensorRecord createSensorData(Record record) { - SensorRecord recordBean = new SensorRecord(); - recordBean.setId(record.getId()); - recordBean.setValues(record.getValues()); - return recordBean; - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/SensorRecord.java b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/SensorRecord.java deleted file mode 100644 index 559ceb11..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/SensorRecord.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.api.util; - -import org.codehaus.jackson.annotate.JsonIgnoreProperties; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -@XmlRootElement -/** - * This stores sensor event data for android sense. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class SensorRecord { - - @XmlElementWrapper(required = true, name = "values") - private Map values; - - @XmlElement(required = false, name = "id") - private String id; - - /** - * Gets the values. - * - * @return the values - */ - public Map getValues() { - return values; - } - - /** - * Sets the values. - * - * @param values the values - */ - public void setValues(Map values) { - this.values = values; - } - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - return id; - } - - /** - * Sets the id. - * - * @param id the new id - */ - public void setId(String id) { - this.id = id; - } - - @Override - public String toString() { - List valueList = new ArrayList(); - for (Map.Entry entry : values.entrySet()) { - valueList.add(entry.getKey() + ":" + entry.getValue()); - } - return valueList.toString(); - - } - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/META-INF/permissions.xml b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/META-INF/permissions.xml deleted file mode 100644 index e216705b..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/META-INF/permissions.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - Register a device - /device-mgt/user/devices - /device/register - POST - connectedcup_user - - - Order coffee cup - /device-mgt/user/operation - /device/ordercoffee - POST - connectedcup_user - - - get device stats - /device-mgt/user/stats - /stats/*/sensors/* - GET - connectedcup_user - - \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/META-INF/webapp-classloading.xml b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index ac70a8ca..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - false - - - CXF,Carbon - diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index 5dfc1661..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 55a9dd85..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/api/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - ConnectedCup-Webapp - - - CXFServlet - org.apache.cxf.transport.servlet.CXFServlet - 1 - - - CXFServlet - /* - - - isAdminService - false - - - doAuthentication - true - - - isSharedWithAllTenants - true - - - providerTenantDomain - carbon.super - - - - - managed-api-enabled - true - - - managed-api-owner - admin - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/pom.xml b/modules/distribution/src/core/samples/connectedcup/component/plugin/pom.xml deleted file mode 100644 index 4236a15b..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - device-mgt-iot-connectedcup - org.coffeeking - 1.0.0 - ../pom.xml - - - 4.0.0 - org.coffeeking.connectedcup.plugin - 1.0.0 - bundle - WSO2 IoTS(Device Types) - Connected Cup CDMF Plugin - WSO2 IoTS(Device Types) - Connected Cup CDMF Plugin - http://wso2.org - - - - - org.apache.felix - maven-scr-plugin - - - maven-compiler-plugin - - 1.8 - 1.8 - - 2.3.2 - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${org.coffeeking.version} - IoT Server Impl Bundle - org.coffeeking.connectedcup.plugin.internal - - org.osgi.framework, - org.osgi.service.component, - org.apache.commons.logging, - javax.xml.bind.*;resolution:=optional, - javax.naming;resolution:=optional, - javax.sql;resolution:=optional, - javax.xml.bind.annotation.*;resolution:=optional, - org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.device.mgt.common, - org.wso2.carbon.context.*, - org.wso2.carbon.base.*, - javax.xml.parsers.*;resolution:=optional - - - !org.coffeeking.connectedcup.plugin.internal, - org.coffeeking.connectedcup.plugin.* - - - - - - - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - - org.wso2.carbon - org.wso2.carbon.logging - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - - - org.wso2.carbon - org.wso2.carbon.ndatasource.core - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/constants/ConnectedCupConstants.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/constants/ConnectedCupConstants.java deleted file mode 100644 index b1b71488..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/constants/ConnectedCupConstants.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.coffeeking.connectedcup.plugin.constants; - -public class ConnectedCupConstants { - - public final static String DEVICE_TYPE = "connectedcup"; - public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; - public final static String DEVICE_PLUGIN_DEVICE_ID = "CONNECTED_CUP_DEVICE_ID"; - public final static String ORDER_ON = "YES"; - public final static String ORDER_OFF = "NO"; - - public static final String URL_PREFIX = "http://"; - public static final String LEVEL_CONTEXT = "/LEVEL/"; - public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/"; - - public static final String SENSOR_TEMPERATURE = "temperature"; - public static final String SENSOR_LEVEL = "level"; - public static final String DATA_SOURCE_NAME = "jdbc/ConnectedCupDM_DB"; - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/exception/ConnectedCupDeviceMgtPluginException.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/exception/ConnectedCupDeviceMgtPluginException.java deleted file mode 100644 index 92b85968..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/exception/ConnectedCupDeviceMgtPluginException.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.coffeeking.connectedcup.plugin.exception; - -public class ConnectedCupDeviceMgtPluginException extends Exception { - - public ConnectedCupDeviceMgtPluginException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public ConnectedCupDeviceMgtPluginException(String message, Throwable cause) { - super(message, cause); - } - - public ConnectedCupDeviceMgtPluginException(String msg) { - super(msg); - } - - public ConnectedCupDeviceMgtPluginException() { - super(); - } - - public ConnectedCupDeviceMgtPluginException(Throwable cause) { - super(cause); - } - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupFeatureManager.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupFeatureManager.java deleted file mode 100644 index d1f9e3f3..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupFeatureManager.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.connectedcup.plugin.impl; - -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.Feature; -import org.wso2.carbon.device.mgt.common.FeatureManager; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * This hold the feature manager implementation for Connected CUp. - */ -public class ConnectedCupFeatureManager implements FeatureManager{ - private static Feature feature = new Feature(); - private static final String METHOD = "method"; - private static final String URI = "uri"; - private static final String CONTENT_TYPE = "contentType"; - private static final String PATH_PARAMS = "pathParams"; - private static final String QUERY_PARAMS = "queryParams"; - private static final String FORM_PARAMS = "formParams"; - - public ConnectedCupFeatureManager() { - - feature.setCode("ordercoffee"); - feature.setName("Order Coffee"); - feature.setDescription("Order coffee cup"); - - Map apiParams = new HashMap<>(); - apiParams.put(METHOD, "POST"); - apiParams.put(URI, "/connectedcup/device/ordercoffee"); - List pathParams = new ArrayList<>(); - List queryParams = new ArrayList<>(); - List formParams = new ArrayList<>(); - apiParams.put(PATH_PARAMS, pathParams); - queryParams.add("deviceId"); - apiParams.put(QUERY_PARAMS, queryParams); - apiParams.put(FORM_PARAMS, formParams); - List metadataEntries = new ArrayList<>(); - Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); - metadataEntry.setId(-1); - metadataEntry.setValue(apiParams); - metadataEntries.add(metadataEntry); - feature.setMetadataEntries(metadataEntries); - } - - @Override - public boolean addFeature(Feature feature) throws DeviceManagementException { - return false; - } - - @Override - public boolean addFeatures(List list) throws DeviceManagementException { - return false; - } - - @Override - public Feature getFeature(String code) throws DeviceManagementException { - if (code.equals(feature.getCode())) { - return feature; - } - return null; - } - - @Override - public List getFeatures() throws DeviceManagementException { - List features = new ArrayList<>(); - features.add(feature); - return features; - } - - @Override - public boolean removeFeature(String s) throws DeviceManagementException { - return false; - } - - @Override - public boolean addSupportedFeaturesToDB() throws DeviceManagementException { - return false; - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupManager.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupManager.java deleted file mode 100644 index 5fb9244e..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupManager.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.connectedcup.plugin.impl; - - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException; -import org.coffeeking.connectedcup.plugin.impl.dao.ConnectedCupDAOUtil; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.DeviceManager; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.FeatureManager; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.license.mgt.License; -import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; -import java.util.List; - -/** - * Device Manager interface impl for connected cup. - */ -public class ConnectedCupManager implements DeviceManager { - - private static final Log log = LogFactory.getLog(ConnectedCupManager.class); - - private static final ConnectedCupDAOUtil CONNECTED_CUP_DAO_UTIL = new ConnectedCupDAOUtil(); - - - @Override - public FeatureManager getFeatureManager() { - return null; - } - - @Override - public boolean saveConfiguration(PlatformConfiguration platformConfiguration) throws DeviceManagementException { - return false; - } - - @Override - public PlatformConfiguration getConfiguration() throws DeviceManagementException { - return null; - } - - @Override - public boolean enrollDevice(Device device) throws DeviceManagementException { - boolean status; - try { - if (log.isDebugEnabled()) { - log.debug("Enrolling a new Connected Cup device : " + device.getDeviceIdentifier()); - } - ConnectedCupDAOUtil.beginTransaction(); - status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().addDevice(device); - ConnectedCupDAOUtil.commitTransaction(); - } catch (ConnectedCupDeviceMgtPluginException e) { - try { - ConnectedCupDAOUtil.rollbackTransaction(); - } catch (ConnectedCupDeviceMgtPluginException iotDAOEx) { - String msg = "Error occurred while roll back the device enrol transaction :" + device.toString(); - log.warn(msg, iotDAOEx); - } - String msg = "Error while enrolling the Connected Cup device : " + device.getDeviceIdentifier(); - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - return status; - } - - @Override - public boolean modifyEnrollment(Device device) throws DeviceManagementException { - boolean status; - try { - if (log.isDebugEnabled()) { - log.debug("Modifying the Connected Cup device enrollment data"); - } - ConnectedCupDAOUtil.beginTransaction(); - status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().updateDevice(device); - ConnectedCupDAOUtil.commitTransaction(); - } catch (ConnectedCupDeviceMgtPluginException e) { - try { - ConnectedCupDAOUtil.rollbackTransaction(); - } catch (ConnectedCupDeviceMgtPluginException iotDAOEx) { - String msg = "Error occurred while roll back the update device transaction :" + device.toString(); - log.warn(msg, iotDAOEx); - } - String msg = "Error while updating the enrollment of the Connected Cup device : " + - device.getDeviceIdentifier(); - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - return status; - } - - @Override - public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - boolean status; - try { - if (log.isDebugEnabled()) { - log.debug("Dis-enrolling Connected Cup device : " + deviceId); - } - ConnectedCupDAOUtil.beginTransaction(); - status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().deleteDevice(deviceId.getId()); - ConnectedCupDAOUtil.commitTransaction(); - } catch (ConnectedCupDeviceMgtPluginException e) { - try { - ConnectedCupDAOUtil.rollbackTransaction(); - } catch (ConnectedCupDeviceMgtPluginException iotDAOEx) { - String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString(); - log.warn(msg, iotDAOEx); - } - String msg = "Error while removing the Connected Cup device : " + deviceId.getId(); - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - return status; - } - - @Override - public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { - boolean isEnrolled = false; - try { - if (log.isDebugEnabled()) { - log.debug("Checking the enrollment of Connected Cup device : " + deviceId.getId()); - } - Device iotDevice = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().getDevice(deviceId.getId()); - if (iotDevice != null) { - isEnrolled = true; - } - } catch (ConnectedCupDeviceMgtPluginException e) { - String msg = "Error while checking the enrollment status of Connected Cup device : " + - deviceId.getId(); - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - return isEnrolled; - } - - @Override - public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException { - return true; - } - - @Override - public boolean setActive(DeviceIdentifier deviceId, boolean status) - throws DeviceManagementException { - return true; - } - - @Override - public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - Device device; - try {if (log.isDebugEnabled()) { - log.debug("Getting the details of Connected Cup device : " + deviceId.getId()); - } - device = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().getDevice(deviceId.getId()); - - } catch (ConnectedCupDeviceMgtPluginException e) { - String msg = "Error while fetching the Connected Cup device : " + deviceId.getId(); - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - return device; - } - - @Override - public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) - throws DeviceManagementException { - return true; - } - - public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { - return false; - } - - @Override - public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, - EnrolmentInfo.Status status) throws DeviceManagementException { - return false; - } - - @Override - public License getLicense(String s) throws LicenseManagementException { - return null; - } - - @Override - public void addLicense(License license) throws LicenseManagementException { - - } - - @Override - public boolean requireDeviceAuthorization() { - return false; - } - - @Override - public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { - boolean status; - try { - if (log.isDebugEnabled()) { - log.debug( - "updating the details of Connected Cup device : " + deviceIdentifier); - } - ConnectedCupDAOUtil.beginTransaction(); - status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().updateDevice(device); - ConnectedCupDAOUtil.commitTransaction(); - } catch (ConnectedCupDeviceMgtPluginException e) { - try { - ConnectedCupDAOUtil.rollbackTransaction(); - } catch (ConnectedCupDeviceMgtPluginException iotDAOEx) { - String msg = "Error occurred while roll back the update device info transaction :" + device.toString(); - log.warn(msg, iotDAOEx); - } - String msg = - "Error while updating the Connected Cup device : " + deviceIdentifier; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - return status; - } - - @Override - public List getAllDevices() throws DeviceManagementException { - List devices = null; - try { - if (log.isDebugEnabled()) { - log.debug("Fetching the details of all Connected Cup devices"); - } - devices = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().getAllDevices(); - } catch (ConnectedCupDeviceMgtPluginException e) { - String msg = "Error while fetching all Connected Cup devices."; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - return devices; - } - - @Override - public boolean updateDeviceProperties(DeviceIdentifier deviceIdentifier, List list) throws DeviceManagementException { - return false; - } -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupManagerService.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupManagerService.java deleted file mode 100644 index d74586ca..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/ConnectedCupManagerService.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.connectedcup.plugin.impl; - -import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.DeviceManager; -import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; -import org.wso2.carbon.device.mgt.common.InitialOperationConfig; -import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; -import org.wso2.carbon.device.mgt.common.ProvisioningConfig; -import org.wso2.carbon.device.mgt.common.general.GeneralConfig; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; -import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; -import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; -import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; -import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; - -public class ConnectedCupManagerService implements DeviceManagementService { - private DeviceManager deviceManager; - - @Override - public void init() throws DeviceManagementException { - this.deviceManager = new ConnectedCupManager(); - } - - @Override - public String getType() { - return ConnectedCupConstants.DEVICE_TYPE; - } - - @Override - public OperationMonitoringTaskConfig getOperationMonitoringConfig() { - return null; - } - - @Override - public DeviceManager getDeviceManager() { - return deviceManager; - } - - @Override - public ApplicationManager getApplicationManager() { - return null; - } - - @Override - public ProvisioningConfig getProvisioningConfig() { - return new ProvisioningConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, false); - } - - @Override - public PushNotificationConfig getPushNotificationConfig() { - return null; - } - - @Override - public PolicyMonitoringManager getPolicyMonitoringManager() { - return null; - } - - @Override - public InitialOperationConfig getInitialOperationConfig() { - return null; - } - - @Override - public PullNotificationSubscriber getPullNotificationSubscriber() { - return null; - } - - @Override - public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() { - return null; - } - - @Override - public GeneralConfig getGeneralConfig() { - return null; - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/ConnectedCupDAO.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/ConnectedCupDAO.java deleted file mode 100644 index deb509cc..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/ConnectedCupDAO.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.connectedcup.plugin.impl.dao; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; -import org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException; -import org.coffeeking.connectedcup.plugin.impl.dao.util.ConnectedCupUtils; -import org.wso2.carbon.device.mgt.common.Device; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -/** - * Device Dao for connected cup Devices. - */ -public class ConnectedCupDAO { - - - private static final Log log = LogFactory.getLog(ConnectedCupDAO.class); - - public Device getDevice(String deviceId) throws ConnectedCupDeviceMgtPluginException { - Connection conn = null; - PreparedStatement stmt = null; - Device connectedCupDevice = null; - ResultSet resultSet = null; - try { - conn = ConnectedCupDAOUtil.getConnection(); - String selectDBQuery = - "SELECT CONNECTED_CUP_DEVICE_ID, DEVICE_NAME FROM CONNECTED_CUP_DEVICE WHERE CONNECTED_CUP_DEVICE_ID = ?"; - stmt = conn.prepareStatement(selectDBQuery); - stmt.setString(1, deviceId); - resultSet = stmt.executeQuery(); - - if (resultSet.next()) { - connectedCupDevice = new Device(); - connectedCupDevice.setName(resultSet.getString(ConnectedCupConstants.DEVICE_PLUGIN_DEVICE_NAME)); - if (log.isDebugEnabled()) { - log.debug("Connected Cup service " + deviceId + " data has been fetched from" + - "Connected Cup database."); - } - } - } catch (SQLException e) { - String msg = "Error occurred while fetching Connected Cup device : '" + deviceId + "'"; - log.error(msg, e); - throw new ConnectedCupDeviceMgtPluginException(msg, e); - } finally { - ConnectedCupUtils.cleanupResources(stmt, resultSet); - ConnectedCupDAOUtil.closeConnection(); - } - return connectedCupDevice; - } - - - public boolean addDevice(Device connectedCupDevice) throws ConnectedCupDeviceMgtPluginException { - boolean status = false; - Connection conn = null; - PreparedStatement stmt = null; - try { - conn = ConnectedCupDAOUtil.getConnection(); - String createDBQuery = - "INSERT INTO CONNECTED_CUP_DEVICE(CONNECTED_CUP_DEVICE_ID, DEVICE_NAME ) VALUES (?, ?)"; - - stmt = conn.prepareStatement(createDBQuery); - stmt.setString(1, connectedCupDevice.getDeviceIdentifier()); - stmt.setString(2, connectedCupDevice.getName()); - - int rows = stmt.executeUpdate(); - if (rows > 0) { - status = true; - if (log.isDebugEnabled()) { - log.debug("Connected Cup device " + connectedCupDevice.getDeviceIdentifier() + - " data has been added to the Connected Cup database."); - } - } - } catch (SQLException e) { - String msg = "Error occurred while adding the Connected Cup device '" + - connectedCupDevice.getDeviceIdentifier() + "' to the Connected Cup db."; - log.error(msg, e); - throw new ConnectedCupDeviceMgtPluginException(msg, e); - } finally { - ConnectedCupUtils.cleanupResources(stmt, null); - } - return status; - } - - public boolean updateDevice(Device connectedCupDevice) throws ConnectedCupDeviceMgtPluginException { - boolean status = false; - Connection conn = null; - PreparedStatement stmt = null; - try { - conn = ConnectedCupDAOUtil.getConnection(); - String updateDBQuery = - "UPDATE CONNECTED_CUP_DEVICE SET DEVICE_NAME = ? WHERE CONNECTED_CUP_DEVICE_ID = ?"; - - stmt = conn.prepareStatement(updateDBQuery); - stmt.setString(1, connectedCupDevice.getName()); - stmt.setString(2, connectedCupDevice.getDeviceIdentifier()); - int rows = stmt.executeUpdate(); - if (rows > 0) { - status = true; - if (log.isDebugEnabled()) { - log.debug("Connected Cup device " + connectedCupDevice.getDeviceIdentifier() + - " data has been modified."); - } - } - } catch (SQLException e) { - String msg = "Error occurred while modifying the Connected Cup device '" + - connectedCupDevice.getDeviceIdentifier() + "' data."; - log.error(msg, e); - throw new ConnectedCupDeviceMgtPluginException(msg, e); - } finally { - ConnectedCupUtils.cleanupResources(stmt, null); - } - return status; - } - - public boolean deleteDevice(String deviceId) throws ConnectedCupDeviceMgtPluginException { - boolean status = false; - Connection conn = null; - PreparedStatement stmt = null; - try { - conn = ConnectedCupDAOUtil.getConnection(); - String deleteDBQuery = - "DELETE FROM CONNECTED_CUP_DEVICE WHERE CONNECTED_CUP_DEVICE_ID = ?"; - stmt = conn.prepareStatement(deleteDBQuery); - stmt.setString(1, deviceId); - int rows = stmt.executeUpdate(); - if (rows > 0) { - status = true; - if (log.isDebugEnabled()) { - log.debug("Connected Cup device " + deviceId + " data has deleted" + - " from the Connected Cup database."); - } - } - } catch (SQLException e) { - String msg = "Error occurred while deleting Connected Cup device " + deviceId; - log.error(msg, e); - throw new ConnectedCupDeviceMgtPluginException(msg, e); - } finally { - ConnectedCupUtils.cleanupResources(stmt, null); - } - return status; - } - - public List getAllDevices() throws ConnectedCupDeviceMgtPluginException { - - Connection conn = null; - PreparedStatement stmt = null; - ResultSet resultSet = null; - Device connectedCupDevice; - List iotDevices = new ArrayList<>(); - - try { - conn = ConnectedCupDAOUtil.getConnection(); - String selectDBQuery = - "SELECT CONNECTED_CUP_DEVICE_ID, DEVICE_NAME" + - "FROM CONNECTED_CUP_DEVICE"; - stmt = conn.prepareStatement(selectDBQuery); - resultSet = stmt.executeQuery(); - while (resultSet.next()) { - connectedCupDevice = new Device(); - connectedCupDevice.setDeviceIdentifier(resultSet.getString( - ConnectedCupConstants.DEVICE_PLUGIN_DEVICE_ID)); - connectedCupDevice.setName(resultSet.getString( - ConnectedCupConstants.DEVICE_PLUGIN_DEVICE_NAME)); - } - if (log.isDebugEnabled()) { - log.debug("All Connected Cup device details have fetched from Connected Cup database" + - "."); - } - return iotDevices; - } catch (SQLException e) { - String msg = "Error occurred while fetching all Connected Cup device data'"; - log.error(msg, e); - throw new ConnectedCupDeviceMgtPluginException(msg, e); - } finally { - ConnectedCupUtils.cleanupResources(stmt, resultSet); - ConnectedCupDAOUtil.closeConnection(); - } - - } - -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/ConnectedCupDAOUtil.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/ConnectedCupDAOUtil.java deleted file mode 100644 index 4daa8569..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/ConnectedCupDAOUtil.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.connectedcup.plugin.impl.dao; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; -import org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -public class ConnectedCupDAOUtil { - - private static final Log log = LogFactory.getLog(ConnectedCupDAOUtil.class); - static DataSource dataSource; - private static ThreadLocal currentConnection = new ThreadLocal(); - - public ConnectedCupDAOUtil() { - initConnectedCupDAO(); - } - - public static void initConnectedCupDAO() { - try { - Context ctx = new InitialContext(); - dataSource = (DataSource) ctx.lookup(ConnectedCupConstants.DATA_SOURCE_NAME); - } catch (NamingException e) { - log.error("Error while looking up the data source: " + - ConnectedCupConstants.DATA_SOURCE_NAME); - } - - } - - - public ConnectedCupDAO getConnectedCupDeviceDAO() { - return new ConnectedCupDAO(); - } - - public static void beginTransaction() throws ConnectedCupDeviceMgtPluginException { - try { - Connection conn = dataSource.getConnection(); - conn.setAutoCommit(false); - currentConnection.set(conn); - } catch (SQLException e) { - throw new ConnectedCupDeviceMgtPluginException( - "Error occurred while retrieving datasource connection", e); - } - } - - public static Connection getConnection() throws ConnectedCupDeviceMgtPluginException { - if (currentConnection.get() == null) { - try { - currentConnection.set(dataSource.getConnection()); - } catch (SQLException e) { - throw new ConnectedCupDeviceMgtPluginException( - "Error occurred while retrieving data source connection", e); - } - } - return currentConnection.get(); - } - - public static void commitTransaction() throws ConnectedCupDeviceMgtPluginException { - try { - Connection conn = currentConnection.get(); - if (conn != null) { - conn.commit(); - } else { - if (log.isDebugEnabled()) { - log.debug("Datasource connection associated with the current thread is null, " + - "hence commit has not been attempted"); - } - } - } catch (SQLException e) { - throw new ConnectedCupDeviceMgtPluginException( - "Error occurred while committing the transaction", e); - } finally { - closeConnection(); - } - } - - public static void closeConnection() throws ConnectedCupDeviceMgtPluginException { - - Connection con = currentConnection.get(); - if (con != null) { - try { - con.close(); - } catch (SQLException e) { - log.error("Error occurred while close the connection"); - } - } - currentConnection.remove(); - } - - public static void rollbackTransaction() throws ConnectedCupDeviceMgtPluginException { - try { - Connection conn = currentConnection.get(); - if (conn != null) { - conn.rollback(); - } else { - if (log.isDebugEnabled()) { - log.debug( - "Datasource connection associated with the current thread is null, " + - "hence rollback has not been attempted"); - } - } - } catch (SQLException e) { - throw new ConnectedCupDeviceMgtPluginException("Error occurred while rollback the transaction", e); - } finally { - closeConnection(); - } - } -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/util/ConnectedCupUtils.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/util/ConnectedCupUtils.java deleted file mode 100644 index 9c25f256..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/impl/dao/util/ConnectedCupUtils.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.connectedcup.plugin.impl.dao.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.Device; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -/** - * Contains utility methods used by FireAlarm plugin. - */ -public class ConnectedCupUtils { - - private static Log log = LogFactory.getLog(ConnectedCupUtils.class); - - public static String getDeviceProperty(List deviceProperties, String propertyKey) { - String deviceProperty = ""; - for (Device.Property property : deviceProperties) { - if (propertyKey.equals(property.getName())) { - deviceProperty = property.getValue(); - } - } - return deviceProperty; - } - - public static Device.Property getProperty(String property, String value) { - if (property != null) { - Device.Property prop = new Device.Property(); - prop.setName(property); - prop.setValue(value); - return prop; - } - return null; - } - - public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing result set", e); - } - } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing prepared statement", e); - } - } - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing database connection", e); - } - } - } - - public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { - cleanupResources(null, stmt, rs); - } - - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/internal/ConnectedCupServiceComponent.java b/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/internal/ConnectedCupServiceComponent.java deleted file mode 100644 index 6b6f00bd..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/plugin/src/main/java/org/coffeeking/connectedcup/plugin/internal/ConnectedCupServiceComponent.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.coffeeking.connectedcup.plugin.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.coffeeking.connectedcup.plugin.impl.ConnectedCupManagerService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; - -/** - * @scr.component name="org.coffeeking.connectedcup.plugin.internal - * .ConnectedCupServiceComponent" - * immediate="true" - */ - -public class ConnectedCupServiceComponent { - private static final Log log = LogFactory.getLog(ConnectedCupServiceComponent.class); - private ServiceRegistration connectedCupServiceRegRef; - - protected void activate(ComponentContext ctx) { - if (log.isDebugEnabled()) { - log.debug("Activating Connected Cup Service Component"); - } - try { - BundleContext bundleContext = ctx.getBundleContext(); - connectedCupServiceRegRef = - bundleContext.registerService(DeviceManagementService.class.getName(), - new ConnectedCupManagerService(), null); - - if (log.isDebugEnabled()) { - log.debug("Connected Cup Service Component has been successfully activated"); - } - } catch (Throwable e) { - log.error("Error occurred while activating Connected Cup Service Component", e); - } - } - - protected void deactivate(ComponentContext ctx) { - if (log.isDebugEnabled()) { - log.debug("De-activating Connected Cup Service Component"); - } - try { - if (connectedCupServiceRegRef != null) { - connectedCupServiceRegRef.unregister(); - } - - if (log.isDebugEnabled()) { - log.debug("Connected Cup Service Component has been successfully de-activated"); - } - } catch (Throwable e) { - log.error("Error occurred while de-activating Connected Cup Service Component", e); - } - } - -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/pom.xml b/modules/distribution/src/core/samples/connectedcup/component/pom.xml deleted file mode 100644 index b4e2bfdc..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - org.coffeeking - device.mgt.iot.connectedcup-parent - 1.0.0 - ../pom.xml - - - 4.0.0 - device-mgt-iot-connectedcup - 1.0.0 - pom - WSO2 IoTS(Device Types) - Connected Cup Component - WSO2 IoTS(Device Types) - Connected Cup Component - http://wso2.org - - - analytics - plugin - api - agent - ui - - - - - - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/pom.xml b/modules/distribution/src/core/samples/connectedcup/component/ui/pom.xml deleted file mode 100644 index d4118711..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - org.coffeeking - device-mgt-iot-connectedcup - 1.0.0 - ../pom.xml - - - 4.0.0 - org.coffeeking.connectedcup.ui - 1.0.0 - WSO2 IoTS(Device Types) - Connected Cup UI - pom - - - - - maven-assembly-plugin - 2.5.5 - - ${project.artifactId}-${carbon.device.mgt.version} - false - - src/assembly/src.xml - - - - - create-archive - package - - single - - - - - - - - diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/assembly/src.xml b/modules/distribution/src/core/samples/connectedcup/component/ui/src/assembly/src.xml deleted file mode 100644 index 2797034e..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/assembly/src.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - src - - zip - - false - ${basedir}/src - - - ${basedir}/src/main/resources/jaggeryapps/devicemgt - / - true - - - \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.hbs b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.hbs deleted file mode 100644 index 76a4038a..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.hbs +++ /dev/null @@ -1,48 +0,0 @@ -{{! - Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - - WSO2 Inc. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -}} - -
-
-

Temperature

-
-
-
-
-
-
-
-
-
-
-

Coffee Level

-
-
-
-
-
-
-
-
-
-
- -{{#zone "bottomJs"}} - {{js "js/connectedcup.js"}} -{{/zone}} diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.js b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.js deleted file mode 100644 index d651ba0b..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -function onRequest(context) { - var devices = context.unit.params.devices; - var deviceType = context.uriParams.deviceType; - var deviceId = request.getParameter("deviceId"); - - if (devices) { - return { - "devices": stringify(devices), - "backendApiUri": "/connectedcup/stats/" - }; - } else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { - var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; - var device = deviceModule.viewDevice(deviceType, deviceId); - if (device && device.status != "error") { - return { - "device": device.content, - "backendApiUri": "/connectedcup/stats/" + deviceId - }; - } else { - response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!"); - exit(); - } - } -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.json b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.json deleted file mode 100644 index 688e9398..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/analytics-view.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "version": "1.0.0" -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/public/js/connectedcup.js b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/public/js/connectedcup.js deleted file mode 100644 index 02e4a6d3..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.analytics-view/public/js/connectedcup.js +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var palette = new Rickshaw.Color.Palette({scheme: 'classic9'}); - -function drawGraph_connectedcup(from, to) { - $('#y_axis-temperature').html(''); - $('#smoother-temperature').html(''); - $('#legend-temperature').html(''); - $('#chart-temperature').html(''); - $('#x_axis-temperature').html(''); - $('#slider-temperature').html(''); - - $('#y_axis-coffeelevel').html(''); - $('#smoother-coffeelevel').html(''); - $('#legend-coffeelevel').html(''); - $('#chart-coffeelevel').html(''); - $('#x_axis-coffeelevel').html(''); - $('#slider-coffeelevel').html(''); - - var devices = $('#connectedcup-details').data('devices'); - var tzOffset = new Date().getTimezoneOffset() * 60; - - var chartWrapperElmId = '#connectedcup-div-chart'; - var graphWidth = $(chartWrapperElmId).width() - 50; - var temperatureGraphConfig = { - element: document.getElementById('chart-temperature'), - width: graphWidth, - height: 400, - strokeWidth: 2, - renderer: 'line', - interpolation: 'linear', - unstack: true, - stack: false, - xScale: d3.time.scale(), - padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2}, - series: [] - }; - - var coffeelevelGraphConfig = { - element: document.getElementById('chart-coffeelevel'), - width: graphWidth, - height: 400, - strokeWidth: 2, - renderer: 'line', - interpolation: 'linear', - unstack: true, - stack: false, - xScale: d3.time.scale(), - padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2}, - series: [] - }; - - if (devices) { - for (var i = 0; i < devices.length; i++) { - temperatureGraphConfig['series'].push( - { - 'color': palette.color(), - 'data': [{ - x: parseInt(new Date().getTime() / 1000), - y: 0 - }], - 'name': devices[i].name - }); - - coffeelevelGraphConfig['series'].push( - { - 'color': palette.color(), - 'data': [{ - x: parseInt(new Date().getTime() / 1000), - y: 0 - }], - 'name': devices[i].name - }); - } - } else { - temperatureGraphConfig['series'].push( - { - 'color': palette.color(), - 'data': [{ - x: parseInt(new Date().getTime() / 1000), - y: 0 - }], - 'name': $('#connectedcup-details').data('devicename') - }); - coffeelevelGraphConfig['series'].push( - { - 'color': palette.color(), - 'data': [{ - x: parseInt(new Date().getTime() / 1000), - y: 0 - }], - 'name': $('#connectedcup-details').data('devicename') - }); - } - - var temperatureGraph = new Rickshaw.Graph(temperatureGraphConfig); - var coffeelevelGraph = new Rickshaw.Graph(coffeelevelGraphConfig); - - temperatureGraph.render(); - coffeelevelGraph.render - - var xAxisTemepature = new Rickshaw.Graph.Axis.Time({ - graph: temperatureGraph - }); - - xAxisTemepature.render(); - - var xAxisCoffeelevel = new Rickshaw.Graph.Axis.Time({ - graph: coffeelevelGraph - }); - - xAxisCoffeelevel.render(); - - var yAxisTemperature = new Rickshaw.Graph.Axis.Y({ - graph: temperatureGraph, - orientation: 'left', - element: document.getElementById('y_axis-temperature'), - width: 40, - height: 410 - }); - - yAxisTemperature.render(); - - var yAxisCoffeelevel = new Rickshaw.Graph.Axis.Y({ - graph: coffeelevelGraph, - orientation: 'left', - element: document.getElementById('y_axis-coffeelevel'), - width: 40, - height: 410 - }); - - yAxisCoffeelevel.render(); - - var slider = new Rickshaw.Graph.RangeSlider.Preview({ - graph: temperatureGraph, - element: document.getElementById('slider-temperature') - }); - - var legend = new Rickshaw.Graph.Legend({ - graph: temperatureGraph, - element: document.getElementById('legend-temperature') - }); - - var sliderCoffee = new Rickshaw.Graph.RangeSlider.Preview({ - graph: coffeelevelGraph, - element: document.getElementById('slider-coffeelevel') - }); - - var legendCoffee = new Rickshaw.Graph.Legend({ - graph: coffeelevelGraph, - element: document.getElementById('legend-coffeelevel') - }); - - var hoverDetail = new Rickshaw.Graph.HoverDetail({ - graph: temperatureGraph, - formatter: function (series, x, y) { - var date = '' + - moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + ''; - var swatch = ''; - return swatch + series.name + ': ' + parseInt(y) + '
' + date; - } - }); - - var hoverDetailCoffeelevel = new Rickshaw.Graph.HoverDetail({ - graph: coffeelevelGraph, - formatter: function (series, x, y) { - var date = '' + - moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + ''; - var swatch = ''; - return swatch + series.name + ': ' + parseInt(y) + '
' + date; - } - }); - - var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({ - graph: temperatureGraph, - legend: legend - }); - - var order = new Rickshaw.Graph.Behavior.Series.Order({ - graph: temperatureGraph, - legend: legend - }); - - var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({ - graph: temperatureGraph, - legend: legend - }); - - var shelvingCoffee = new Rickshaw.Graph.Behavior.Series.Toggle({ - graph: coffeelevelGraph, - legend: legendCoffee - }); - - var orderCoffee = new Rickshaw.Graph.Behavior.Series.Order({ - graph: coffeelevelGraph, - legend: legendCoffee - }); - - var highlighterCoffee = new Rickshaw.Graph.Behavior.Series.Highlight({ - graph: coffeelevelGraph, - legend: legendCoffee - }); - - var deviceIndex = 0; - - if (devices) { - getData(); - } else { - var backendApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + '/sensors/temperature' - + '?from=' + from + '&to=' + to; - var successCallback = function (data) { - if (data) { - drawTemperatureLineGraph(JSON.parse(data)); - } - }; - invokerUtil.get(backendApiUrl, successCallback, function (message) {}); - - var coffeeLevelApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + '/sensors/coffeelevel' - + '?from=' + from + '&to=' + to; - var successCallbackCoffeeLevel = function (data) { - if (data) { - drawCoffeeLevelLineGraph(JSON.parse(data)); - } - }; - invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) { - console.log(message); - }); - } - - function getData() { - if (deviceIndex >= devices.length) { - return; - } - var backendApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + devices[deviceIndex].deviceIdentifier - + '/sensors/temperature?from=' + from + '&to=' + to; - var successCallback = function (data) { - if (data) { - drawTemperatureLineGraph(JSON.parse(data)); - } - deviceIndex++; - getData(); - }; - invokerUtil.get(backendApiUrl, successCallback, function (message) { - console.log(message); - deviceIndex++; - getData(); - }); - var coffeeLevelApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + devices[deviceIndex].deviceIdentifier - + '/sensors/coffeelevel?from=' + from + '&to=' + to; - - var successCallbackCoffeeLevel = function (data) { - if (data) { - drawCoffeeLevelLineGraph(JSON.parse(data)); - } - }; - invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) { - console.log(message); - }); - } - - function drawTemperatureLineGraph(data) { - if (data.length === 0 || data.length === undefined) { - return; - } - - var chartData = []; - for (var i = 0; i < data.length; i++) { - chartData.push( - { - x: parseInt(data[i].values.time) - tzOffset, - y: parseInt(data[i].values.temperature) - } - ); - } - - temperatureGraphConfig.series[deviceIndex].data = chartData; - temperatureGraph.update(); - } - - function drawCoffeeLevelLineGraph(data) { - if (data.length === 0 || data.length === undefined) { - return; - } - - var chartData = []; - for (var i = 0; i < data.length; i++) { - chartData.push( - { - x: parseInt(data[i].values.time) - tzOffset, - y: parseInt(data[i].values.coffeelevel) - } - ); - } - - coffeelevelGraphConfig.series[deviceIndex].data = chartData; - coffeelevelGraph.update(); - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.hbs b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.hbs deleted file mode 100644 index 0beb6b45..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.hbs +++ /dev/null @@ -1,84 +0,0 @@ -{{! - Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - - WSO2 Inc. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -}} - -{{#zone "topCss"}} - -{{/zone}} - -{{#zone "device-thumbnail"}} - -{{/zone}} - -{{#zone "device-details-header"}} -

- {{device.enrolmentInfo.owner}}'s {{device.name}} - - - -

-

Ownership - {{device.enrolmentInfo.ownership}}

-

Device is - - {{#equal device.enrolmentInfo.status "ACTIVE"}}Active{{/equal}} - {{#equal device.enrolmentInfo.status "INACTIVE"}}Inactive{{/equal}} - {{#equal device.enrolmentInfo.status "BLOCKED"}}Blocked{{/equal}} - {{#equal device.enrolmentInfo.status "REMOVED"}}Removed{{/equal}} - {{#equal device.enrolmentInfo.status "UNREACHABLE"}}Unreachable{{/equal}} - -

-{{/zone}} - - -{{#zone "device-opetations"}} -
-
-

Device Operations

-
- -
-{{/zone}} - -{{#zone "device-view-tabs"}} -
  • Device - Statistics -
  • -{{/zone}} - -{{#zone "device-view-tab-contents"}} - -
    -
    Device Statistics
    - {{unit "cdmf.unit.device.type.connectedcup.realtime.analytics-view" device=device}} -
    - -{{/zone}} diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.js b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.js deleted file mode 100644 index 63ebf3d2..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -function onRequest(context) { - var deviceType = context.uriParams.deviceType; - var deviceId = request.getParameter('id'); - - if (deviceType && deviceId) { - var deviceModule = require("/app/modules/business-controllers/device.js").deviceModule; - var deviceData = deviceModule.viewDevice(deviceType, deviceId); - - if (deviceData && deviceData.status != 'error') { - var device = deviceData.content; - var constants = require('/app/modules/constants.js'); - var tokenPair = JSON.parse(session.get(constants.TOKEN_PAIR)); - if (tokenPair) { - device.accessToken = tokenPair.accessToken; - } - var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; - device.ip = devicemgtProps['httpsWebURL']; - return {'device': deviceData.content}; - } - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.json b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.json deleted file mode 100644 index 9eecd8f5..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/device-view.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "version": "1.0.0" -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/public/images/thumb.png b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/public/images/thumb.png deleted file mode 100644 index 7dda85e4..00000000 Binary files a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view/public/images/thumb.png and /dev/null differ diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.hbs b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.hbs deleted file mode 100644 index 9f73a6ce..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.hbs +++ /dev/null @@ -1,64 +0,0 @@ -{{! - Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - - WSO2 Inc. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -}} -{{unit "cdmf.unit.lib.rickshaw-graph"}} - -
    -
    -
    Temperature
    -
    -
    -
    -
    -
    -
    Time
    -
    -
    - -
    -
    -
    Coffee Level
    -
    -
    -
    -
    -
    -
    Time
    -
    -
    - - - - - - - - - - View Device Analytics - - -
    - Realtime Analytics for $sensorType not available. Failed to connect to the websocket. Please make sure; '$webSocketURL' is available and re-try again. -
    - -{{#zone "bottomJs"}} - {{js "js/moment.min.js"}} - {{js "js/socket.io.min.js"}} - {{js "js/device-stats.js"}} -{{/zone}} diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.js b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.js deleted file mode 100644 index 2ef444f6..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -function onRequest(context) { - var log = new Log("stats.js"); - var carbonServer = require("carbon").server; - var device = context.unit.params.device; - var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; - var constants = require("/app/modules/constants.js"); - var websocketEndpoint = devicemgtProps["wssURL"].replace("https", "wss"); - var jwtService = carbonServer.osgiService( - 'org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService'); - var jwtClient = jwtService.getJWTClient(); - var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]); - var token = ""; - if (encodedClientKeys) { - var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"]; - var resp = tokenUtil.decode(encodedClientKeys).split(":"); - var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {}); - if (tokenPair) { - token = tokenPair.accessToken; - } - websocketEndpointTemperature = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?" - + "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type+ "&websocketToken=" + token; - websocketEndpointCoffeeLevel = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.coffeelevel/1.0.0?" - + "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type+ "&websocketToken=" + token; - var websocketToken= {'name':'websocket-token','value': token, 'path':'/', "maxAge":18000}; - response.addCookie(websocketToken); - } - return { - "device": device, - "websocketEndpointTemperature": websocketEndpointTemperature, - "websocketEndpointCoffeeLevel": websocketEndpointCoffeeLevel - }; -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.json b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.json deleted file mode 100644 index 688e9398..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/analytics-view.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "version": "1.0.0" -} \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/device-stats.js b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/device-stats.js deleted file mode 100644 index 669fc0ef..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/device-stats.js +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var wsConnectionTemperature; -var wsConnectionCoffeeLevel; -var graphForSensorTypeTemperature; -var graphForSensorTypeCoffeeLevel; -var chartDataSensorTypeTemperature = []; -var chartDataSensorTypeCoffeeLevel = []; - -var palette = new Rickshaw.Color.Palette({scheme: "classic9"}); - -$(window).load(function () { - drawGraph(wsConnectionTemperature, "#div-chartTemperature", "y_axisTemperature", "chartTemperature", chartDataSensorTypeTemperature - , graphForSensorTypeTemperature); - var millisecondsToWait = 1000; - setTimeout(function() { - drawGraph(wsConnectionCoffeeLevel, "#div-chartCoffeeLevel", "y_axisCoffeeLevel", "chartCoffeeLevel", chartDataSensorTypeCoffeeLevel - , graphForSensorTypeCoffeeLevel); - }, millisecondsToWait); -}); - -window.onbeforeunload = function() { - disconnect(wsConnectionTemperature); - disconnect(wsConnectionCoffeeLevel); -}; - -function drawGraph(wsConnection, placeHolder, yAxis, chat, chartData, graph) { - var tNow = new Date().getTime() / 1000; - for (var i = 0; i < 30; i++) { - chartData.push({ - x: tNow - (30 - i) * 15, - y: parseFloat(0) - }); - } - - graph = new Rickshaw.Graph({ - element: document.getElementById(chat), - width: $(placeHolder).width() - 50, - height: 300, - renderer: "line", - interpolation: "linear", - padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2}, - xScale: d3.time.scale(), - series: [{ - 'color': palette.color(), - 'data': chartData, - 'name': "SensorValue" - }] - }); - - graph.render(); - - var xAxis = new Rickshaw.Graph.Axis.Time({ - graph: graph - }); - - xAxis.render(); - - new Rickshaw.Graph.Axis.Y({ - graph: graph, - orientation: 'left', - height: 300, - tickFormat: Rickshaw.Fixtures.Number.formatKMBT, - element: document.getElementById(yAxis) - }); - - new Rickshaw.Graph.HoverDetail({ - graph: graph, - formatter: function (series, x, y) { - var date = '' + moment.unix(x * 1000).format('Do MMM YYYY h:mm:ss a') + ''; - var swatch = ''; - return swatch + series.name + ": " + parseInt(y) + '
    ' + date; - } - }); - - var sensorType = $(placeHolder).attr("data-sensorType"); - var websocketUrl = $(placeHolder).attr("data-websocketurl"); - connect(wsConnection, websocketUrl, chartData, graph, sensorType); - -} - -//websocket connection -function connect(wsConnection, target, chartData, graph, sensorType) { - if ('WebSocket' in window) { - wsConnection = new WebSocket(target); - } else if ('MozWebSocket' in window) { - wsConnection = new MozWebSocket(target); - } else { - console.log('WebSocket is not supported by this browser.'); - } - if (wsConnection) { - wsConnection.onmessage = function (event) { - var dataPoint = JSON.parse(event.data); - chartData.push({ - x: parseInt(dataPoint[4]) / 1000, - y: parseFloat(dataPoint[5]) - }); - chartData.shift(); - graph.update(); - }; - wsConnection.onerror = function (event) { - var websocketURL = event.currentTarget.url; - websocketURL = websocketURL.replace("wss://","https://"); - var uriParts = websocketURL.split("/"); - websocketURL = uriParts[0] + "//" + uriParts[2]; - var errorMsg = $("#websocker-onerror").html(); - errorMsg = errorMsg.replace(new RegExp('\\$sensorType', 'g'), sensorType); - errorMsg = errorMsg.replace(new RegExp('\\$webSocketURL', 'g'), websocketURL); - $(graph.element).parent().html("
    " + errorMsg + "
    "); - $(graph.element).hide(); - }; - } - if (sensorType == "temperature") { - wsConnectionTemperature = wsConnection; - } else { - wsConnectionCoffeeLevel = wsConnection; - } -} - -function disconnect(wsConnection) { - if (wsConnection != null) { - wsConnection.close(); - wsConnection = null; - } -} diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/moment.min.js b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/moment.min.js deleted file mode 100644 index d0b48f73..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/moment.min.js +++ /dev/null @@ -1,7 +0,0 @@ -//! moment.js -//! version : 2.10.2 -//! authors : Tim Wood, Iskren Chernev, Moment.js contributors -//! license : MIT -//! momentjs.com -!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function(){"use strict";function a(){return Ac.apply(null,arguments)}function b(a){Ac=a}function c(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}function e(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function f(a,b){var c,d=[];for(c=0;c0)for(c in Cc)d=Cc[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function m(b){l(this,b),this._d=new Date(+b._d),Dc===!1&&(Dc=!0,a.updateOffset(this),Dc=!1)}function n(a){return a instanceof m||null!=a&&g(a,"_isAMomentObject")}function o(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function p(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&o(a[d])!==o(b[d]))&&g++;return g+f}function q(){}function r(a){return a?a.toLowerCase().replace("_","-"):a}function s(a){for(var b,c,d,e,f=0;f0;){if(d=t(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&p(e,c,!0)>=b-1)break;b--}f++}return null}function t(a){var b=null;if(!Ec[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Bc._abbr,require("./locale/"+a),u(b)}catch(c){}return Ec[a]}function u(a,b){var c;return a&&(c="undefined"==typeof b?w(a):v(a,b),c&&(Bc=c)),Bc._abbr}function v(a,b){return null!==b?(b.abbr=a,Ec[a]||(Ec[a]=new q),Ec[a].set(b),u(a),Ec[a]):(delete Ec[a],null)}function w(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Bc;if(!d(a)){if(b=t(a))return b;a=[a]}return s(a)}function x(a,b){var c=a.toLowerCase();Fc[c]=Fc[c+"s"]=Fc[b]=a}function y(a){return"string"==typeof a?Fc[a]||Fc[a.toLowerCase()]:void 0}function z(a){var b,c,d={};for(c in a)g(a,c)&&(b=y(c),b&&(d[b]=a[c]));return d}function A(b,c){return function(d){return null!=d?(C(this,b,d),a.updateOffset(this,c),this):B(this,b)}}function B(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function C(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function D(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=y(a),"function"==typeof this[a])return this[a](b);return this}function E(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.lengthb;b++)d[b]=Jc[d[b]]?Jc[d[b]]:G(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function I(a,b){return a.isValid()?(b=J(b,a.localeData()),Ic[b]||(Ic[b]=H(b)),Ic[b](a)):a.localeData().invalidDate()}function J(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Hc.lastIndex=0;d>=0&&Hc.test(a);)a=a.replace(Hc,c),Hc.lastIndex=0,d-=1;return a}function K(a,b,c){Yc[a]="function"==typeof b?b:function(a){return a&&c?c:b}}function L(a,b){return g(Yc,a)?Yc[a](b._strict,b._locale):new RegExp(M(a))}function M(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function N(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=o(a)}),c=0;cd;d++){if(e=i([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function U(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),Q(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function V(b){return null!=b?(U(this,b),a.updateOffset(this,!0),this):B(this,"Month")}function W(){return Q(this.year(),this.month())}function X(a){var b,c=a._a;return c&&-2===a._pf.overflow&&(b=c[_c]<0||c[_c]>11?_c:c[ad]<1||c[ad]>Q(c[$c],c[_c])?ad:c[bd]<0||c[bd]>24||24===c[bd]&&(0!==c[cd]||0!==c[dd]||0!==c[ed])?bd:c[cd]<0||c[cd]>59?cd:c[dd]<0||c[dd]>59?dd:c[ed]<0||c[ed]>999?ed:-1,a._pf._overflowDayOfYear&&($c>b||b>ad)&&(b=ad),a._pf.overflow=b),a}function Y(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function Z(a,b){var c=!0;return h(function(){return c&&(Y(a),c=!1),b.apply(this,arguments)},b)}function $(a,b){hd[a]||(Y(b),hd[a]=!0)}function _(a){var b,c,d=a._i,e=id.exec(d);if(e){for(a._pf.iso=!0,b=0,c=jd.length;c>b;b++)if(jd[b][1].exec(d)){a._f=jd[b][0]+(e[6]||" ");break}for(b=0,c=kd.length;c>b;b++)if(kd[b][1].exec(d)){a._f+=kd[b][0];break}d.match(Vc)&&(a._f+="Z"),sa(a)}else a._isValid=!1}function aa(b){var c=ld.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(_(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ba(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function ca(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function da(a){return ea(a)?366:365}function ea(a){return a%4===0&&a%100!==0||a%400===0}function fa(){return ea(this.year())}function ga(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=za(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ha(a){return ga(a,this._week.dow,this._week.doy).week}function ia(){return this._week.dow}function ja(){return this._week.doy}function ka(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function la(a){var b=ga(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function ma(a,b,c,d,e){var f,g,h=ca(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:da(a-1)+g}}function na(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function oa(a,b,c){return null!=a?a:null!=b?b:c}function pa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function qa(a){var b,c,d,e,f=[];if(!a._d){for(d=pa(a),a._w&&null==a._a[ad]&&null==a._a[_c]&&ra(a),a._dayOfYear&&(e=oa(a._a[$c],d[$c]),a._dayOfYear>da(e)&&(a._pf._overflowDayOfYear=!0),c=ca(e,0,a._dayOfYear),a._a[_c]=c.getUTCMonth(),a._a[ad]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[bd]&&0===a._a[cd]&&0===a._a[dd]&&0===a._a[ed]&&(a._nextDay=!0,a._a[bd]=0),a._d=(a._useUTC?ca:ba).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[bd]=24)}}function ra(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=oa(b.GG,a._a[$c],ga(za(),1,4).year),d=oa(b.W,1),e=oa(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=oa(b.gg,a._a[$c],ga(za(),f,g).year),d=oa(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=ma(c,d,e,g,f),a._a[$c]=h.year,a._dayOfYear=h.dayOfYear}function sa(b){if(b._f===a.ISO_8601)return void _(b);b._a=[],b._pf.empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,j=0;for(e=J(b._f,b._locale).match(Gc)||[],c=0;c0&&b._pf.unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),j+=d.length),Jc[f]?(d?b._pf.empty=!1:b._pf.unusedTokens.push(f),P(f,d,b)):b._strict&&!d&&b._pf.unusedTokens.push(f);b._pf.charsLeftOver=i-j,h.length>0&&b._pf.unusedInput.push(h),b._pf.bigHour===!0&&b._a[bd]<=12&&(b._pf.bigHour=void 0),b._a[bd]=ta(b._locale,b._a[bd],b._meridiem),qa(b),X(b)}function ta(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function ua(a){var b,d,e,f,g;if(0===a._f.length)return a._pf.invalidFormat=!0,void(a._d=new Date(0/0));for(f=0;fg)&&(e=g,d=b));h(a,d||b)}function va(a){if(!a._d){var b=z(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],qa(a)}}function wa(a){var b,c=a._i,e=a._f;return a._locale=a._locale||w(a._l),null===c||void 0===e&&""===c?k({nullInput:!0}):("string"==typeof c&&(a._i=c=a._locale.preparse(c)),n(c)?new m(X(c)):(d(e)?ua(a):e?sa(a):xa(a),b=new m(X(a)),b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b))}function xa(b){var c=b._i;void 0===c?b._d=new Date:e(c)?b._d=new Date(+c):"string"==typeof c?aa(b):d(c)?(b._a=f(c.slice(0),function(a){return parseInt(a,10)}),qa(b)):"object"==typeof c?va(b):"number"==typeof c?b._d=new Date(c):a.createFromInputFallback(b)}function ya(a,b,d,e,f){var g={};return"boolean"==typeof d&&(e=d,d=void 0),g._isAMomentObject=!0,g._useUTC=g._isUTC=f,g._l=d,g._i=a,g._f=b,g._strict=e,g._pf=c(),wa(g)}function za(a,b,c,d){return ya(a,b,c,d,!1)}function Aa(a,b){var c,e;if(1===b.length&&d(b[0])&&(b=b[0]),!b.length)return za();for(c=b[0],e=1;ea&&(a=-a,c="-"),c+E(~~(a/60),2)+b+E(~~a%60,2)})}function Ga(a){var b=(a||"").match(Vc)||[],c=b[b.length-1]||[],d=(c+"").match(qd)||["-",0,0],e=+(60*d[1])+o(d[2]);return"+"===d[0]?e:-e}function Ha(b,c){var d,f;return c._isUTC?(d=c.clone(),f=(n(b)||e(b)?+b:+za(b))-+d,d._d.setTime(+d._d+f),a.updateOffset(d,!1),d):za(b).local();return c._isUTC?za(b).zone(c._offset||0):za(b).local()}function Ia(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Ja(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ga(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ia(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?Za(this,Ua(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ia(this)}function Ka(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function La(a){return this.utcOffset(0,a)}function Ma(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ia(this),"m")),this}function Na(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ga(this._i)),this}function Oa(a){return a=a?za(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Pa(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Qa(){if(this._a){var a=this._isUTC?i(this._a):za(this._a);return this.isValid()&&p(this._a,a.toArray())>0}return!1}function Ra(){return!this._isUTC}function Sa(){return this._isUTC}function Ta(){return this._isUTC&&0===this._offset}function Ua(a,b){var c,d,e,f=a,h=null;return Ea(a)?f={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(f={},b?f[b]=a:f.milliseconds=a):(h=rd.exec(a))?(c="-"===h[1]?-1:1,f={y:0,d:o(h[ad])*c,h:o(h[bd])*c,m:o(h[cd])*c,s:o(h[dd])*c,ms:o(h[ed])*c}):(h=sd.exec(a))?(c="-"===h[1]?-1:1,f={y:Va(h[2],c),M:Va(h[3],c),d:Va(h[4],c),h:Va(h[5],c),m:Va(h[6],c),s:Va(h[7],c),w:Va(h[8],c)}):null==f?f={}:"object"==typeof f&&("from"in f||"to"in f)&&(e=Xa(za(f.from),za(f.to)),f={},f.ms=e.milliseconds,f.M=e.months),d=new Da(f),Ea(a)&&g(a,"_locale")&&(d._locale=a._locale),d}function Va(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function Wa(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function Xa(a,b){var c;return b=Ha(b,a),a.isBefore(b)?c=Wa(a,b):(c=Wa(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function Ya(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||($(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Ua(c,d),Za(this,e,a),this}}function Za(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&C(b,"Date",B(b,"Date")+g*d),h&&U(b,B(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function $a(a){var b=a||za(),c=Ha(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,za(b)))}function _a(){return new m(this)}function ab(a,b){var c;return b=y("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=n(a)?a:za(a),+this>+a):(c=n(a)?+a:+za(a),c<+this.clone().startOf(b))}function bb(a,b){var c;return b=y("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=n(a)?a:za(a),+a>+this):(c=n(a)?+a:+za(a),+this.clone().endOf(b)a?Math.ceil(a):Math.floor(a)}function fb(a,b,c){var d,e,f=Ha(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=y(b),"year"===b||"month"===b||"quarter"===b?(e=gb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:eb(e)}function gb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function hb(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function ib(){var a=this.clone().utc();return 0b;b++)if(this._weekdaysParse[b]||(c=za([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Jb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Eb(a,this.localeData()),this.add(a-b,"d")):b}function Kb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Lb(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Mb(a,b){F(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Nb(a,b){return b._meridiemParse}function Ob(a){return"p"===(a+"").toLowerCase().charAt(0)}function Pb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Qb(a){F(0,[a,3],0,"millisecond")}function Rb(){return this._isUTC?"UTC":""}function Sb(){return this._isUTC?"Coordinated Universal Time":""}function Tb(a){return za(1e3*a)}function Ub(){return za.apply(null,arguments).parseZone()}function Vb(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function Wb(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b}function Xb(){return this._invalidDate}function Yb(a){return this._ordinal.replace("%d",a)}function Zb(a){return a}function $b(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function _b(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function ac(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function bc(a,b,c,d){var e=w(),f=i().set(d,b);return e[c](f,a)}function cc(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return bc(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=bc(a,f,c,e);return g}function dc(a,b){return cc(a,b,"months",12,"month")}function ec(a,b){return cc(a,b,"monthsShort",12,"month")}function fc(a,b){return cc(a,b,"weekdays",7,"day")}function gc(a,b){return cc(a,b,"weekdaysShort",7,"day")}function hc(a,b){return cc(a,b,"weekdaysMin",7,"day")}function ic(){var a=this._data;return this._milliseconds=Od(this._milliseconds),this._days=Od(this._days),this._months=Od(this._months),a.milliseconds=Od(a.milliseconds),a.seconds=Od(a.seconds),a.minutes=Od(a.minutes),a.hours=Od(a.hours),a.months=Od(a.months),a.years=Od(a.years),this}function jc(a,b,c,d){var e=Ua(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function kc(a,b){return jc(this,a,b,1)}function lc(a,b){return jc(this,a,b,-1)}function mc(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;return g.milliseconds=d%1e3,a=eb(d/1e3),g.seconds=a%60,b=eb(a/60),g.minutes=b%60,c=eb(b/60),g.hours=c%24,e+=eb(c/24),h=eb(nc(e)),e-=eb(oc(h)),f+=eb(e/30),e%=30,h+=eb(f/12),f%=12,g.days=e,g.months=f,g.years=h,this}function nc(a){return 400*a/146097}function oc(a){return 146097*a/400}function pc(a){var b,c,d=this._milliseconds;if(a=y(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+12*nc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(oc(this._months/12)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 24*b*60+d/6e4;case"second":return 24*b*60*60+d/1e3;case"millisecond":return Math.floor(24*b*60*60*1e3)+d;default:throw new Error("Unknown unit "+a)}}function qc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*o(this._months/12)}function rc(a){return function(){return this.as(a)}}function sc(a){return a=y(a),this[a+"s"]()}function tc(a){return function(){return this._data[a]}}function uc(){return eb(this.days()/7)}function vc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function wc(a,b,c){var d=Ua(a).abs(),e=ce(d.as("s")),f=ce(d.as("m")),g=ce(d.as("h")),h=ce(d.as("d")),i=ce(d.as("M")),j=ce(d.as("y")),k=e0,k[4]=c,vc.apply(null,k)}function xc(a,b){return void 0===de[a]?!1:void 0===b?de[a]:(de[a]=b,!0)}function yc(a){var b=this.localeData(),c=wc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function zc(){var a=ee(this.years()),b=ee(this.months()),c=ee(this.days()),d=ee(this.hours()),e=ee(this.minutes()),f=ee(this.seconds()+this.milliseconds()/1e3),g=this.asSeconds();return g?(0>g?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"}var Ac,Bc,Cc=a.momentProperties=[],Dc=!1,Ec={},Fc={},Gc=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Hc=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Ic={},Jc={},Kc=/\d/,Lc=/\d\d/,Mc=/\d{3}/,Nc=/\d{4}/,Oc=/[+-]?\d{6}/,Pc=/\d\d?/,Qc=/\d{1,3}/,Rc=/\d{1,4}/,Sc=/[+-]?\d{1,6}/,Tc=/\d+/,Uc=/[+-]?\d+/,Vc=/Z|[+-]\d\d:?\d\d/gi,Wc=/[+-]?\d+(\.\d{1,3})?/,Xc=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Yc={},Zc={},$c=0,_c=1,ad=2,bd=3,cd=4,dd=5,ed=6;F("M",["MM",2],"Mo",function(){return this.month()+1}),F("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),F("MMMM",0,0,function(a){return this.localeData().months(this,a)}),x("month","M"),K("M",Pc),K("MM",Pc,Lc),K("MMM",Xc),K("MMMM",Xc),N(["M","MM"],function(a,b){b[_c]=o(a)-1}),N(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[_c]=e:c._pf.invalidMonth=a});var fd="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),gd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),hd={};a.suppressDeprecationWarnings=!1;var id=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,jd=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],kd=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],ld=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=Z("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),F(0,["YY",2],0,function(){return this.year()%100}),F(0,["YYYY",4],0,"year"),F(0,["YYYYY",5],0,"year"),F(0,["YYYYYY",6,!0],0,"year"),x("year","y"),K("Y",Uc),K("YY",Pc,Lc),K("YYYY",Rc,Nc),K("YYYYY",Sc,Oc),K("YYYYYY",Sc,Oc),N(["YYYY","YYYYY","YYYYYY"],$c),N("YY",function(b,c){c[$c]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return o(a)+(o(a)>68?1900:2e3)};var md=A("FullYear",!1);F("w",["ww",2],"wo","week"),F("W",["WW",2],"Wo","isoWeek"),x("week","w"),x("isoWeek","W"),K("w",Pc),K("ww",Pc,Lc),K("W",Pc),K("WW",Pc,Lc),O(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=o(a)});var nd={dow:0,doy:6};F("DDD",["DDDD",3],"DDDo","dayOfYear"),x("dayOfYear","DDD"),K("DDD",Qc),K("DDDD",Mc),N(["DDD","DDDD"],function(a,b,c){c._dayOfYear=o(a)}),a.ISO_8601=function(){};var od=Z("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=za.apply(null,arguments);return this>a?this:a}),pd=Z("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=za.apply(null,arguments);return a>this?this:a});Fa("Z",":"),Fa("ZZ",""),K("Z",Vc),K("ZZ",Vc),N(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ga(a)});var qd=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var rd=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,sd=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Ua.fn=Da.prototype;var td=Ya(1,"add"),ud=Ya(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var vd=Z("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});F(0,["gg",2],0,function(){return this.weekYear()%100}),F(0,["GG",2],0,function(){return this.isoWeekYear()%100}),xb("gggg","weekYear"),xb("ggggg","weekYear"),xb("GGGG","isoWeekYear"),xb("GGGGG","isoWeekYear"),x("weekYear","gg"),x("isoWeekYear","GG"),K("G",Uc),K("g",Uc),K("GG",Pc,Lc),K("gg",Pc,Lc),K("GGGG",Rc,Nc),K("gggg",Rc,Nc),K("GGGGG",Sc,Oc),K("ggggg",Sc,Oc),O(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=o(a)}),O(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),F("Q",0,0,"quarter"),x("quarter","Q"),K("Q",Kc),N("Q",function(a,b){b[_c]=3*(o(a)-1)}),F("D",["DD",2],"Do","date"),x("date","D"),K("D",Pc),K("DD",Pc,Lc),K("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),N(["D","DD"],ad),N("Do",function(a,b){b[ad]=o(a.match(Pc)[0],10)});var wd=A("Date",!0);F("d",0,"do","day"),F("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),F("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),F("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),F("e",0,0,"weekday"),F("E",0,0,"isoWeekday"),x("day","d"),x("weekday","e"),x("isoWeekday","E"),K("d",Pc),K("e",Pc),K("E",Pc),K("dd",Xc),K("ddd",Xc),K("dddd",Xc),O(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:c._pf.invalidWeekday=a}),O(["d","e","E"],function(a,b,c,d){b[d]=o(a)});var xd="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),yd="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),zd="Su_Mo_Tu_We_Th_Fr_Sa".split("_");F("H",["HH",2],0,"hour"),F("h",["hh",2],0,function(){return this.hours()%12||12}),Mb("a",!0),Mb("A",!1),x("hour","h"),K("a",Nb),K("A",Nb),K("H",Pc),K("h",Pc),K("HH",Pc,Lc),K("hh",Pc,Lc),N(["H","HH"],bd),N(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),N(["h","hh"],function(a,b,c){b[bd]=o(a),c._pf.bigHour=!0});var Ad=/[ap]\.?m?\.?/i,Bd=A("Hours",!0);F("m",["mm",2],0,"minute"),x("minute","m"),K("m",Pc),K("mm",Pc,Lc),N(["m","mm"],cd);var Cd=A("Minutes",!1);F("s",["ss",2],0,"second"),x("second","s"),K("s",Pc),K("ss",Pc,Lc),N(["s","ss"],dd);var Dd=A("Seconds",!1);F("S",0,0,function(){return~~(this.millisecond()/100)}),F(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Qb("SSS"),Qb("SSSS"),x("millisecond","ms"),K("S",Qc,Kc),K("SS",Qc,Lc),K("SSS",Qc,Mc),K("SSSS",Tc),N(["S","SS","SSS","SSSS"],function(a,b){b[ed]=o(1e3*("0."+a))});var Ed=A("Milliseconds",!1);F("z",0,0,"zoneAbbr"),F("zz",0,0,"zoneName");var Fd=m.prototype;Fd.add=td,Fd.calendar=$a,Fd.clone=_a,Fd.diff=fb,Fd.endOf=pb,Fd.format=jb,Fd.from=kb,Fd.fromNow=lb,Fd.get=D,Fd.invalidAt=wb,Fd.isAfter=ab,Fd.isBefore=bb,Fd.isBetween=cb,Fd.isSame=db,Fd.isValid=ub,Fd.lang=vd,Fd.locale=mb,Fd.localeData=nb,Fd.max=pd,Fd.min=od,Fd.parsingFlags=vb,Fd.set=D,Fd.startOf=ob,Fd.subtract=ud,Fd.toArray=tb,Fd.toDate=sb,Fd.toISOString=ib,Fd.toJSON=ib,Fd.toString=hb,Fd.unix=rb,Fd.valueOf=qb,Fd.year=md,Fd.isLeapYear=fa,Fd.weekYear=zb,Fd.isoWeekYear=Ab,Fd.quarter=Fd.quarters=Db,Fd.month=V,Fd.daysInMonth=W,Fd.week=Fd.weeks=ka,Fd.isoWeek=Fd.isoWeeks=la,Fd.weeksInYear=Cb,Fd.isoWeeksInYear=Bb,Fd.date=wd,Fd.day=Fd.days=Jb,Fd.weekday=Kb,Fd.isoWeekday=Lb,Fd.dayOfYear=na,Fd.hour=Fd.hours=Bd,Fd.minute=Fd.minutes=Cd,Fd.second=Fd.seconds=Dd,Fd.millisecond=Fd.milliseconds=Ed,Fd.utcOffset=Ja,Fd.utc=La,Fd.local=Ma,Fd.parseZone=Na,Fd.hasAlignedHourOffset=Oa,Fd.isDST=Pa,Fd.isDSTShifted=Qa,Fd.isLocal=Ra,Fd.isUtcOffset=Sa,Fd.isUtc=Ta,Fd.isUTC=Ta,Fd.zoneAbbr=Rb,Fd.zoneName=Sb,Fd.dates=Z("dates accessor is deprecated. Use date instead.",wd),Fd.months=Z("months accessor is deprecated. Use month instead",V),Fd.years=Z("years accessor is deprecated. Use year instead",md),Fd.zone=Z("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Ka);var Gd=Fd,Hd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Id={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},Jd="Invalid date",Kd="%d",Ld=/\d{1,2}/,Md={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Nd=q.prototype;Nd._calendar=Hd,Nd.calendar=Vb,Nd._longDateFormat=Id,Nd.longDateFormat=Wb,Nd._invalidDate=Jd,Nd.invalidDate=Xb,Nd._ordinal=Kd,Nd.ordinal=Yb,Nd._ordinalParse=Ld, -Nd.preparse=Zb,Nd.postformat=Zb,Nd._relativeTime=Md,Nd.relativeTime=$b,Nd.pastFuture=_b,Nd.set=ac,Nd.months=R,Nd._months=fd,Nd.monthsShort=S,Nd._monthsShort=gd,Nd.monthsParse=T,Nd.week=ha,Nd._week=nd,Nd.firstDayOfYear=ja,Nd.firstDayOfWeek=ia,Nd.weekdays=Fb,Nd._weekdays=xd,Nd.weekdaysMin=Hb,Nd._weekdaysMin=zd,Nd.weekdaysShort=Gb,Nd._weekdaysShort=yd,Nd.weekdaysParse=Ib,Nd.isPM=Ob,Nd._meridiemParse=Ad,Nd.meridiem=Pb,u("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===o(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=Z("moment.lang is deprecated. Use moment.locale instead.",u),a.langData=Z("moment.langData is deprecated. Use moment.localeData instead.",w);var Od=Math.abs,Pd=rc("ms"),Qd=rc("s"),Rd=rc("m"),Sd=rc("h"),Td=rc("d"),Ud=rc("w"),Vd=rc("M"),Wd=rc("y"),Xd=tc("milliseconds"),Yd=tc("seconds"),Zd=tc("minutes"),$d=tc("hours"),_d=tc("days"),ae=tc("months"),be=tc("years"),ce=Math.round,de={s:45,m:45,h:22,d:26,M:11},ee=Math.abs,fe=Da.prototype;fe.abs=ic,fe.add=kc,fe.subtract=lc,fe.as=pc,fe.asMilliseconds=Pd,fe.asSeconds=Qd,fe.asMinutes=Rd,fe.asHours=Sd,fe.asDays=Td,fe.asWeeks=Ud,fe.asMonths=Vd,fe.asYears=Wd,fe.valueOf=qc,fe._bubble=mc,fe.get=sc,fe.milliseconds=Xd,fe.seconds=Yd,fe.minutes=Zd,fe.hours=$d,fe.days=_d,fe.weeks=uc,fe.months=ae,fe.years=be,fe.humanize=yc,fe.toISOString=zc,fe.toString=zc,fe.toJSON=zc,fe.locale=mb,fe.localeData=nb,fe.toIsoString=Z("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",zc),fe.lang=vd,F("X",0,0,"unix"),F("x",0,0,"valueOf"),K("x",Uc),K("X",Wc),N("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),N("x",function(a,b,c){c._d=new Date(o(a))}),a.version="2.10.2",b(za),a.fn=Gd,a.min=Ba,a.max=Ca,a.utc=i,a.unix=Tb,a.months=dc,a.isDate=e,a.locale=u,a.invalid=k,a.duration=Ua,a.isMoment=n,a.weekdays=fc,a.parseZone=Ub,a.localeData=w,a.isDuration=Ea,a.monthsShort=ec,a.weekdaysMin=hc,a.defineLocale=v,a.weekdaysShort=gc,a.normalizeUnits=y,a.relativeTimeThreshold=xc;var ge=a;return ge}); \ No newline at end of file diff --git a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/socket.io.min.js b/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/socket.io.min.js deleted file mode 100644 index 7e870c98..00000000 --- a/modules/distribution/src/core/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.realtime.analytics-view/public/js/socket.io.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! Socket.IO.min.js build:0.9.16, production. Copyright(c) 2011 LearnBoost MIT Licensed */ -var io="undefined"==typeof module?{}:module.exports;(function(){(function(a,b){var c=a;c.version="0.9.16",c.protocol=1,c.transports=[],c.j=[],c.sockets={},c.connect=function(a,d){var e=c.util.parseUri(a),f,g;b&&b.location&&(e.protocol=e.protocol||b.location.protocol.slice(0,-1),e.host=e.host||(b.document?b.document.domain:b.location.hostname),e.port=e.port||b.location.port),f=c.util.uniqueUri(e);var h={host:e.host,secure:"https"==e.protocol,port:e.port||("https"==e.protocol?443:80),query:e.query||""};c.util.merge(h,d);if(h["force new connection"]||!c.sockets[f])g=new c.Socket(h);return!h["force new connection"]&&g&&(c.sockets[f]=g),g=g||c.sockets[f],g.of(e.path.length>1?e.path:"")}})("object"==typeof module?module.exports:this.io={},this),function(a,b){var c=a.util={},d=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];c.parseUri=function(a){var b=d.exec(a||""),c={},f=14;while(f--)c[e[f]]=b[f]||"";return c},c.uniqueUri=function(a){var c=a.protocol,d=a.host,e=a.port;return"document"in b?(d=d||document.domain,e=e||(c=="https"&&document.location.protocol!=="https:"?443:document.location.port)):(d=d||"localhost",!e&&c=="https"&&(e=443)),(c||"http")+"://"+d+":"+(e||80)},c.query=function(a,b){var d=c.chunkQuery(a||""),e=[];c.merge(d,c.chunkQuery(b||""));for(var f in d)d.hasOwnProperty(f)&&e.push(f+"="+d[f]);return e.length?"?"+e.join("&"):""},c.chunkQuery=function(a){var b={},c=a.split("&"),d=0,e=c.length,f;for(;db.length?a:b,f=a.length>b.length?b:a;for(var g=0,h=f.length;g0&&a.splice(0,1)[0]!=c.transport.name);a.length?h(a):c.publish("connect_failed")}}},c.options["connect timeout"]))})}c.sessionid=d,c.closeTimeout=f*1e3,c.heartbeatTimeout=e*1e3,c.transports||(c.transports=c.origTransports=g?b.util.intersect(g.split(","),c.options.transports):c.options.transports),c.setHeartbeatTimeout(),h(c.transports),c.once("connect",function(){clearTimeout(c.connectTimeoutTimer),a&&typeof a=="function"&&a()})}),this},d.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);if(this.transport&&!this.transport.heartbeats())return;var a=this;this.heartbeatTimeoutTimer=setTimeout(function(){a.transport.onClose()},this.heartbeatTimeout)},d.prototype.packet=function(a){return this.connected&&!this.doBuffer?this.transport.packet(a):this.buffer.push(a),this},d.prototype.setBuffer=function(a){this.doBuffer=a,!a&&this.connected&&this.buffer.length&&(this.options.manualFlush||this.flushBuffer())},d.prototype.flushBuffer=function(){this.transport.payload(this.buffer),this.buffer=[]},d.prototype.disconnect=function(){if(this.connected||this.connecting)this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted");return this},d.prototype.disconnectSync=function(){var a=b.util.request(),c=["http"+(this.options.secure?"s":"")+":/",this.options.host+":"+this.options.port,this.options.resource,b.protocol,"",this.sessionid].join("/")+"/?disconnect=1";a.open("GET",c,!1),a.send(null),this.onDisconnect("booted")},d.prototype.isXDomain=function(){var a=c.location.port||("https:"==c.location.protocol?443:80);return this.options.host!==c.location.hostname||this.options.port!=a},d.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},d.prototype.onOpen=function(){this.open=!0},d.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},d.prototype.onPacket=function(a){this.of(a.endpoint).onPacket(a)},d.prototype.onError=function(a){a&&a.advice&&a.advice==="reconnect"&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",a&&a.reason?a.reason:a)},d.prototype.onDisconnect=function(a){var b=this.connected,c=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1;if(b||c)this.transport.close(),this.transport.clearTimeouts(),b&&(this.publish("disconnect",a),"booted"!=a&&this.options.reconnect&&!this.reconnecting&&this.reconnect())},d.prototype.reconnect=function(){function e(){if(a.connected){for(var b in a.namespaces)a.namespaces.hasOwnProperty(b)&&""!==b&&a.namespaces[b].packet({type:"connect"});a.publish("reconnect",a.transport.name,a.reconnectionAttempts)}clearTimeout(a.reconnectionTimer),a.removeListener("connect_failed",f),a.removeListener("connect",f),a.reconnecting=!1,delete a.reconnectionAttempts,delete a.reconnectionDelay,delete a.reconnectionTimer,delete a.redoTransports,a.options["try multiple transports"]=c}function f(){if(!a.reconnecting)return;if(a.connected)return e();if(a.connecting&&a.reconnecting)return a.reconnectionTimer=setTimeout(f,1e3);a.reconnectionAttempts++>=b?a.redoTransports?(a.publish("reconnect_failed"),e()):(a.on("connect_failed",f),a.options["try multiple transports"]=!0,a.transports=a.origTransports,a.transport=a.getTransport(),a.redoTransports=!0,a.connect()):(a.reconnectionDelay=10:!1},c.xdomainCheck=function(){return!0},typeof window!="undefined"&&(WEB_SOCKET_DISABLE_AUTO_INITIALIZATION=!0),b.transports.push("flashsocket")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);if("undefined"!=typeof window)var swfobject=function(){function A(){if(t)return;try{var a=i.getElementsByTagName("body")[0].appendChild(Q("span"));a.parentNode.removeChild(a)}catch(b){return}t=!0;var c=l.length;for(var d=0;d0)for(var c=0;c0){var g=P(d);if(g)if(S(m[c].swfVersion)&&!(y.wk&&y.wk<312))U(d,!0),e&&(f.success=!0,f.ref=G(d),e(f));else if(m[c].expressInstall&&H()){var h={};h.data=m[c].expressInstall,h.width=g.getAttribute("width")||"0",h.height=g.getAttribute("height")||"0",g.getAttribute("class")&&(h.styleclass=g.getAttribute("class")),g.getAttribute("align")&&(h.align=g.getAttribute("align"));var i={},j=g.getElementsByTagName("param"),k=j.length;for(var l=0;l');h.outerHTML='"+k+"",n[n.length]=c.id,g=P(c.id)}else{var m=Q(b);m.setAttribute("type",e);for(var o in c)c[o]!=Object.prototype[o]&&(o.toLowerCase()=="styleclass"?m.setAttribute("class",c[o]):o.toLowerCase()!="classid"&&m.setAttribute(o,c[o]));for(var p in d)d[p]!=Object.prototype[p]&&p.toLowerCase()!="movie"&&M(m,p,d[p]);h.parentNode.replaceChild(m,h),g=m}}return g}function M(a,b,c){var d=Q("param");d.setAttribute("name",b),d.setAttribute("value",c),a.appendChild(d)}function N(a){var b=P(a);b&&b.nodeName=="OBJECT"&&(y.ie&&y.win?(b.style.display="none",function(){b.readyState==4?O(a):setTimeout(arguments.callee,10)}()):b.parentNode.removeChild(b))}function O(a){var b=P(a);if(b){for(var c in b)typeof b[c]=="function"&&(b[c]=null);b.parentNode.removeChild(b)}}function P(a){var b=null;try{b=i.getElementById(a)}catch(c){}return b}function Q(a){return i.createElement(a)}function R(a,b,c){a.attachEvent(b,c),o[o.length]=[a,b,c]}function S(a){var b=y.pv,c=a.split(".");return c[0]=parseInt(c[0],10),c[1]=parseInt(c[1],10)||0,c[2]=parseInt(c[2],10)||0,b[0]>c[0]||b[0]==c[0]&&b[1]>c[1]||b[0]==c[0]&&b[1]==c[1]&&b[2]>=c[2]?!0:!1}function T(c,d,e,f){if(y.ie&&y.mac)return;var g=i.getElementsByTagName("head")[0];if(!g)return;var h=e&&typeof e=="string"?e:"screen";f&&(v=null,w=null);if(!v||w!=h){var j=Q("style");j.setAttribute("type","text/css"),j.setAttribute("media",h),v=g.appendChild(j),y.ie&&y.win&&typeof i.styleSheets!=a&&i.styleSheets.length>0&&(v=i.styleSheets[i.styleSheets.length-1]),w=h}y.ie&&y.win?v&&typeof v.addRule==b&&v.addRule(c,d):v&&typeof i.createTextNode!=a&&v.appendChild(i.createTextNode(c+" {"+d+"}"))}function U(a,b){if(!x)return;var c=b?"visible":"hidden";t&&P(a)?P(a).style.visibility=c:T("#"+a,"visibility:"+c)}function V(b){var c=/[\\\"<>\.;]/,d=c.exec(b)!=null;return d&&typeof encodeURIComponent!=a?encodeURIComponent(b):b}var a="undefined",b="object",c="Shockwave Flash",d="ShockwaveFlash.ShockwaveFlash",e="application/x-shockwave-flash",f="SWFObjectExprInst",g="onreadystatechange",h=window,i=document,j=navigator,k=!1,l=[D],m=[],n=[],o=[],p,q,r,s,t=!1,u=!1,v,w,x=!0,y=function(){var f=typeof i.getElementById!=a&&typeof i.getElementsByTagName!=a&&typeof i.createElement!=a,g=j.userAgent.toLowerCase(),l=j.platform.toLowerCase(),m=l?/win/.test(l):/win/.test(g),n=l?/mac/.test(l):/mac/.test(g),o=/webkit/.test(g)?parseFloat(g.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):!1,p=!1,q=[0,0,0],r=null;if(typeof j.plugins!=a&&typeof j.plugins[c]==b)r=j.plugins[c].description,r&&(typeof j.mimeTypes==a||!j.mimeTypes[e]||!!j.mimeTypes[e].enabledPlugin)&&(k=!0,p=!1,r=r.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),q[0]=parseInt(r.replace(/^(.*)\..*$/,"$1"),10),q[1]=parseInt(r.replace(/^.*\.(.*)\s.*$/,"$1"),10),q[2]=/[a-zA-Z]/.test(r)?parseInt(r.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0);else if(typeof h[["Active"].concat("Object").join("X")]!=a)try{var s=new(window[["Active"].concat("Object").join("X")])(d);s&&(r=s.GetVariable("$version"),r&&(p=!0,r=r.split(" ")[1].split(","),q=[parseInt(r[0],10),parseInt(r[1],10),parseInt(r[2],10)]))}catch(t){}return{w3:f,pv:q,wk:o,ie:p,win:m,mac:n}}(),z=function(){if(!y.w3)return;(typeof i.readyState!=a&&i.readyState=="complete"||typeof i.readyState==a&&(i.getElementsByTagName("body")[0]||i.body))&&A(),t||(typeof i.addEventListener!=a&&i.addEventListener("DOMContentLoaded",A,!1),y.ie&&y.win&&(i.attachEvent(g,function(){i.readyState=="complete"&&(i.detachEvent(g,arguments.callee),A())}),h==top&&function(){if(t)return;try{i.documentElement.doScroll("left")}catch(a){setTimeout(arguments.callee,0);return}A()}()),y.wk&&function(){if(t)return;if(!/loaded|complete/.test(i.readyState)){setTimeout(arguments.callee,0);return}A()}(),C(A))}(),W=function(){y.ie&&y.win&&window.attachEvent("onunload",function(){var a=o.length;for(var b=0;b= 10.0.0 is required.");return}location.protocol=="file:"&&a.error("WARNING: web-socket-js doesn't work in file:///... URL unless you set Flash Security Settings properly. Open the page via Web server i.e. http://..."),WebSocket=function(a,b,c,d,e){var f=this;f.__id=WebSocket.__nextId++,WebSocket.__instances[f.__id]=f,f.readyState=WebSocket.CONNECTING,f.bufferedAmount=0,f.__events={},b?typeof b=="string"&&(b=[b]):b=[],setTimeout(function(){WebSocket.__addTask(function(){WebSocket.__flash.create(f.__id,a,b,c||null,d||0,e||null)})},0)},WebSocket.prototype.send=function(a){if(this.readyState==WebSocket.CONNECTING)throw"INVALID_STATE_ERR: Web Socket connection has not been established";var b=WebSocket.__flash.send(this.__id,encodeURIComponent(a));return b<0?!0:(this.bufferedAmount+=b,!1)},WebSocket.prototype.close=function(){if(this.readyState==WebSocket.CLOSED||this.readyState==WebSocket.CLOSING)return;this.readyState=WebSocket.CLOSING,WebSocket.__flash.close(this.__id)},WebSocket.prototype.addEventListener=function(a,b,c){a in this.__events||(this.__events[a]=[]),this.__events[a].push(b)},WebSocket.prototype.removeEventListener=function(a,b,c){if(!(a in this.__events))return;var d=this.__events[a];for(var e=d.length-1;e>=0;--e)if(d[e]===b){d.splice(e,1);break}},WebSocket.prototype.dispatchEvent=function(a){var b=this.__events[a.type]||[];for(var c=0;c"),this.doc.close(),this.doc.parentWindow.s=this;var a=this.doc.createElement("div");a.className="socketio",this.doc.body.appendChild(a),this.iframe=this.doc.createElement("iframe"),a.appendChild(this.iframe);var c=this,d=b.util.query(this.socket.options.query,"t="+ +(new Date));this.iframe.src=this.prepareUrl()+d,b.util.on(window,"unload",function(){c.destroy()})},c.prototype._=function(a,b){a=a.replace(/\\\//g,"/"),this.onData(a);try{var c=b.getElementsByTagName("script")[0];c.parentNode.removeChild(c)}catch(d){}},c.prototype.destroy=function(){if(this.iframe){try{this.iframe.src="about:blank"}catch(a){}this.doc=null,this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,CollectGarbage()}},c.prototype.close=function(){return this.destroy(),b.Transport.XHR.prototype.close.call(this)},c.check=function(a){if(typeof window!="undefined"&&["Active"].concat("Object").join("X")in window)try{var c=new(window[["Active"].concat("Object").join("X")])("htmlfile");return c&&b.Transport.XHR.check(a)}catch(d){}return!1},c.xdomainCheck=function(){return!1},b.transports.push("htmlfile")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(){b.Transport.XHR.apply(this,arguments)}function e(){}a["xhr-polling"]=d,b.util.inherit(d,b.Transport.XHR),b.util.merge(d,b.Transport.XHR),d.prototype.name="xhr-polling",d.prototype.heartbeats=function(){return!1},d.prototype.open=function(){var a=this;return b.Transport.XHR.prototype.open.call(a),!1},d.prototype.get=function(){function b(){this.readyState==4&&(this.onreadystatechange=e,this.status==200?(a.onData(this.responseText),a.get()):a.onClose())}function d(){this.onload=e,this.onerror=e,a.retryCounter=1,a.onData(this.responseText),a.get()}function f(){a.retryCounter++,!a.retryCounter||a.retryCounter>3?a.onClose():a.get()}if(!this.isOpen)return;var a=this;this.xhr=this.request(),c.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=d,this.xhr.onerror=f):this.xhr.onreadystatechange=b,this.xhr.send(null)},d.prototype.onClose=function(){b.Transport.XHR.prototype.onClose.call(this);if(this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=e;try{this.xhr.abort()}catch(a){}this.xhr=null}},d.prototype.ready=function(a,c){var d=this;b.util.defer(function(){c.call(d)})},b.transports.push("xhr-polling")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b,c){function e(a){b.Transport["xhr-polling"].apply(this,arguments),this.index=b.j.length;var c=this;b.j.push(function(a){c._(a)})}var d=c.document&&"MozAppearance"in c.document.documentElement.style;a["jsonp-polling"]=e,b.util.inherit(e,b.Transport["xhr-polling"]),e.prototype.name="jsonp-polling",e.prototype.post=function(a){function i(){j(),c.socket.setBuffer(!1)}function j(){c.iframe&&c.form.removeChild(c.iframe);try{h=document.createElement('